lundi 15 juin 2020

Spring Boot @DataMongoTest - Assertion fails unexpectedly

I have a spring test class like this:

@DataMongoTest
@ExtendWith(SpringExtension.class)
public class UserRepositoryTest {

    @MockBean
    UserRepository repository;

    @Test
    void findByUserName() {
        // given
        User user = new User();
        user.setUsername("sysadmin");
        user.setPassword("Test1234");
        user.setRoles(Arrays.asList(new String[] {"ROLE_USER", "ROLE_ADMIN"}));

        // when
        repository.save(user);

        // then
        assertThat(repository.findByUsername("sysadmin")).isPresent();
    }
}

This test is supposed to pass given there's a dummy user saved with the mock repo. However, everytime I execute the test, I get the error message

java.lang.AssertionError: Expecting Optional to contain a value but it was empty.

In the repo interface, I have the query to return an optional of user.

Optional<User> findByUsername(@Param("username") String username);

What could be the cause to the issue? Since it's not actually saving to the db (I believe it's using a embedded in-memory mongoDB to handle the data), there's no way to tell if the save fails or the fetch query fails.

Aucun commentaire:

Enregistrer un commentaire