我想将Mockito模拟对象注入到Spring (3+) bean中,以便使用JUnit进行单元测试。我的bean依赖项目前是通过在私有成员字段上使用@Autowired注释注入的。

我考虑过使用ReflectionTestUtils。setField,但是我希望注入的bean实例实际上是一个代理,因此没有声明目标类的私有成员字段。我不希望为依赖项创建公共setter,因为我将纯粹为了测试目的而修改我的接口。

我遵循了Spring社区提供的一些建议,但模拟没有被创建,自动连接失败:

<bean id="dao" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="com.package.Dao" />
</bean>

我目前遇到的错误如下:

...
Caused by: org...NoSuchBeanDefinitionException:
    No matching bean of type [com.package.Dao] found for dependency:
    expected at least 1 bean which qualifies as autowire candidate for this dependency.
    Dependency annotations: {
        @org...Autowired(required=true),
        @org...Qualifier(value=dao)
    }
at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901)
at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770)

如果我将constructor-arg值设置为无效的值,那么在启动应用程序上下文时就不会出现错误。


当前回答

看看springingckito的开发速度和开放问题的数量,我现在有点担心把它引入我的测试套件堆栈。事实上,上一个版本是在Spring 4发布之前发布的,这带来了一些问题,比如“是否可以轻松地将它与Spring 4集成?”我不知道,因为我没试过。如果我需要在集成测试中模拟Spring bean,我更喜欢纯Spring方法。

有一个选项可以使用简单的Spring特性来伪造Spring bean。你需要使用@Primary, @Profile和@ActiveProfiles注解。我就这个话题写了一篇博客。

其他回答

如果您正在使用Spring Boot 1.4,它有一种很棒的方式来实现这一点。只需要在你的类上使用新品牌@SpringBootTest,在字段上使用@MockBean, SpringBoot就会创建一个这种类型的mock,并将它注入到上下文中(而不是注入原来的那个):

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {

    @MockBean
    private RemoteService remoteService;

    @Autowired
    private Reverser reverser;

    @Test
    public void exampleTest() {
        // RemoteService has been injected into the reverser bean
        given(this.remoteService.someCall()).willReturn("mock");
        String reverse = reverser.reverseSomeCall();
        assertThat(reverse).isEqualTo("kcom");
    }

}

另一方面,如果你没有使用Spring Boot,或者你使用的是以前的版本,你将不得不做更多的工作:

创建一个@Configuration bean,将模拟对象注入Spring上下文:

@Configuration
@Profile("useMocks")
public class MockConfigurer {

    @Bean
    @Primary
    public MyBean myBeanSpy() {
        return mock(MyBean.class);
    }
}

使用@Primary注释可以告诉spring,如果没有指定限定符,则该bean具有优先级。

确保您用@Profile(“useMocks”)注释了类,以便控制哪些类将使用模拟,哪些类将使用真正的bean。

最后,在你的测试中,激活userMocks配置文件:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest
@ActiveProfiles(profiles={"useMocks"})
public class YourIntegrationTestIT {

    @Inject
    private MyBean myBean; //It will be the mock!


    @Test
    public void test() {
        ....
    }
}

如果你不想使用mock而是真正的bean,就不要激活useMocks配置文件:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest
public class AnotherIntegrationTestIT {

    @Inject
    private MyBean myBean; //It will be the real implementation!


    @Test
    public void test() {
        ....
    }
}

为了记录,我所有的测试都是通过使fixture惰性初始化来正确工作的,例如:

<bean id="fixture"
      class="it.tidalwave.northernwind.rca.embeddedserver.impl.DefaultEmbeddedServer"
      lazy-init="true" /> <!-- To solve Mockito + Spring problems -->

<bean class="it.tidalwave.messagebus.aspect.spring.MessageBusAdapterFactory" />

<bean id="applicationMessageBus"
      class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="it.tidalwave.messagebus.MessageBus" />
</bean>

<bean class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="javax.servlet.ServletContext" />
</bean>

我认为基本原理是Mattias在这里(在文章的底部)解释的,一种变通方法是改变bean的声明顺序——延迟初始化是“某种程度上”在最后声明fixture。

今天,我发现在Mockito bean之前声明的spring上下文无法加载。 移动After模拟后,应用程序上下文被成功加载。 保重:)

自从1.8.3 Mockito有了@InjectMocks——这是非常有用的。我的JUnit测试是@RunWith MockitoJUnitRunner,我构建了@Mock对象,它满足被测试类的所有依赖关系,当私有成员被@InjectMocks注释时,这些依赖关系都被注入。

我现在只使用SpringJUnit4Runner进行集成测试。

我将注意到,它似乎不能以与Spring相同的方式注入List<T>。它只寻找满足List的Mock对象,而不会注入Mock对象列表。我的解决方法是对一个手动实例化的列表使用@Spy,并手动将模拟对象添加到该列表中进行单元测试。也许这是故意的,因为它确实迫使我密切关注被嘲笑的是什么。

我使用了Markus T在回答中使用的方法和ImportBeanDefinitionRegistrar的一个简单助手实现的组合,该实现查找一个自定义注释(@MockedBeans),可以在其中指定要模拟哪些类。我相信这种方法的结果是简洁的单元测试,删除了一些与模拟相关的样板代码。

下面是使用这种方法的单元测试示例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class ExampleServiceIntegrationTest {

    //our service under test, with mocked dependencies injected
    @Autowired
    ExampleService exampleService;

    //we can autowire mocked beans if we need to used them in tests
    @Autowired
    DependencyBeanA dependencyBeanA;

    @Test
    public void testSomeMethod() {
        ...
        exampleService.someMethod();
        ...
        verify(dependencyBeanA, times(1)).someDependencyMethod();
    }

    /**
     * Inner class configuration object for this test. Spring will read it thanks to
     * @ContextConfiguration(loader=AnnotationConfigContextLoader.class) annotation on the test class.
     */
    @Configuration
    @Import(TestAppConfig.class) //TestAppConfig may contain some common integration testing configuration
    @MockedBeans({DependencyBeanA.class, DependencyBeanB.class, AnotherDependency.class}) //Beans to be mocked
    static class ContextConfiguration {

        @Bean
        public ExampleService exampleService() {
            return new ExampleService(); //our service under test
        }
    }
}

要做到这一点,您需要定义两个简单的助手类——自定义注释(@MockedBeans)和自定义 ImportBeanDefinitionRegistrar实现。@MockedBeans注释定义需要使用@Import(CustomImportBeanDefinitionRegistrar.class)进行注释,并且ImportBeanDefinitionRgistrar需要在它的registerBeanDefinitions方法中将模拟bean定义添加到配置中。

如果你喜欢这种方法,你可以在我的博客上找到示例实现。