@Mock 和 @InjectMocks 之间的区别
Mockito框架中的@Mock
和@InjectMocks
有什么区别?
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...
}
相关文章