Java 如何使用 Spring Autowire 编写 JUnit 测试?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21878714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write JUnit test with Spring Autowire?
提问by Premraj
Here are the files that I use:
以下是我使用的文件:
component.xml
组件.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<context:component-scan
base-package="controllers,services,dao,org.springframework.jndi" />
</beans>
ServiceImpl.java
服务实现程序
@org.springframework.stereotype.Service
public class ServiceImpl implements MyService {
@Autowired
private MyDAO myDAO;
public void getData() {...}
}
ServiceImplTest.java
ServiceImplTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:conf/components.xml")
public class ServiceImplTest{
@Test
public void testMyFunction() {...}
}
Error:
错误:
16:22:48.753 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@2092dcdb] to prepare test instance [services.ServiceImplTest@9e1be92]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'services.ServiceImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private services.ServiceImpl services.ServiceImplTest.publishedServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [services.ServiceImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) ~[spring-beans.jar:3.1.2.RELEASE]
采纳答案by Sembrano
Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;
确保您导入了正确的包。如果我没记错的话,自动装配有两个不同的包。应该 :org.springframework.beans.factory.annotation.Autowired;
Also this looks wierd to me :
这对我来说也很奇怪:
@ContextConfiguration("classpath*:conf/components.xml")
Here is an example that works fine for me :
这是一个对我来说很好用的例子:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {
@Autowired
OwnerService ownerService;
@Before
public void setup() {
ownerService.cleanList();
}
@Test
public void testOwners() {
Owner owner = new Owner("Bengt", "Karlsson", "Ankav?gen 3");
owner = ownerService.createOwner(owner);
assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
assertTrue("Check that Id exist: ", owner.getId() > 0);
owner.setLastName("Larsson");
ownerService.updateOwner(owner);
owner = ownerService.getOwner(owner.getId());
assertEquals("Name is changed", "Larsson", owner.getLastName());
}
回答by jmkgreen
I think somewhere in your codebase are you @Autowiring
the concrete class ServiceImpl
where you should be autowiring it's interface (presumably MyService
).
我认为你的代码库中的某个地方是你应该自动装配它的接口@Autowiring
的具体类ServiceImpl
(大概是MyService
)。
回答by Mohsen Msr
You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:
您应该在您的测试资源文件夹中制作另一个 XML-spring 配置文件,或者只是复制旧的,看起来不错,但是如果您尝试启动 web 上下文来测试微服务,只需将以下代码作为您的主测试类并继承自:
@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
@Autowired
private WebApplicationContext wac;
}