I have a test that creates a user via a JPA repo and then logs that user in via a TestRestTemplate
The problem is after I create my user using the repo, the web call cannot see the user in the database, even after calling entityManager.flush()
and entityManager.clear()
The methods in question:
fun _createUserGetLoginDTO(): LoginDTO{
val password = passwordEncoder.encode(Instancio.create(String::class.java))
val user = getTestUser()
user.setPassword(password)
latestUser = user
itrUserRepository.save(user)
val loginDTO = LoginDTO(user.username!!, password)
entityManager.flush()
entityManager.clear()
return loginDTO
}
fun _createUserAndLoginReturningToken(): String {
val loginDTO = _createUserGetLoginDTO()
val tr = this.testRestTemplate.exchange(
"http://localhost:$port/auth/login", HttpMethod.POST, HttpEntity<LoginDTO>(loginDTO),
LoginResponse::class.java
) // Fails b/c user is not found?
Assertions.assertThat(tr.statusCode.value()).isEqualTo(200)
Assertions.assertThat(centralTokenStorageService.isValid(tr.body?.token!!)).isTrue()
entityManager.flush()
entityManager.clear()
return tr.body?.token!!
}
To debug, I added a message in my user details service and I can see that my user lookup is failing, causing a 403 (I see the error message printed to stderr):
@Bean
fun userDetailsService(): UserDetailsService {
return UserDetailsService { username ->
val u = itrUserRepository.findByUn(username)
if (!u.isPresent) {
System.err.println("************ User not found ${username}")
throw (UsernameNotFoundException("User $username not found"))
}
u.get()
}
}
How can I make the user I'm inserting available to the web layer?
Found it, this combination of annotations worked for me.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase
@AutoConfigureWebTestClient
For some reason, the AutoConfigure*
annotations sorted it.
If you down-vote a question, please leave a comment as to why.