【问题标题】:spring mvc servlet 3 async response no database result in testspring mvc servlet 3异步响应没有数据库结果测试
【发布时间】:2015-11-13 02:30:59
【问题描述】:

我正在我的新项目中测试新的 servlet 3 异步请求,并在测试控制器时卡住了。

我有一个这样的控制器方法:

@RequestMapping(value = "/thumbnails", method = RequestMethod.GET)
public Callable<ResponseEntity<List<Thumbnail>>> getAllThumbnails() {
    //at this point I get results from the repository
    return () -> {
        //at this point I don't get any results
        final List<Thumbnail> thumbnails = thumbnailRepository.findAll();
        return ResponseEntity.ok(thumbnails);
    };
}

相应的测试如下:

@Test
@Transactional
public void testGetAllThumbnails() throws Exception {
    thumbnailRepository.saveAndFlush(thumbnail);

    final MvcResult mvcResult = restThumbnailMockMvc.perform(get("/test/thumbnails"))
                                                    .andExpect(request().asyncStarted())
                                                    .andExpect(request().asyncResult(instanceOf(ResponseEntity.class)))
                                                    .andReturn();

    mvcResult.getAsyncResult();

    restThumbnailMockMvc.perform(asyncDispatch(mvcResult))
                        .andDo(print())
                        .andExpect(status().isOk())
                        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                        .andExpect(jsonPath("$.[*].id").value(hasItem(thumbnail.getId().longValue())))
                        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
                        .andExpect(jsonPath("$.[*].fileName").value(hasItem(DEFAULT_FILE_NAME)));
}

Repository 和东西是一个简单的 spring data jpa bean,整个配置基于 spring boot。

如果我以正常方式查询控制器,一切正常,但在测试中,存储库不返回任何结果。

非常感谢您在这方面的帮助,我在网上找不到类似的东西。

【问题讨论】:

    标签: spring-mvc servlets jpa asynchronous spring-mvc-test


    【解决方案1】:

    好的,经过反复试验,我发现出了什么问题。

    问题是/是测试方法在事务中运行,并且由于某种原因,在测试运行时无法在控制器的可调用对象中访问相同的事务。从测试方法中删除 @Transactional 注释后,一切正常。

    【讨论】:

      猜你喜欢
      • 2014-06-29
      • 2013-05-26
      • 1970-01-01
      • 2011-03-21
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多