@RunWith(SpringRunner.class)与@RunWith(MockitoJUnitRunner.class) [英] @RunWith(SpringRunner.class) vs @RunWith(MockitoJUnitRunner.class)

查看:989
本文介绍了@RunWith(SpringRunner.class)与@RunWith(MockitoJUnitRunner.class)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用@RunWith(MockitoJUnitRunner.class)进行我的Mockito的junit测试.但是现在我正在使用Spring Boot应用程序并尝试使用@RunWith(SpringRunner.class).与使用@RunWith(MockitoJUnitRunner.class)相比,使用@RunWith(SpringRunner.class)有什么优势吗?我是否仍可以将@Injectmock@Mock@Spy之类的功能与@RunWith(SpringRunner.class)

I was using @RunWith(MockitoJUnitRunner.class) for my junit test with mockito. But now i am working with spring boot app and trying to use @RunWith(SpringRunner.class) . Does using @RunWith(SpringRunner.class) has any advantages over using @RunWith(MockitoJUnitRunner.class)? Can i still use feature like @Injectmock, @Mock, @Spy with @RunWith(SpringRunner.class)

推荐答案

SpringRunner提供了对加载Spring ApplicationContext并将bean @Autowired放入测试实例的支持. 实际上,它的功能远不止这些(在Spring参考手册中有介绍),但这是基本思想.

The SpringRunner provides support for loading a Spring ApplicationContext and having beans @Autowired into your test instance. It actually does a whole lot more than that (covered in the Spring Reference Manual), but that's the basic idea.

MockitoJUnitRunner提供了使用Mockito创建模拟和间谍的支持.

Whereas, the MockitoJUnitRunner provides support for creating mocks and spies with Mockito.

但是,在JUnit 4中,一次只能使用一个Runner.

However, with JUnit 4, you can only use one Runner at a time.

因此,如果您想同时使用Spring和Mockito的支持,则只能选择其中的一个.

Thus, if you want to use support from Spring and Mockito simultaneously, you can only pick one of those runners.

但是您很幸运,因为Spring和Mockito都提供了 runners 之外的 rules .

But you're in luck since both Spring and Mockito provide rules in addition to runners.

例如,您可以按如下所示将Spring Runner与Mockito规则一起使用.

For example, you can use the Spring runner with the Mockito rule as follows.

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

    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    MyService myService;

    // ...
}

但是,通常,如果您使用的是Spring Boot,并且需要从Spring ApplicationContext中模拟 bean ,则可以使用Spring Boot的@MockBean支持而不是简单的@Mock.

Though, typically, if you're using Spring Boot and need to mock a bean from the Spring ApplicationContext you would then use Spring Boot's @MockBean support instead of simply @Mock.

这篇关于@RunWith(SpringRunner.class)与@RunWith(MockitoJUnitRunner.class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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