弹簧单元测试

时间:2016-08-05 17:57:44

标签: java spring spring-mvc spring-boot

当我将应用程序作为Spring Boot应用程序启动时,ServiceEndpointConfig会正确地自动装配。但是当我作为Junit测试运行时,我得到以下异常。我正在使用application.yml文件和不同的配置文件。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyServiceContextConfig.class, 
loader = SpringApplicationContextLoader.class) 
@ActiveProfiles({"unit", "statsd-none"})
public class MyServiceTest
{
}

@Configuration
public class MyServiceContextConfig {

    @Bean
    public MyService myServiceImpl(){
        return new MyServiceImpl();
    }
}

@Configuration
@Component
@EnableConfigurationProperties
@ComponentScan("com.myservice")
@Import({ServiceEndpointConfig.class})
public class MyServiceImpl implements MyService {

   @Autowired
   ServiceEndpointConfig serviceEndpointConfig;

}

@Configuration
@Component
@ConfigurationProperties(prefix="service")
public class ServiceEndpointConfig
{
}

错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myServiceImpl': 
Unsatisfied dependency expressed through field 'serviceEndpointConfig': No qualifying bean of type [com.myservice.config.ServiceEndpointConfig] found 

1 个答案:

答案 0 :(得分:2)

您不一致地处理MyServiceImpl:一方面,您正在使用扫描注释,另一方面,您在配置类中明确创建@Bean。只有当Spring通过扫描选择MyServiceImpl时,才会处理import指令;否则,它不被视为配置。

你们之间的关系纠结在一起;依赖注入的整个要点是MyServiceImpl应该说它需要什么样的东西而不是自己创建它。这个组织并不比在内部手动创建依赖项更好。

相反,

  • @Configuration
  • 中删除@ImportMyServiceImpl指令
  • MyServiceImpl
  • 上使用构造函数注入
  • 更改您的测试配置以包含所有必需的配置类。

使用构造函数注入,您可以完全绕过Spring上下文,并通过创建new MyServiceImpl(testServiceConfig)将其作为实际的单元测试运行。