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

查看:1860
本文介绍了如何在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.

手动创建模拟< a href =http://static.javadoc.io/org.mockito/mockito-core/2.2.28/org/mockito/Mockito.html#mock(java.lang.Class) =noreferrer> 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
to 创建模拟无论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);
    }
}

Mockito文档对扩展程序仍然保持沉默。

The Mockito documentation is still a little silent on the extension.

JUnit 4规则和跑步者在JUnit 5中不起作用,所以 MockitoRule Mockito 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天全站免登陆