dany giguere
02/18/2024, 9:42 PM@ContextConfiguration
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class PostControllerTest(@Autowired val webTestClient: WebTestClient) {
@MockkBean
lateinit var postService: PostService
lateinit var postRepository: PostRepository
@BeforeEach
fun setUp() {
postRepository = mockk()
}
@Test
fun `GIVEN valid data WHEN a post is submitted THEN the post is returned`() {
// Given
val postDto = PostFactory(postRepository).makeOne(1)
coEvery { postService.create(1, postDto) } returns postDto
Can someone can confirm this is the right way to do it ? My concern is regarding the PostRepository. I think because of lateinit, PostRepository is not created and because I initialize it with mockk(), then it will only be mocked. Right ? : https://github.com/danygiguere/spring-boot-3-reactive-with-kotlin-coroutines/blob/main/src/test/kotlin/com/example/demo/unit/PostControllerTest.ktrenatomrcosta
02/19/2024, 9:15 AM@MockkBean
as you also did to your service, and use the clearAllMocks()
function Mockk provides to only block mocks from leaking from test case to test case.
However, it seems like your Repository will not be called, given that you are mocking the Service class that ultimately calls it. If you are mocking specific services, it can be good to also verify / coVerify
that the calls happened as expected, depending on the business context
Ultimately, for database integration tests, I would recommend looking into TestContainers or similar to spin up a test database so your integration tests can be more accurate to a real life scenariodany giguere
02/19/2024, 9:17 PMrenatomrcosta
02/20/2024, 7:27 AM