-1

Hi all I am completely new to spring-boot and Junit Mockito I am trying to check if my method is throwing a correct exception Below is the method from my service class

    public Optional<User> getUserByEmail(String emailaddress) {
    System.out.println("From DB");
    Optional<User> user = userDao.findByEmailAddress(emailaddress);
    user.orElseThrow(() -> new BadRequestException("User Not Found"));
    return user;
}

Below is my Test Method

    @Test
@DisplayName("TextCase to check if We are able to get Correct User")
public void getUserByEmailExceptionTest() {
    Mockito.when(userDao.findByEmailAddress("mokal006@gmail.com"))
    .thenThrow(UserNotFoundException.class);
     assertThrows(UserNotFoundException.class, () -> {
        LibraryUserDetailsService.getUserByEmail("mokal006@gmail.com");
    });
    
    
}

Now, this test is getting passed even if I am throwing the wrong exception in the actual method.

Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74
Vishal Mokal
  • 792
  • 1
  • 5
  • 22

1 Answers1

0

To understand why your test case is passing for the wrong exception type, check how assertThrows works internally. AssertThrows.java

try {
    // execute lambda expression passed in assertThrows
} catch (Throwable var5) {
    if (expectedType.isInstance(var5)) {
        // if type matches returns the exception back
        return var5; 
    }
    // ..
    // Else throws different exception
    throw new AssertionFailedError(message, var5);
}

JUnit 5 checks type of exception calling Class.isIntance(..), Class.isInstance(..) will return true even if the exception thrown is of the parent types. In your case, it's highly likely that the thrown exception is of parent types.

you can fix it by asserting on Class.

Throwable throwable =  assertThrows(Throwable.class, () -> {
    LibraryUserDetailsService.getUserByEmail("mokal006@gmail.com");
});
assertEquals(UserNotFoundException.class, throwable.getClass());

or by using solutions from here JUnit 5: How to assert an exception is thrown?

[EDIT]

As pointed out by johanneslink in comments, user.orElseThrow will be never executed. userDao.findByEmailAddress(...) will throw UserNotFoundException as there is no catch block exception will be propagated back to the caller hence BadRequestException won't be thrown and test case will always pass.

Govinda Sakhare
  • 5,009
  • 6
  • 33
  • 74