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

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

问题描述

我正在使用 @RunWith(MockitoJUnitRunner.class) 进行带有 mockito 的 junit 测试.但现在我正在使用 spring boot 应用程序并尝试使用 @RunWith(SpringRunner.class) .使用 @RunWith(SpringRunner.class) 是否比使用 @RunWith(MockitoJUnitRunner.class) 有任何优势?我还能在 @RunWith(SpringRunner.class) 中使用 @Injectmock@Mock@Spy 等功能吗?

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 和拥有 beans @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 都提供 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天全站免登陆