自动装配实现相同接口的bean-如何在JUnit测试中自动装配特定的依赖bean? [英] Autowiring beans implementing same interface - how to autowire a particular dependency bean in a JUnit Test?

查看:110
本文介绍了自动装配实现相同接口的bean-如何在JUnit测试中自动装配特定的依赖bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring 3.1/Java/Tomcat应用程序.我有一个如下的服务类:

I have a Spring 3.1/Java/Tomcat application. I have a service class that is as follows:

public class SomeServiceImpl implements SomeService {

  @Autowired
  public AnotherService anotherService;

  //  other code...

这将使用另一个自动连接的服务类AnotherService.这两个服务类都在serviceContext.xml文件中声明.

This uses another service class AnotherService which is autowired. Both these services classes are declared in a serviceContext.xml file.

我正在编写junit来测试SomeServiceImpl,并使用自动装配功能注入被测类(SomeService)以及被测类(AnotherService)所需的模拟(EasyMock)依赖项.另一个服务的easymock依赖项在testContext.xml中定义,如下所示:

I am writing junit to test SomeServiceImpl and use autowired to inject the class under test (SomeService) as well as the mock (EasyMock) dependency required by class under test (AnotherService). The easymock dependency for AnotherService is defined in a testContext.xml like below:

    <bean id="mockAnotherService" class="org.easymock.EasyMock" factory-method="createMock" primary="true">
        <constructor-arg value="com.xyz.AnotherService" />
    </bean>

在测试类中,我配置为使用两个上下文文件.但是,我看到ServiceImpl已正确连接到实际的实现(这是所需要的),但不是连接了另一个服务的模拟版本,而是连接了concreate版本(AnotherServiceImpl).

In my test class I configure to use both the context files. However, I am seeing that the ServiceImpl is correctly wired to the actual implementation (this is desired) but instead of mock version of AnotherService the concreate version (AnotherServiceImpl) is getting wired.

我该如何获取依赖关系的模拟版本?我不能在实际的实现中使用@Resource或@Qualifier,因为那样会达到目的.我可以在测试课程中使用它们.

How do I get the mocked version of my dependency wired instead? I can not use @Resource or @Qualifier in the actual implementation as that would defeat the purpose. I am ok to use these in my test class.

推荐答案

如果它们都在serviceContext.xml中声明,并且您要模拟其中之一,则该文件无用进行测试.要么对其进行拆分,以便可以将其中一个真实的" Spring上下文文件与包含该模拟的测试上下文结合使用,或者仅手动创建bean并使用setter方法设置AnotherService.控制反转的优点之一是允许您手动创建bean并以这种方式注入依赖项.

If they're both declared in serviceContext.xml, and you want to mock one of them, then that file is no use for testing. Either split it so that you can use one of the 'real' Spring context files combined with a test context containing the mocks, or just create the bean manually and set the AnotherService using a setter method. One of the advantages of Inversion of Control is to allow you to create beans by hand and inject the dependencies that way.

这篇关于自动装配实现相同接口的bean-如何在JUnit测试中自动装配特定的依赖bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆