简体   繁体   English

使用@Autowired为Spring @Service添加JUnit测试

[英]Add JUnit test with @Autowired for Spring @Service

I've checked all other posts and blogs/wikis about this topic, but there's still something wrong with our project setup. 我已经检查了有关此主题的所有其他帖子和博客/ Wiki,但是我们的项目设置仍然存在问题。

There's project ParentProject and there are multiple subprojects. 有项目ParentProject ,并且有多个子项目。 For this specific problem, we take API and WS into consideration. 对于此特定问题,我们考虑了APIWS

There's an interface Service (annotated as @WebService and @SOAPBinding ) declared in the API , and its implementation is in WS (annotated as @WebService and @Service ). API声明了一个接口Service (标注为@WebService@SOAPBinding ),其实现在WS (标注为@WebService@Service )。

When trying to implement a JUnit test for this implementation, for some reason maven clean install (in Eclipse) ends in BUILD FAILURE 尝试为此实现实现JUnit测试时,出于某种原因,(在Eclipse中) maven clean installBUILD FAILURE结尾

Some of the problems encountered: 遇到的一些问题:

Could not find an 'annotation declaring class' for annotation type [interface org.springframework.test.context.ActiveProfiles] and class [class com.x.ws.services.x.ServiceTest]
java.lang.NullPointerException
...
After test class: context [[TestContext@c0843d testClass = ServiceImplTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@2e0dcb testClass = ServiceImplTest, locations = '{classpath:spring-config-business-test.xml}', classes = '{}', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], dirtiesContext [false].
java.lang.NullPointerException
...
Caught exception while allowing TestExecutionListener 
[org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1bcdc8] to prepare test instance [com.x.ws.services.x.ServiceImplTest@5d285b]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.x.ws.services.x.ServiceImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.x.api.services.x.Service com.x.ws.services.x.ServiceImplTest.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.x.api.services.x.Service] 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)}

This is the current ServiceImplTest : 这是当前的ServiceImplTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
        locations = {
//                "classpath:spring-config-business.xml",
//                "classpath:spring-config-business-cxf.xml",
//                "classpath:dozer-config.xml"//,
                "classpath:spring-config-business-test.xml"
        })
//        classes = Service.class)
//@ComponentScan("com.<service_package>")
//@TestExecutionListeners({
    //org.springframework.test.context.support.DependencyInjectionTestExecutionListener.class,
    //org.springframework.test.context.support.DirtiesContextTestExecutionListener.class,
    //org.springframework.test.context.transaction.TransactionalTestExecutionListener.class
    })
//@Profile("test")
public class ServiceImplTest {

    @Autowired
    private Service service;
...
}

This is the spring-config-business-test.xml 这是spring-config-business-test.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>

    <!-- Allow @Autowired Annotation -->
    <context:annotation-config/>

    <context:component-scan base-package="com.x.api"></context:component-scan>    
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
        p:driverClassName="${jdbcDriverDB2.className}"
        p:url="${testDataSource.url}"
        p:username="${testDataSource.user}"
        p:password="${testDataSource.password}"
        p:suppressClose="true" />

</beans>

It is not working when using @Autowired , and it does compile when not using it. 使用@Autowired ,它不起作用,不使用时,它会编译。

UPDATE: 更新:

After investigating and following instructions given in comments, I've noticed that the log is showing multiple java.lang.NullPointerException , after those messages (for another beans): 在调查并遵循注释中给出的说明之后,我注意到该日志在这些消息之后(对于另一个bean)显示了多个java.lang.NullPointerException

Creating shared instance of singleton bean 'x'
...
Processing injected method of bean 'x': AutowiredFieldElement for private package.ws.y package.ws.y.x

Tests are also not compiling whenever there's an @Autowired private field (no matter which one and even for ApplicationContext ) in the ServiceImplTest . 每当ServiceImplTest存在@Autowired私有字段(无论是哪个,甚至是ApplicationContext )时,测试也不会编译。

Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1c1fbd9] to prepare test instance [package.ws.services.x.ServiceImplTest@16f2b7f]
java.lang.IllegalStateException: Failed to load ApplicationContext

UPDATE2: UPDATE2:

I tried what @Louis Steimberg mentioned (without defining the loader) and now I get 我尝试了@Louis Steimberg提到的内容(未定义加载程序),现在我得到了

testFunction(package.ws.services.x.ServiceImplTest): Error creating bean with name 'packge.ws.services.x.ServiceImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private package.ws.services.x.ServiceTest package.ws.services.x.ServiceImplTest.serviceTest; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [package.ws.services.x.ServiceTest] 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)}

It looks like it can't create the bean for some reason. 似乎由于某种原因无法创建Bean。

You should add this param to your @ContextConfiguration annotation : 您应该将此参数添加到@ContextConfiguration批注中:

@ContextConfiguration(
    classes = {TestConfig.class },
    loader = AnnotationConfigWebContextLoader.class
    )

and in TestConfig.class : 并在TestConfig.class中:

@Configuration
@ComponentScan(basePackages = "com.your.component.package1, com.your.component.package2")
public class TestConfig {

// You can put some beans here

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM