首页 > 解决方案 > 如何使用 JUnit/Mockito 模拟一个值以在另一种方法中测试条件?

问题描述

我是 JUnit 和 Mockito 的新手,并且正在努力尝试模拟从布尔方法返回的值以命中条件。

我已经尝试过这篇文章的答案,但似乎对此不起作用。我试过用spy,然后CallRealMethod,想不通。

我已经测试了该值何时为真,但我似乎无法进入测试的 else 部分。

这是我所做的一个例子:

ServiceImpl.java 有一个方法 register(),它调用一个布尔方法 shouldRegister()。shouldRegister() 方法只是检查另一个服务以查看布尔值是真还是假,然后返回。

如果为 true,它会构建一个 JsonNode 有效负载来发送,否则,如果为 false,它会从有效负载中删除一个字段。

// ServiceImpl.java:

// in the record() method: 

if (body.has("fieldtoBeRemoved")) {
   if (shouldRegister()) {
      ((ObjectNode) body).set("fieldtoBeRemoved");
    } else {
       // this is the line I am trying to test
       ((ObjectNode) body).remove("fieldtoBeRemoved");
       }
   }

// method being called above in the conditional
protected boolean shouldRegister() {
        Optional<String> flag = configService.getString("booleanValue");
        String stringFlag = flag.orElse("false");
        return BooleanUtils.toBoolean(stringFlag);
    }


// In the test

@InjectMocks
private ServiceImpl serviceImpl;

@Test
public void testingForFalse() {
     serviceImpl = new ServiceImpl();

     // what I am struggling with, trying to make the value false,
     // so that it hits the else in the record() method in ServiceImpl
    // and removes fieldtoBeRemoved from the payload
    when(serviceImpl.shouldRegister()).thenCallRealMethod();
   doReturn(false).when(spy(serviceImpl)).shouldRegister();

    assertThat(fieldtoBeRemoved, is(""));

}


当我运行它时,它失败了,因为 fieldtoBeRemoved 的值不为空,它具有负载中字段的值,它不应该具有。我猜这个值仍然返回为真,因为我没有正确地模拟它/将它设置为这个测试用例的假。我也尝试过模拟对 record() 方法的调用。任何帮助表示赞赏!

标签: javajunitmockingmockitojunit4

解决方案


shouldRegister如果源和测试在同一个包中并且至少是包私有的,你可以这样做

@Test
public void testingForFalse() {
    serviceImpl = new ServiceImpl() {
        @Override
        public boolean shouldRegister() {
            return false;
        }
    }

    // rest of the test
}

在这种情况下,您不需要对此方法进行任何模拟。


推荐阅读