@Mock 和 @InjectMocks 之间的区别 [英] Difference between @Mock and @InjectMocks

查看:28
本文介绍了@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...

}

这篇关于@Mock 和 @InjectMocks 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆