我有一個從其端點@RestController返回DeferredResult對象的類。在到達這些端點之前,我使用一個@EnableWebSecurity類來設(shè)置基本身份驗證。我能夠使用正確的基本身份驗證在本地卷曲這些端點并使其工作。但是,通過 spring 測試測試這些端點會導(dǎo)致此異常:java.lang.ClassCastException: org.springframework.security.web.servletapi.HttpServlet3RequestFactory$SecurityContextAsyncContext 不能轉(zhuǎn)換為 org.springframework.mock.web.MockAsyncCont我已經(jīng)嘗試在我的測試類上使用@WebAppConfiguration和@ContextConfiguration(classes = SpringSecurityConfig.class)注釋并設(shè)置MockMvc我自己(SpringSecurityConfig只是我實現(xiàn)基本身份驗證的類)。我也試過只使用@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貢獻1825條經(jīng)驗 獲得超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());
}
}
添加回答
舉報
0/150
提交
取消