4

我有一个 Lua 函数,它返回false后跟错误消息,并希望使用破坏的测试框架来测试它的行为。现在我这样做有点像这样:

function safe_divide(a, b)
    if b > 0 then -- buggy! should be b ~= 0 
        return a / b
    else
        return false, "division by zero"
    end
end

describe("safe_divide", function()
    it("can divide by positive numbers", function()
        local ok, err = safe_divide(10.0, 5.0)
        assert.truthy(ok)
        assert.are.same(2.0, ok)
    end)

    it("errors when dividing by zero", function()
        local ok, err = safe_divide(10.0, 0.0)
        assert.not_truthy(ok)
        assert.are.same("division by zero", err)
    end)

    it("can divide by negative numbers", function()
        local ok, err = safe_divide(-10.0, -5.0)
        assert.truthy(ok)
        assert.are.same(2.0, ok)
    end)
end)

我不喜欢我目前的方法有两点:

  • 每个测试是 3 行而不是单个干净的行
  • 当第三次测试失败时,busted 只是说这false不是预期的真实值,并且从未提及“除以零”错误消息。

有没有办法改进我的测试文件以避免这些问题?

我认为我想做的有点类似于has_errorbusted 中的断言,但这似乎只适用于实际引发异常的函数,而不适用于返回false后跟错误消息的函数。

4

1 回答 1

2

Busted使用luassert,可以使用您自己的断言进行扩展。

例如,以下代码使用用户定义的断言,该断言answers将预期结果表作为第一个参数,并将有效函数结果作为其余参数。

local assert = require "luassert"

local function safe_divide(a, b)
    if b > 0 then -- buggy! should be b ~= 0
        return a / b
    else
        return false, "division by zero"
    end
end

local function answers(state, arguments)
  local expected = arguments[1]
  assert(type(expected) == "table")
  for i = 2, #arguments do
      if arguments[i] ~= expected[i-1] then
          state.failure_message = "unexpected result " .. tostring (i-1) .. ": " .. tostring (arguments [i])
          return false
      end
  end
  return true
end
assert:register("assertion", "answers", answers)

describe("safe_divide", function()
    it("can divide by positive numbers", function()
        assert.answers({ 2.0 }, safe_divide(10.0, 5.0))
    end)

    it("errors when dividing by zero", function()
        assert.answers({ false, "division by zero" }, safe_divide(10.0, 0.0))
    end)

    it("can divide by negative numbers", function()
        assert.answers({ 2.0 }, safe_divide(-10.0, -5.0))
    end)
end)

此代码缺少断言消息的正确格式。您可以查看luaassert文档,或查看预定义的断言。它包含一个say用于消息翻译的模块。

于 2017-09-22T06:52:46.057 回答