mockito 如何为if条件编写此void方法的测试用例

2lpgd968  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(278)
public void setRefundIdForPrepaid(RefundReturnRequest refundReturnRequest) { 
    if(StringUtils.isBlank (refundReturnRequest.getRefundRequest().getRefundId())) {
        refundReturnRequest.getRefundRequest().setRefundId (Integer.toString(ThreadLocalRandom.current().nextInt(999999999)));
    }
}
oxf4rvwz

oxf4rvwz1#

您可以在方法执行后测试RefundReturnRequest refundReturnRequest

@Test
void testSetRefundIdForPrepaid(){
   //build param
   RefundReturnRequest refundReturnRequest = new RefundReturnRequest();
   //executetd
   service.setRefundIdForPrepaid(refundReturnRequest);
   //test result
   assertThat(refundReturnRequest.getRefundRequest().getRefundId()).isEqualTo(xxx);
}
ao218c7q

ao218c7q2#

您可以将RefundReturnRequest设为Spy并验证set是否被调用。如果您想进一步测试它,您可以传递一个Argument Captor并检查随机数是否在某个范围内。但我认为这种方法在测试中没有太大价值。如果您只想为If逻辑编写两个测试用例,只需验证set方法是否被调用,并在它没有被调用的情况下进行另一个测试。我没打过电话。
因此,您需要一个在调用getRefundRequest之后返回Spy RefundRequest的Mock refundReturnRequest,并验证setter。

ev7lccsx

ev7lccsx3#

@Test
void TestsetRefundIdForPrepaid(){
//test case
}

相关问题