一起测试Spring asyncResult()和jsonPath() [英] Testing Spring asyncResult() and jsonPath() together

查看:332
本文介绍了一起测试Spring asyncResult()和jsonPath()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个宁静的URL来启动一个长期运行的后端进程(通常在cron计划中,但是我们希望能够手动启动它).

I'm using a restful url to kick off a long-running backend process (it is normally on a cron schedule, but we want the ability to kick it off manually).

下面的代码有效,当我手动测试时,我会在浏览器中看到结果.

The code below works and I see the result in the browser when I test manually.

@ResponseBody
@RequestMapping(value = "/trigger/{jobName}", method = RequestMethod.GET)
public Callable<TriggerResult> triggerJob(@PathVariable final String jobName) {

    return new Callable<TriggerResult>() {
        @Override
        public TriggerResult call() throws Exception {
            // Code goes here to locate relevant job and kick it off, waiting for result
            String message = <result from my job>;
            return new TriggerResult(SUCCESS, message);
        }
    };
}

当我在没有Callable的情况下测试此代码时,我使用了下面的代码,并且一切正常(我更改了预期的错误消息以简化发布).

When I test this without the Callable I used the code below and it all works (I changed the expected error message to simplify post).

mockMvc.perform(get("/trigger/job/xyz"))
    .andExpect(status().isOk())
    .andDo(print())
    .andExpect(jsonPath("status").value("SUCCESS"))
    .andExpect(jsonPath("message").value("A meaningful message appears"));

当我添加Callable时,它不起作用.我也在下面尝试过,但是没有用.其他人成功了吗?

When I added the Callable however it does not work. I also tried below but it did not work. Anyone else had success?

mockMvc.perform(get("/trigger/job/xyz"))
    .andExpect(status().isOk())
    .andDo(print())
    .andExpect(request().asyncResult(jsonPath("status").value("SUCCESS")))
    .andExpect(request().asyncResult(jsonPath("message").value("A meaningful message appears")));

下面是我print()的相关部分.在这种情况下,mockMvc似乎无法正确解开Json(即使它在我的浏览器中也有效)?当我不使用Callable进行此操作时,我会看到完整的JSON.

Below is the relevant part from my print(). Looks like mockMvc can't untangle the Json correctly in this case (even though it works in my browser)? When I do this without Callable I see full JSON.

MockHttpServletRequest:
     HTTP Method = GET
     Request URI = /trigger/job/xyz
      Parameters = {}
         Headers = {}

         Handler:
            Type = foo.bar.web.controller.TriggerJobController
          Method = public java.util.concurrent.Callable<foo.bar.myproject.web.model.TriggerResult> foo.bar.myproject.web.controller.TriggerJobController.triggerJob(java.lang.String)

           Async:
 Was async started = true
      Async result = foo.bar.myproject.web.model.TriggerResult@67aa1e71


Resolved Exception:
            Type = null

    ModelAndView:
       View name = null
            View = null
           Model = null

        FlashMap:

MockHttpServletResponse:
          Status = 200
   Error message = null
         Headers = {}
    Content type = null
            Body = 
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

推荐答案

Bud的回答确实帮助我指出了正确的方向,但是它并不起作用,因为它没有等待异步结果.自发布此问题以来,spring-mvc-showcase示例( https://github.com/SpringSource/spring-mvc-showcase )已更新.

Bud's answer really helped point me in the right direction however it didn't quite work because it did not wait for the async result. Since posting this question, the spring-mvc-showcase samples (https://github.com/SpringSource/spring-mvc-showcase) have been updated.

似乎在调用的第一部分中,当您检索MvcResult时,您需要在asyncResult()上声明,对于JSON pojo映射,您需要在实际的类型本身(而不是JSON)上声明.因此,我需要在Bud的答案中添加下面的第三行,然后其余的就可以了.

It seems like in the first part of the call when you retrieve the MvcResult, you need to assert on an asyncResult() and in the case of JSON pojo mapping you need to assert on the actual type itself (not JSON). So I needed to add the third line below to Bud's answer, then the rest just works.

MvcResult mvcResult = this.mockMvc.perform(get("/trigger/job/xyz"))
    .andExpect(request().asyncStarted())
    .andExpect(request().asyncResult(instanceOf(TriggerResult.class)))
    .andReturn();

this.mockMvc.perform(asyncDispatch(mvcResult))
    .andExpect(status().isOk())
    .andExpect(content().contentType(MediaType.APPLICATION_JSON))
    .andExpect(jsonPath("status").value("SUCCESS"))
    .andExpect(jsonPath("message").value("A meaningful message appears"));

注意:instanceOf()org.hamcrest.CoreMatchers.instanceOf.要访问Hamcrest库,请包含最新的hamcrest-library jar.

Note: instanceOf() is org.hamcrest.CoreMatchers.instanceOf. To get access to Hamcrest libraries include the latest hamcrest-library jar.

对于Maven ...

For maven ...

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>LATEST VERSION HERE</version>
        <scope>test</scope>
    </dependency>

这篇关于一起测试Spring asyncResult()和jsonPath()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆