本文介绍了jUnit 中的多个 RunWith 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写单元测试并希望将 JUnitParamsRunnerMockitoJUnitRunner 用于一个测试类.

I write unit test and want to use JUnitParamsRunner and MockitoJUnitRunner for one test class.

不幸的是,以下方法不起作用:

Unfortunately, the following does not work:

@RunWith(MockitoJUnitRunner.class)
@RunWith(JUnitParamsRunner.class)
public class DatabaseModelTest {
  // some tests
}

有没有办法在一个测试类中同时使用 Mockito 和 JUnitParams?

Is there a way to use both, Mockito and JUnitParams in one test class?

推荐答案

你不能这样做,因为根据规范你不能在同一个带注释的元素上放置两次相同的注释.

You cannot do this because according to spec you cannot put the same annotation twice on the same annotated element.

那么,解决方案是什么?解决方案是只将一个 @RunWith() 与 runner 一起放置,然后用其他东西替换另一个.在您的情况下,我猜您将删除 MockitoJUnitRunner 并以编程方式执行它的操作.

So, what is the solution? The solution is to put only one @RunWith() with runner you cannot stand without and replace other one with something else. In your case I guess you will remove MockitoJUnitRunner and do programatically what it does.

事实上,它唯一能做的就是运行:

In fact the only thing it does it runs:

MockitoAnnotations.initMocks(test);

在测试用例的开头.所以,最简单的办法就是把这段代码放到setUp()方法中:

in the beginning of test case. So, the simplest solution is to put this code into setUp() method:

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

我不确定,但可能您应该避免使用标志多次调用此方法:

I am not sure, but probably you should avoid multiple call of this method using flag:

private boolean mockInitialized = false;
@Before
public void setUp() {
    if (!mockInitialized) {
        MockitoAnnotations.initMocks(this);
        mockInitialized = true;
    }
}

然而,使用 JUnt 的规则可以实现更好的、可重用的解决方案.

However better, reusable solution may be implemented with JUnt's rules.

public class MockitoRule extends TestWatcher {
    private boolean mockInitialized = false;

    @Override
    protected void starting(Description d) {
        if (!mockInitialized) {
            MockitoAnnotations.initMocks(this);
            mockInitialized = true;
        }
    }
}

现在只需将以下行添加到您的测试类中:

Now just add the following line to your test class:

@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

并且您可以使用您想要的任何运行程序运行此测试用例.

and you can run this test case with any runner you want.

这篇关于jUnit 中的多个 RunWith 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:52