I am getting an error when trying to get the TestRestTemplate. Is there any way to get the TestRestTemplate or test the ErrorController?
error log: https://pastebin.com/XVPU9qrb
package io.kuark.ppalli
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT
import org.springframework.test.context.ActiveProfiles
@ActiveProfiles("test")
@SpringBootTest(classes = [PpalliApi::class], webEnvironment = RANDOM_PORT)
class PpalliApiTest {
@Test
fun contextLoads() {}
}
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.web.client.TestRestTemplate
import kotlin.test.assertEquals
@WebMvcTest
class FallbackErrorControllerTest {
@Autowired
lateinit var http: TestRestTemplate
@Test
fun handleError() {
val result = http.getForObject("/error", String::class.java);
assertEquals("""{"code": "NOT_FOUND"}""", result)
}
}
When working with @WebMvcTest
, Spring Boot won't start the embedded Tomcat server and you won't be able to access your endpoints over a port. Instead, Spring Boot configures a mocked servlet environment that you directly interact with using MockMvc
:
@WebMvcTest
class FallbackErrorControllerTest {
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun handleError() {
mockMvc.perform(get("/error")).andExpect(status().isOk);
}
}
MockMvc even comes with its own Kotlin DSL.
When using @SpringBootTest
and webEnvironment=RANDOM_PORT
however, Spring Boot will auto-configure Tomcat and expose your application on a random port. This will be a real servlet environment where you can use TestRestTemplate
as an HTTP client to interact and test your endpoints.