I have the following method and I wrote a unit test in Java for this method. It is coveraged except from the if
statement and I also need to test this part.
@InjectMocks
private ProductServiceImpl productService;
public void demoMethod(final List<UUID> productUuidList) {
if (productUuidList.isEmpty()) {
return;
}
final Map<ProductRequest, PriceOverride> requestMap = getPriceRequests(uuidList);
productService.updateByPriceList(priceRequestMap, companyUuid);
}
However, as the method execution is finalized and does not return anything when uuidList
is empty, I cannot test this if
block.
So:
How can I test this if
block?
Should I create a new Unit Test method for testing this if
block? Or should I add related assert lines to the current test method?
Update: Here is my test method:
@Test
public void testDemoMethod() {
final UUID uuid = UUID.randomUUID();
final List<Price> priceList = new ArrayList<>();
final Price price = new Price();
price.setUuid(uuid);
priceList.add(price);
productService.demoMethod(Collections.singletonList(uuid));
}
The general idea is that you don't want to test specific code , but you want to test some behaviour .
So in your case you want to verify that getPriceRequests
and priceService.updateByPriceList
are not called when passing in an empty List
.
How exactly you do that depends on what tools you have available. The easiest way is if you already mock priceService
: then just instruct your mocking liberary/framework to verify that updateByPriceList
is never called.
The point of doing a return in your if condition is that the rest of the code is not executed. Ie, if this // code omitted for brevity
was to be executed, the method would not fill it's purpose. Therefore, just make sure that whatever that code does, it was not done if your list is empty.
You have 3 choices:
Check out Test Pyramid and How anemic architecture spoils your tests for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.