I have created this integration test with RestTemplate:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension::class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class PatientControllerIntTest @Autowired constructor(
private val patientRepository: PatientRepository,
private val restTemplate: TestRestTemplate
) {
private val defaultPatientId = ObjectId.get()
@LocalServerPort
protected var port: Int = 0
@BeforeEach
fun setUp() {
patientRepository.deleteAll()
}
private fun getRootUrl(): String = "http://localhost:$port/patients"
private fun saveOnePatient() = patientRepository.save(Patient(defaultPatientId, "Name", "Description"))
@Test
fun `should return single patient by id`() {
saveOnePatient()
val response = restTemplate.getForEntity(
getRootUrl() + "/$defaultPatientId",
Patient::class.java
)
assertEquals(200, response.statusCode.value())
assertNotNull(response.body)
assertEquals(defaultPatientId, response.body?.id)
}
}
I have run this application and it responds correctly.
I have debugged it at controller finding the correct id but when I get the response in the test case it is always the expected id incremented by one.