为了账号安全,请及时绑定邮箱和手机立即绑定

无法使用具有异步 + 弹簧安全性的弹簧测试

无法使用具有异步 + 弹簧安全性的弹簧测试

元芳怎么了 2021-08-19 13:34:22
我有一个从其端点@RestController返回DeferredResult对象的类。在到达这些端点之前,我使用一个@EnableWebSecurity类来设置基本身份验证。我能够使用正确的基本身份验证在本地卷曲这些端点并使其工作。但是,通过 spring 测试测试这些端点会导致此异常:java.lang.ClassCastException: org.springframework.security.web.servletapi.HttpServlet3RequestFactory$SecurityContextAsyncContext 不能转换为 org.springframework.mock.web.MockAsyncCont我已经尝试在我的测试类上使用@WebAppConfiguration和@ContextConfiguration(classes = SpringSecurityConfig.class)注释并设置MockMvc我自己(SpringSecurityConfig只是我实现基本身份验证的类)。我也试过只使用@SpringBootTestand @AutoConfigureMockMvc。这是我当前的测试课程:@RunWith(SpringRunner.class)@WebAppConfiguration@ContextConfiguration(classes = SpringSecurityConfig.class)public class PushNotificationControllerSpringTest {    @MockBean    BucketDetailsService bucketDetailsService;    @MockBean    NotificationService notificationService;    @Autowired    protected WebApplicationContext wac;    private MockMvc mockMvc;    @Before    public void prepare() {        mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build();    }    @Test    public void testListBulletins() throws Exception {        mockMvc.perform(asyncDispatch(                mockMvc.perform(get("/admin/bulletins").header("Authorization", "Basic YWRtaW46cGFzc3cwcmQ="))                        .andExpect(status().isOk()).andReturn()));    }}这是我的休息控制器:@RestController@RequestMapping("/admin")public class PushNotificationController {    protected static final Logger logger = LoggerFactory.getLogger(PushNotificationController.class);    @Autowired    BucketDetailsService bucketDetailsService;    @GetMapping("/bulletins")    public DeferredResult<List<BulletinDetails>> listBulletins() {        DeferredResult<List<BulletinDetails>> deferredResult = new DeferredResult<>();        logger.debug("Fetching bulletins...");        bucketDetailsService.listBulletins()                .whenComplete((res, ex) -> setResult(deferredResult, res, ex, "List bulletins"));        return deferredResult;    }
查看完整描述

2 回答

?
米脂

TA贡献1836条经验 获得超3个赞

这是 Core Spring 中已修复的错误。

有关详细信息,请参阅SPR-16695

如果升级到 Spring Framework 4.3.16、5.0.6 或更高版本,问题应该会消失。

如果升级后它没有消失,请创建一个新的JIRA 问题来描述问题。


查看完整回答
反对 回复 2021-08-19
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

更新你的测试


 @Test

 public void PushNotificationControllerSpringTest() throws Exception {


 ....


 MvcResult mvcResult = this.mockMvc.perform(get("/admin/bulletins").header("Authorization", "Basic YWRtaW46cGFzc3cwcmQ="))

    .andExpect(request().asyncStarted()).andReturn();


     this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk());

 }

}


查看完整回答
反对 回复 2021-08-19
  • 2 回答
  • 0 关注
  • 182 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信