有没有一种方法可以初始化模拟并使用@ClassRule编写when()。thenReturn()语句并在不同的测试类之间共享它们

时间:2019-01-09 20:38:49

标签: unit-testing junit

我有一些要使用Junit测试的实用程序(准确地说是4个实用程序)。这些工具中的每一个都会检查某些条件是否匹配,并相应地设置布尔变量的值。

在每个这些实用程序中,我的setUp代码都用@Before标注为:

when(mockObjectA.performFunction()).thenReturn(mockObjectB);
when(mockObjectB.performDifferentFunction()).thenReturn(mockObjectC);

上面的代码在4个util类的每一个中。我想将它们移到一个普通的类中以避免冗余。

我使用@Rule注释相同。这就是它的实现方式:

@Rule
public CustomTestRules rule = new CustomTestRules();

和我的CustomTestRules类实现了TestRule接口,在这里我重写了公共Statement apply(Statement statement,Description description)方法来实现相同的效果。

我还没有在CustomTestRules中初始化模拟,但是测试工作正常。我无法弄清楚这种奇怪的行为。

我也想使用@ClassRule实现相同的目的。我阅读了@ClassRule,发现它比@Rule更有效率,因为那些语句在所有测试方法之前仅执行一次。我尝试使用@ClassRule实现相同功能,但测试方法未运行。 (甚至都无法确定测试内容)

以下是测试方法之一:

         @Test
         public void testCondition() {
             final Map<String, String> mockFilterMap = new HashMap<>();
             mockFilterMap.put(key, "someValue");
             final MyClassObject object = new MyClassObject();
             object.setKey("incorrectValue");
             when(mockObjectC.doFunction()).thenReturn(object);
             final boolean doesMatch = testingFunction(mockObjectA, mockFilterMap);
             Assert.assertFalse(doesMatch);
         }
public class CustomTestRules implements TestRule {

         @Override
         public Statement apply(Statement statement, Description description) {

             return new Statement() {
                 @Override
                 public void evaluate() {
                     //no-op
                 }
             };
          }

0 个答案:

没有答案
相关问题