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模板网!
如何模拟超级参考(在超级类上)?How to mock super reference (on super class)?(如何模拟超级参考(在超级类上)?)
Java 模拟数据库连接Java mock database connection(Java 模拟数据库连接)
Mockito ClassCastException - 无法投射模拟Mockito ClassCastException - A mock cannot be cast(Mockito ClassCastException - 无法投射模拟)
将值设置为模拟对象但获取 nullSet value to mocked object but get null(将值设置为模拟对象但获取 null)
如何模拟 DriverManager.getConnection(...)?How to mock DriverManager.getConnection(...)?(如何模拟 DriverManager.getConnection(...)?)
模拟;使用列表调用验证方法,忽略列表中元素的Mockito; verify method was called with list, ignore order of elements in list(模拟;使用列表调用验证方法,忽略列表中元素的顺序)