简体   繁体   中英

How to test void using Unit Test?

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:

  1. How can I test this if block?

  2. 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:

  1. Write a unit test with mocks. Mockito allows you to verify() whether some method was invoked.
  2. Write a more high-level test with database. When testing Service Facade Layer this is usually a wiser choice. In this case you can obtain the resulting state of DB in your test to check whether it did what it had to.
  3. Refactor your code to work differently

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM