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

我有一个从其端点@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;

    }

元芳怎么了
浏览 183回答 2
2回答

米脂

这是 Core Spring 中已修复的错误。有关详细信息,请参阅SPR-16695。如果升级到 Spring Framework 4.3.16、5.0.6 或更高版本,问题应该会消失。如果升级后它没有消失,请创建一个新的JIRA 问题来描述问题。

胡子哥哥

更新你的测试&nbsp;@Test&nbsp;public void PushNotificationControllerSpringTest() throws Exception {&nbsp;....&nbsp;MvcResult mvcResult = this.mockMvc.perform(get("/admin/bulletins").header("Authorization", "Basic YWRtaW46cGFzc3cwcmQ="))&nbsp; &nbsp; .andExpect(request().asyncStarted()).andReturn();&nbsp; &nbsp; &nbsp;this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk());&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java