Reputation:
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?
Upvotes: 0
Views: 1157
Reputation: 784
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);
}
Upvotes: 1