Home > front end >  How can i unit test exception thrown in lambda?
How can i unit test exception thrown in lambda?

Time:09-09

I am have a method:

    public UserEntity authentication(final UserEntity auth)
        throws AuthenticationException, EmailNotFoundException {
        final AtomicReference<UserEntity> atomic = new AtomicReference<>();
        this.repository
            .findByEmail(auth.getEmail())
            .ifPresentOrElse(
                usr -> {
                    if (Objects.equals(usr.getPassword(), auth.getPassword())) {
                        atomic.set(usr);
                    } else {
                        throw new AuthenticationException();
                    }
                },
                () -> {
                    throw new EmailNotFoundException(auth.getEmail());
                }
            );
        return atomic.get();
    }

This is what the user authorization test looks like:

    @Test
    void userAuthentication_success() {
        given(this.repository.findByEmail(this.user.getEmail()))
            .willReturn(Optional.of(this.user));
        assertThat(this.underTest.authentication(this.user))
            .isInstanceOf(UserEntity.class)
            .isEqualTo(this.user);
        verify(this.repository)
            .findByEmail(this.user.getEmail());
    }

Is there any way to check the case when a user has entered the wrong password? Because in the case when I send the wrong password, it doesn't work because given(this.repository.findByEmail(this.user.getEmail())).willReturn(Optional.of(this.user)); makes repository.findByEmail() return the result before you get to checking the password.

CodePudding user response:

First of all I would refactor your code to avoid side-effects:

public UserEntity authentication(final UserEntity auth)
    throws AuthenticationException, EmailNotFoundException {
    return this.repository
        .findByEmail(auth.getEmail())
        .map(usr -> {
           if (!Objects.equals(usr.getPassword(), auth.getPassword())) {
               throw new AuthenticationException();
           }
           return usr;
        }).orElseThrow(() -> { throw new EmailNotFoundException(auth.getEmail()); });
}

Then, I don't see an issue with mocking this.repository.findByEmail, I just think you made it return a valid user with the correct password. Something like:

given(this.repository.findByEmail(this.user.getEmail())).willReturn(Optional.of(this.user.withPassword("wrong password")));
  • Related