spring-security 使用WebMvcTest + JWT +认证原理进行Sping Boot 单元测试

iecba09b  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(154)

我有一个Spring-Boot + Spring-Security的项目。在这个项目中,我使用了典型的MVC架构。
我的控制器看起来像:

@RestController
DemoController
{
    public ResponseEntity<?> get(@AuthenticationPrinciple UserPrinciple userPrinciple)
    { 
       return ...
    }
}

我想用WebMvcTest测试这个控制器类。我知道我可以用SpringBootTest轻松地处理它,但是SpringBootTest不省时...
我创建了一个测试类,如下所示:

@WebMvcTest(controllers = {DemoController.class})
DemoControllerTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    void test_get()
    {
        this.mockMvc.perform(get("/...")
                .header(AUTH_HEADER, getAuthorizationHeader())
            .andExpect(status().isOk());
    }
}

但我得到了错误,如userPrinciple为空或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.如何在WebMvcTest中注入AuthenticationPrinciple?
示例代码:https://github.com/senolatac/spring-boot-book-seller
测试类别:https://github.com/senolatac/spring-boot-book-seller/blob/master/src/test/java/com/sha/springbootbookseller/controller/PurchaseHistoryControllerTest.java

kzipqqlq

kzipqqlq1#

通过添加以下内容解决了该问题:

@WithMockUser
@ContextConfiguration

和嘲笑

@MockBean
private CustomUserDetailsService customUserDetailsService;

最终结果如下所示:

@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());
    }
}

您可以从以下位置找到示例代码:https://github.com/senolatac/spring-boot-book-seller

相关问题