1

I want to test the registration method of my UserService, which looks something like the below.

@Transactional
override fun register(userRegistration: UserRegistration): AuthDto {
    val user = userRegistration.toUserEntity()
    return try {
        val entity = userRepository.save(user)
        //entityManager.flush()
        val id = entity.getIdOrThrow().toString()
        val jwt = jwtService.createJwt(id)
        entity.toAuthDto(jwt)
    } catch (ex: PersistenceException) {
        throw UserRegistrationException(userRegistration.username, ex)
    }
}

Since there is a unique index on the userName of the User entity, I would like to assert that an exception is thrown when an already existing userName is registered. In this case I try to catch whatever exception is thrown and rethrow my own.

Now my test simply takes an existing userName and calls register.

@Test fun `register twice - should throw`() {
    val existingRegistration = UserRegistration(testUserAdminName, "some", "test")

    assertThrows<UserRegistrationException> {
        userService.register(existingRegistration)
        //entityManager.flush()
    }
}

However, no exception is ever thrown, unless I explicitly flush via the entity manager. But then how can I throw my own exception?

Should I use flush in my UserService?

avolkmann
  • 2,962
  • 2
  • 19
  • 27
  • 1
    Flushing is done on commit and that is also where the exception is being thrown. So if you want to directly get an exception you will have to call `saveAndFlush` instead of `save` (assuming you are using the `JpaRepository` as a base for your own repository). – M. Deinum May 23 '20 at 09:57
  • Am using `CrudRepository`. There is not `saveAndFlush` here. – avolkmann May 23 '20 at 09:58
  • 2
    Use `JpaRepository` instead (which is a specialization of `CrudRepository` and adds some JPA specific methods, like `saveAndFlush`). – M. Deinum May 23 '20 at 10:00
  • 1
    @M.Deinum thanks, this seems to work fine. Feel free to write an actual answer so I can mark this as solved. – avolkmann May 23 '20 at 10:27

1 Answers1

0

The answer came from M. Deinum.

Flushing is done on commit and that is also where the exception is being thrown. So if you want to directly get an exception you will have to call saveAndFlush instead of save (assuming you are using the JpaRepository as a base for your own repository)

I switched to JpaRepository and am now using saveAndFlush.

avolkmann
  • 2,962
  • 2
  • 19
  • 27