Repository層でrestTemplateで呼び出してる外部APIをMock化してUnitTestを作成する。
MockはSpringBootに用意されているMockRestServiceServerを使用。
@RestClientTest(TaskRepository::class)
@DisplayName("TaskRepository")
internal class TaskRepositoryTest {
@Autowired
lateinit var taskRepository: TaskRepository
@Autowired
lateinit var mockServer: MockRestServiceServer
@Autowired
lateinit var objectMapper: ObjectMapper
@Nested
@DisplayName("getTask")
inner class GetTask {
@Test
@DisplayName("should return task data when taskRepository call to GET task to external Task-api with task id.")
fun getTask() {
val task = Task(12345, "タスクのタイトル", "タスクの詳細説明", Date())
mockServer.expect(requestTo("http://localhost:50000/tasks/12345"))
.andRespond(withSuccess(objectMapper.writeValueAsString(task), MediaType.APPLICATION_JSON))
val actual = taskRepository.getTask(12345) ?: Task()
assertEquals(12345, actual.taskId)
assertEquals("タスクのタイトル", actual.title)
assertEquals("タスクの詳細説明", actual.description)
assertNotNull(actual.created)
}
}
}
実行結果
参考
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-rest-client
ハマったところ
[SpringBoot/KotlinでBFF]”Unable to use auto-configured MockRestServiceServer since MockServerRestTemplateCustomizer has not been bound to a RestTemplate”の解決
[SpringBoot/KotlinでBFF]”Error while extracting response for type [] and content type [application/json]”の解決
コメントを残す