一起测试 Spring asyncResult() 和 jsonPath()

2024-03-25

我使用 Restful url 来启动长时间运行的后端进程(它通常按照 cron 计划进行,但我们希望能够手动启动它)。

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

@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我使用了下面的代码,一切正常(我更改了预期的错误消息以简化发布)。

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但是它不起作用。我也在下面尝试过,但没有成功。还有其他人成功过吗?

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。

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 = []

巴德的回答确实帮助我指明了正确的方向,但它并没有完全起作用,因为它没有等待异步结果。自从发布这个问题以来,spring-mvc-showcase 示例(https://github.com/SpringSource/spring-mvc-showcase https://github.com/SpringSource/spring-mvc-showcase)已更新。

似乎在调用的第一部分中,当您检索 MvcResult 时,您需要对 asyncResult() 进行断言,而在 JSON pojo 映射的情况下,您需要对实际类型本身(而不是 JSON)进行断言。所以我需要将下面的第三行添加到巴德的答案中,然后剩下的就可以了。

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"));

Note: instanceOf() is org.hamcrest.CoreMatchers.instanceOf。要访问 Hamcrest 图书馆,请包括最新的hamcrest-library jar.

对于行家...

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-library</artifactId>
        <version>LATEST VERSION HERE</version>
        <scope>test</scope>
    </dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一起测试 Spring asyncResult() 和 jsonPath() 的相关文章

随机推荐

  • 模板参数中的自引用模板

    我该怎么做才能使这项工作成功 template
  • 使用 OpenCV 捕获 H264 流

    所以 一段时间以来 我一直在尝试让我的 Raspberry Pi 2 使用 OpenCV 从我的 Logitech C920 捕获 H264 流 我一直在互联网上搜寻信息 但没有运气 简短的系统描述 Raspberry Pi 2 运行 Ra
  • 透明背景上的 CoreText 字体平滑

    我尝试在 半 透明背景上使用 CoreText appkit 版本 进行渲染 结果边缘不平滑 在网上搜索表明这个问题没有解决方案 但是我不相信它 因为一个简单的观察 如果我创建一个包含相同字符串的 CATextLayer 那么字体是可爱和平
  • git全局配置问题

    不知何故 我的全局 git msysgit 设置user name and user email 天知道还有什么 被设置为最近前同事的详细信息 当我尝试改变它们时 我得到了could not commit to u gitconfig 如果
  • 将 SpringCloudSleuth 与 AWS X-Ray 集成

    我有一个使用 Springboot 应用程序运行 Fargate 实例的 ECS 集群 并且希望以最少的代码更改来启用跟踪 我开始研究两种方法 使用 AWS Xray 步骤 gt 添加依赖项 添加 WSXRayServletFilter 在
  • 删除numpy数组中的行

    我有一个可能如下所示的数组 ANOVAInputMatrixValuesArray 0 96488889 0 73641667 0 67521429 0 592875 0 53172222 0 78008333 0 5938125 0 48
  • 追求纯 CSS 布局有商业原因吗?

    似乎每次我尝试创建纯 CSS 布局时 都会比使用一两个表格花费更长的时间 让三列具有不同数量的数据的相同长度似乎需要特殊的技巧 特别是在处理跨浏览器问题时 我的问题 这几张桌子会伤害谁 表格似乎在表格数据上特别有效 为什么它们在当今时代如此
  • 为什么 C# 中函数 isprefix 比 Startswith 快?

    有谁知道为什么 C NET 的以 开始 http msdn microsoft com en us library system string startswith aspx函数比IsPrefix http msdn microsoft c
  • Perl:现实生活中的字符串长度限制

    同时 例如 perldata http perldoc perl org perldata html文档表明 Perl 中的标量字符串仅受可用内存的限制 我强烈怀疑在现实生活中还会有一些其他限制 我正在考虑以下想法 我不确定 Perl 中如
  • 尽管服务器回复积极,但 Rails 渲染未在浏览器中显示

    我在 Rails 中使用 渲染 时遇到问题 我的控制器中有一个自定义操作 搜索 它应该呈现索引 如下所示 def search date params reserve date tables Table all render index e
  • 确定哪些对象引用 SQL Server 中的表

    我需要重命名一个包含许多列和针对该表进行处理的存储过程的表 在这种情况下 如何获取数据库中与表有关系的所有项目 Using sys dm sql referencing entities http msdn microsoft com en
  • 如何为 Rails gem 指定 rvm gemsets ?

    MyApp 正在使用 rvm gemset 电子邮件受保护 cdn cgi l email protection 这不是默认的 我正在使用 gem 每当 定期发送电子邮件通知 这是我的日程表 rb every 1 minutes do ru
  • 使用 pandas 和 numpy 解析冒号分隔的稀疏数据

    我想解析 pandas numpy 中 col index value 格式的数据文件 例如 0 23 3 41 1 31 2 65 将对应于这个矩阵 23 0 0 41 0 31 65 0 这似乎是表示文件中稀疏数据的一种非常常见的方法
  • 如何使用 clang-format 缩进 C++ pragma?

    我在用vim autoformat 它使用clang format作为外部格式化程序 看起来clang format不会缩进 C pragma 例如 include
  • 查找选定列中多个点的斜率

    给定以下数据框 structure list 5 c 0 1 0 0 9 22 4 c 1 3 0 0 1 17 3 c 1 3 0 0 0 12 2 c 1 3 0 0 2 10 1 c 0 0 0 4 3 9 0 c 0 1 0 2 2
  • 如何将嵌入的 Blazegraph 内容转储到 RDF 文件?

    I have 创建了 blazegraph RDF4J 存储库和连接 https wiki blazegraph com wiki index php Sesame API Tutorial在斯卡拉中 val props new Prope
  • 适用于 Android 和 iOS 的离线地图 SDK [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我想为我的应用程序使用离线地图功能 有人会推荐任何有用的地图 SDK 吗 我找到了这些 Skobbler http developer skob
  • 实时数据和双向数据绑定:未调用自定义设置器

    我使用 2 路数据绑定来更新 ViewModel 中的 LiveData String 对象 并使用 EditText 中设置的字符串
  • 处理 .NET Core 构建的错误 CA1416 的正确方法是什么?

    这是我的 C 代码片段 if Environment IsWindows sessionAddress GetSessionBusAddressFromSharedMemory System Runtime Versioning Suppo
  • 一起测试 Spring asyncResult() 和 jsonPath()

    我使用 Restful url 来启动长时间运行的后端进程 它通常按照 cron 计划进行 但我们希望能够手动启动它 下面的代码有效 当我手动测试时 我在浏览器中看到结果 ResponseBody RequestMapping value