I want to test a controller, that returns page using Thymeleaf template, with MockMVC
.
This is my test:
class PostControllerTest {
...
@BeforeClass
fun setUp() {
MockKAnnotations.init(this)
mockMvc = MockMvcBuilders.standaloneSetup(postController)
.build()
}
@Test
fun testGetFirstPost() {
every { postRepository.find(1) } returns post
mockMvc.perform(get("/post/1"))
.andExpect(status().`is`(200))
.andExpect(model().attribute("post", equalTo(post)))
}
}
But I get the exception:
Circular view path [post]: would dispatch back to the current handler URL [/post] again.
Name of the controller mapping and the template are the same (post
).
I don't want to use WebApplicationContext
or something like this.
You should add ViewResolver
to recognize template:
mockMvc = MockMvcBuilders.standaloneSetup(postController)
.setViewResolvers(viewResolver())
.build()
Where viewResolver()
is:
private fun viewResolver(): InternalResourceViewResolver {
val viewResolver = InternalResourceViewResolver()
// configuration
viewResolver.setPrefix("/templates/")
viewResolver.setSuffix(".html")
return viewResolver
}