問題描述
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...
}
這篇關于@Mock 和 @InjectMocks 之間的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!