如何在 JUnit5 中使用 Mockito [英] How to use Mockito with JUnit5

查看:112
本文介绍了如何在 JUnit5 中使用 Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Mockito 和 JUnit 5 中使用注入?

How can I use injection with Mockito and JUnit 5?

在 JUnit4 中,我可以只使用 @RunWith(MockitoJUnitRunner.class) 注释.JUnit5中没有@RunWith注解?

In JUnit4 I can just use the @RunWith(MockitoJUnitRunner.class) Annotation. In JUnit5 is no @RunWith Annotation?

推荐答案

Mockito 的使用方法有很多种——我会一一介绍.

There are different ways to use Mockito - I'll go through them one by one.

使用 Mockito::mock 无论 JUnit 版本(或与此相关的测试框架)如何都有效.

Creating mocks manually with Mockito::mock works regardless of the JUnit version (or test framework for that matter).

使用 @Mock-annotation 和对 的相应调用MockitoAnnotations::initMocks创建模拟无论 JUnit 版本如何(或与此相关的测试框架,但 Java 9 可能会在此处产生干扰,具体取决于测试代码是否在模块中).

Using the @Mock-annotation and the corresponding call to MockitoAnnotations::initMocks to create mocks works regardless of the JUnit version (or test framework for that matter but Java 9 could interfere here, depending on whether the test code ends up in a module or not).

JUnit 5 具有强大的扩展模型和 Mockito最近在群/神器 ID org.mockito : mockito-junit-jupiter.

JUnit 5 has a powerful extension model and Mockito recently published one under the group / artifact ID org.mockito : mockito-junit-jupiter.

您可以通过将 @ExtendWith(MockitoExtension.class) 添加到测试类并使用 @Mock 注释模拟字段来应用扩展.来自 MockitoExtension 的 JavaDoc:

You can apply the extension by adding @ExtendWith(MockitoExtension.class) to the test class and annotating mocked fields with @Mock. From MockitoExtension's JavaDoc:

@ExtendWith(MockitoExtension.class)
public class ExampleTest {

    @Mock
    private List list;

    @Test
    public void shouldDoSomething() {
        list.add(100);
    }

}

MockitoExtension 文档 描述了其他实例化模拟的方法,例如使用构造函数注入(如果您喜欢测试类中的最终字段).

The MockitoExtension documentation describes other ways to instantiate mocks, for example with constructor injection (if you rpefer final fields in test classes).

JUnit 4 规则和运行器在 JUnit 5 中不起作用,所以 MockitoRuleMockito runner 不能使用.

JUnit 4 rules and runners don't work in JUnit 5, so the MockitoRule and the Mockito runner can not be used.

这篇关于如何在 JUnit5 中使用 Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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