@Mock 和 @InjectMocks 的区别 [英] Difference between @Mock and @InjectMocks
问题描述
@Mock
和 @InjectMocks
在 Mockito 框架中有什么区别?
What is the difference between @Mock
and @InjectMocks
in Mockito framework?
推荐答案
@Mock
创建一个模拟.@InjectMocks
创建类的一个实例,并将使用 @Mock
(或 @Spy
)注解创建的模拟注入到该实例中.
@Mock
creates a mock. @InjectMocks
creates an instance of the class and injects the mocks that are created with the @Mock
(or @Spy
) annotations into this instance.
请注意,您必须使用 @RunWith(MockitoJUnitRunner.class)
或 Mockito.initMocks(this)
来初始化这些模拟并注入它们 (JUnit 4).
Note you must use @RunWith(MockitoJUnitRunner.class)
or Mockito.initMocks(this)
to initialize these mocks and inject them (JUnit 4).
对于 JUnit 5,您必须使用 @ExtendWith(MockitoExtension.class)
.
With JUnit 5, you must use @ExtendWith(MockitoExtension.class)
.
@RunWith(MockitoJUnitRunner.class) // JUnit 4
// @ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {
@InjectMocks
private SomeManager someManager;
@Mock
private SomeDependency someDependency; // this will be injected into someManager
// tests...
}
这篇关于@Mock 和 @InjectMocks 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!