简体   繁体   中英

Unit Test for throw Exception in Java?

I want to create a Unit Test using JUnit in my Java app for testing the following method:

private void checkModels(PriceRequest request) {
    final UUID productUuid = menuService.findProductUuidByUuid(request.getMenuUuid());
    if (!menuRepository.existsByMenuUuidAndProductUuid(request.getMenuUuid(), productUuid)) {
        throw new EntityNotFoundException(MENU_ENTITY_NAME);
    }
}

I create the following test method:

public void shouldThrowExceptionWhenMenuUuidNotExists() {
    PriceRequest request = generatePriceRequest();

    when(!menuRepository.existsByUuid(request.getMenuUuid()))
      .thenThrow(new EntityNotFoundException(MENU_ENTITY_NAME));
}

private PriceRequest generatePriceRequest() {
    PriceRequest request = new PriceRequest();
    request.setMenuUuid(UUID.randomUUID());
    return request;
}

However, it always pass the test and I think I made a mistake regarding to setting values in the test method. So, how should I fix the problem and how should I create a unit test that method?

If you want to test if method checkModels() will throw exception when demoService.existsByMenuUuidAndProductUuid will return false then you can check it like this

private PriceRequest generatePriceRequest() {
    PriceRequest request = new PriceRequest();
    request.setMenuUuid("ABC"); // it's bad idea to always run test everytime with different values
    return request;
}


@Test(expected = NullPointerException.class)
public void shouldThrowExceptionWhenMenuUuidNotExists() {
    PriceRequest request = generatePriceRequest();

    when(demoService.existsByMenuUuidAndProductUuid(any()).thenReturn(false);
    
    SomeClass.checkModels(request);
    
}

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