jUnit中的多个RunWith语句 [英] Multiple RunWith Statements in jUnit

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

问题描述

我编写单元测试,想要为一个测试类使用 JUnitParamsRunner MockitoJUnitRunner

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()与跑步者,你不能没有,并用其他东西替换其他人。在你的情况下,我猜你将删除 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);
}

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

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 case:

@Rule public MockitoRule mockitoRule = new MockitoRule();

您可以使用您想要的任何跑步者运行此测试用例。

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

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

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