如何模拟bean并避免NoUniqueBeanDefinitionException

Biz*_*4ik 2 java spring spring-mvc

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

1)为测试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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

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

Nán*_*ete 5

您可以为Spring应用程序定义配置文件,并将您的@Configuration类或@Bean方法(如果使用任何内容,甚至是自定义元注释)绑定到命名配置文件,甚至可以根据需要绑定多个配置文件.然后,你可以用名称来定义配置文件test,development,production或任何自定义场景涉及到你的头脑,并已注册到你的Spring上下文的豆基于当前活动的配置文件(S).

定义你的bean两者的testanotherTest轮廓是这样的:

@Configuration
@Profile({"test", "anotherTest"})
public class SomeConfig {...}
Run Code Online (Sandbox Code Playgroud)

或者在xml文件中:

...
<beans profile="test, anotherTest">
    <bean .../>
</beans>
...
Run Code Online (Sandbox Code Playgroud)

production以类似的方式定义受限bean,以避免配置文件中的bean冲突.然后,使用@ActiveProfilesJUnit测试类上的注释指示在运行测试时要激活的配置文件:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(...)
@ActiveProfiles({"test", "anotherTest"})
Run Code Online (Sandbox Code Playgroud)

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