Issue
I have a project with Spring-Boot + Spring-Security. In this project, typical I have MVC architecture.
My controller looks like:
@RestController
DemoController
{
public ResponseEntity<?> get(@AuthenticationPrinciple UserPrinciple userPrinciple)
{
return ...
}
}
I want to test this controller class with WebMvcTest. I know that I can handle it with SpringBootTest easily but SpringBootTest is not time-effective...
I've created a test class like:
@WebMvcTest(controllers = {DemoController.class})
DemoControllerTest
{
@Autowired
private MockMvc mockMvc;
@Test
void test_get()
{
this.mockMvc.perform(get("/...")
.header(AUTH_HEADER, getAuthorizationHeader())
.andExpect(status().isOk());
}
}
But I got error like userPrinciple is null or org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sha.springbootbookseller.security.CustomUserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate.
How I can inject AuthenticationPrinciple in WebMvcTest?
Example Code: https://github.com/senolatac/spring-boot-book-seller
Solution
Solved it with adding:
@WithMockUser
@ContextConfiguration
and mocking
@MockBean
private CustomUserDetailsService customUserDetailsService;
Final result looks like:
@WithMockUser
@WebMvcTest(controllers = {DemoController.class})
@ContextConfiguration(classes = {DemoController.class, JwtProvider.class, JwtFilter.class})
DemoControllerTest
{
@Autowired
private MockMvc mockMvc;
@MockBean
private CustomUserDetailsService customUserDetailsService;
@Test
void test_get()
{
this.mockMvc.perform(get("/...")
.header(AUTH_HEADER, getAuthorizationHeader())
.andExpect(status().isOk());
}
}
you can find the example code from: https://github.com/senolatac/spring-boot-book-seller
Answered By - Sha
Answer Checked By - Robin (JavaFixing Admin)