如何模拟bean并避免NoUniqueBeanDefinitionException

时间:2016-01-17 22:36:36

标签: java spring spring-mvc

我有基于SpringMVC的webApplication,所有bean都通过注释来定义。今天我尝试为我的控制器编写测试。我把第一个,并试图模拟在这个控制器中使用的服务。我通过以下方式做了所有这些:

1)为test clientControllerTest-context.xml

创建上下文文件
<import resource="classpath:spring-context.xml" />

<bean id="ConnectionDB" name="ConnectionDB" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="biz.podoliako.carwash.services.impl.ConnectDB" />
</bean>

其中 spring-context.xml 是我的webApplication中使用的主要上下文文件(包括真正的ConnectionDB bean 的信息)

2)使用以下配置创建测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:controllers/clientControllerTest-context.xml"})
@WebAppConfiguration

运行测试时,捕获了 NoUniqueBeanDefinitionException exeption。我希望spring覆盖bean ConnectionDB,但事实上它发现了两个有一个名字的bean,而spring却无法选择哪一个必须使用。

请解释一下我如何使用我的主要spring-context并模拟其中一个bean进行测试,并避免NoUniqueBeanDefinitionException,如果可能的话。

注意:我认为使用所有配置进行测试创建上下文是一个坏主意,因此我尝试使用我的主要弹簧上下文。

1 个答案:

答案 0 :(得分:5)

您可以为Spring应用定义配置文件,并将href类或@Configuration方法(如果您使用任何方法,甚至自定义元注释)绑定到命名个人资料,如果你想要甚至多个资料。然后,您可以定义名称为@Beantestdevelopment的配置文件或您想到的任何自定义方案,并根据当前活动的配置文件将您的bean注册到Spring上下文(s )。

productiontest配置文件定义您的bean,如下所示:

anotherTest

或者在xml文件中:

@Configuration
@Profile({"test", "anotherTest"})
public class SomeConfig {...}

以类似的方式定义... <beans profile="test, anotherTest"> <bean .../> </beans> ... 受限制的bean,以避免配置文件中的bean冲突。然后,在JUnit测试类上使用production注释来指示在运行测试时要激活的配置文件:

@ActiveProfiles

如果您想以编程方式执行此操作,请参阅另一个问题Default profile in Spring 3.1,了解如何在webapp中默认激活配置文件,或者org.springframework.core.env.Environment的javadoc。