@RunWith(SpringRunner.class) 与 @RunWith(MockitoJUnitRunner.class) [英] @RunWith(SpringRunner.class) vs @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屋!