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

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

问题描述

我使用 @RunWith(MockitoJUnitRunner.class) 用 mockito 进行 junit 测试.但现在我正在使用 Spring Boot 应用程序并尝试使用 @RunWith(SpringRunner.class) .使用 @RunWith(SpringRunner.class) 比使用 @RunWith(MockitoJUnitRunner.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.

但你很幸运,因为除了 runners 之外,Spring 和 Mockito 都提供了规则.

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

例如,您可以使用带有 Mockito 规则的 Spring runner,如下所示.

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) vs @RunWith(MockitoJUnitRunner.class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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