繁体   English   中英

Spring bean Autowire用于测试

[英]Spring bean autowire for testing

我有很多关于该自动接线的春季服务:

@Autowired
private SmartCardService smartCardService;

我需要一个虚拟类进行测试,并且定义了扩展原始类的此类:

@Service
public class DummySmartCardService extends SmartCardService{
    ...
}

我如何确定所有自动装配都将使用虚拟对象而不是原始服务,而不更改所有自动装配注释?

谢谢。

考虑使用@Primary批注。 这里

DummySmartCardService从应用程序上下文文件的测试版本加载DummySmartCardService bean,这样就无需更改测试代码。

@ContextConfiguration(locations = {"classpath:test-services.xml"})

使用@Resource批注或@Qualifier和@Qualifier来区分Bean类型:

@Autowired
@Qualifier("testing")
private SmartCardService smartCardService;

@Service
@Qualifier("testing")
public class DummySmartCardService extends SmartCardService{
    ...
}

或使用使用名称语义的@Resource:

@Resource("dummySmartCardService")
private SmartCardService smartCardService;


@Service("dummySmartCardService")
public class DummySmartCardService extends SmartCardService{
    ...
}

从理论上讲,您可以使用@Qualifier("beanName")但不建议使用。

但是,如果您有一个Spring配置文件以仅在测试中加载与测试相关的存根,那会更好:

@Service
@Profile("test")
public class DummySmartCardService extends SmartCardService{
    ...
}

@ContextConfiguration(locations = {"classpath:services.xml"})    
@ActiveProfiles("test")
public class TestSuite{
    @Autowired
    private SmartCardService smartCardService;
}

恕我直言,您应该看一下Springockio,以正确,轻松地模拟 Spring bean。

您可以通过以下方式将bean替换为模拟对象或将其包装为Spy:

@ContextConfiguration(loader = SpringockitoContextLoader.class,
locations = "classpath:/context.xml")
public class SpringockitoAnnotationsMocksIntegrationTest extends 
                                AbstractJUnit4SpringContextTests {

    @ReplaceWithMock
    @Autowired
    private InnerBean innerBean;

    @WrapWithSpy
    @Autowired
    private AnotherInnerBean anotherInnerBean;
    ....
}

这不仅是一种干净的方法(您不需要通过添加限定符或配置文件来更改正在测试的代码),而且还允许您使用Mockito的功能来进行模拟 ,验证和监视,这非常好。

暂无
暂无

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

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