I enabled MockMvcResultHandlers.print() to see what the issue is. It turned out that a repository on which my validator depends was not defined. Defining that in BaseTestConfig resolved the issue.
Spring MockMvc - Custom Validators are not registered/called in Spring Container
-
06-07-2023 - |
Question
@Configuration
@EnableWebMvc
@ComponentScan("com.xyz.web")
class BaseTestConfig extends WebMvcConfigurerAdapter {
@Bean
AccountService accountService() {
return Mockito.mock(AccountService)
}
}
class Test {
@Autowired WebApplicationContext wac
MockMvc mockMvc
@BeforeClass
void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()
}
@Test
void testSubmitPageFails() {
mockMvc.perform(post("/createAccount")
.param("account.username", "x")
.param("confirmEmail", "y")
.param("account.firstName", "")
.param("account.lastName", "")
.param("account.zip", ""))
.andExpect(model().errorCount(5))
.andExpect(view().name("account/createAccount"))
.andExpect(status().isOk())
}
@Test
void testSubmitPageSucceeds() {
mockMvc.perform(post("/createAccount")
.param("account.username", "test@test.com")
.param("confirmEmail", "test@test.com")
.param("account.firstName", "John")
.param("account.lastName", "Doe")
.param("account.zip", "22102"))
.andExpect(flash().attributeCount(1))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/home"))
}
}
I define my test class and config class as shown above. However, controller methods having @Valid annotations not being invoked. It seems like they are not registered during Spring container initialization.
These validators registered just fine when I run the application.
Any idea why my custom validators are ignored for my controller tests?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow