在Postman中测试响应模式的泛型函数

时间:2018-08-18 06:21:20

标签: javascript automated-tests postman

最近几天,我非常头痛,无法创建测试脚本来验证我们正在开发的应用程序的300多个端点。最后,我提出了一个非常实用的解决方案,可以归结为:通用JSON验证功能,然后将预期结果复制并粘贴到对象中进行测试。该脚本在JSON内最多执行3个级别的每个字段验证。

[Authorize]
public class DefaultController : Controller
{
    public DefaultController(IHttpContextAccessor contextAccessor)
    {
        // Here HttpContext is not Null :)
        var authenticatedUser = contextAccessor.HttpContext.User.Identity.Name;
    }
}
  1. 使用邮递员,在用于运行测试的集合中创建一个预请求脚本
  2. 在要测试的请求中,粘贴以下代码:

pm.globals.set("validationHelper", function validationHelper(example) { for (var field in example) { if (typeof example[field] === "object") { pm.test(`Field '${field}' is part of the response`, function () { pm.expect(pm.response.text()).to.include(field); }); for (var nested in example[field]) { if (!Array.isArray(example[field][nested])) { pm.test(`Nested field '${nested}' is part of the response`, function () { pm.expect(pm.response.text()).to.include(nested); }); } else { pm.test(`Nested field '${nested}' is part of the response`, function () { pm.expect(pm.response.text()).to.include(nested); }); for (var index in example[field][nested]) { if (typeof example[field][nested][index] === "object") { if (!Array.isArray(example[field][nested][index])) { for (var child in example[field][nested][index]) { pm.test(`Child field '${child}' is part of the response`, function () { pm.expect(pm.response.text()).to.include(child); }); } } } } } } } else { pm.test(`Field '${field}' is part of the response`, function () { pm.expect(pm.response.text()).to.include(field); }); } } return true } + ';');

  1. 您保存的示例对象带有期望的响应。
  2. 尝试发送请求并获取全部绿色

由于性能原因,邮递员文档不建议循环测试,但是要节省多少时间,这可能是一个很好的解决方案。 :-)

1 个答案:

答案 0 :(得分:0)

经过一些研究,我发现了一个解决同一问题的更优雅的方法。 ;-)

pm.globals.set("validationHelper", function validationHelper(example, keys = {}) {
  for (var k in example) {

    if (typeof example[k] == "object" && example[k] !== null) {
      if (k.constructor === String) {
        if (!k.match(/^-{0,1}\d+$/)) {
          existProperty = false
          for (var key in keys) {
            (key === k) && (existProperty = true)
          }
          if (!existProperty) {
            keys[k] = true
            pm.test(`Child field '${k}' is part of the response`, function () {
                pm.expect(pm.response.text()).to.include(k);
            });
          }
        }
      }
      validationHelper(example[k], keys);

    } else {
      if (k.constructor === String) {
        if (!k.match(/^-{0,1}\d+$/)) {
          existProperty = false
          for (var key in keys) {
            (key === k) && (existProperty = true)
          }
          if (!existProperty) {
            keys[k] = true
            pm.test(`Child field '${k}' is part of the response`, function () {
                pm.expect(pm.response.text()).to.include(k);
            });
          }
        }
      }
    }
  }
  return true
} + ';');