Busted has_error 导致测试出错

Busted has_error causes tests to error

我正在尝试使用 busted 对 lua 项目进行单元测试。我有一个看起来像这样的模块:

-- src/rom/apis/display.lua

local _displayModes = {
  single = 1,
  mirrored = 2,
  extended = 3,
  immersive = 4
}

local _validMode = function(mode)
  retVal = false
  for k,v in pairs(_displayModes) do
    if mode == v then retVal = true break end
  end
  return retVal
end

local _setMode = function (mode)
  if _validMode(mode) then
    _config.mode = mode
  else
    error("INVALID DISPLAY MODE: "..mode)
  end
end

display = {
  mode = _displayModes,
  setMode = _setMode
}

在我的规范中,我试图断言 setMode returns 是一个错误:

local displayModule = require("rom/apis/display")
describe("#API #Display", function()
  describe("with single monitor", function()
    setup(function()
      local _p = {
        monitor = {'foo'}
      }
      mockPeripherals(_p)
    end)

    it("should not setMode with invalid mode", function()
      assert.has_error(display.setMode(100), "INVALID DISPLAY MODE: 100")
    end)
  end)
end)

当我 运行 规范时,它由于函数错误而出错。这是控制台输出:

$ busted ●●●●✱ 4 successes / 0 failures / 1 error / 0 pending :
0.001444 seconds

Error → test/spec/rom/apis/display_spec.lua @ 32
#API #Display with single monitor should not setMode with invalid mode ./src/rom/apis/display.lua:32: INVALID DISPLAY MODE: 100

stack traceback:    ./src/rom/apis/display.lua:32: in function 'fn'     test/spec/rom/apis/display_spec.lua:34: in function <test/spec/rom/apis/display_spec.lua:32>

它出现了我预期的错误,但问题是测试应该通过,因为我断言它返回了正确的错误。

您需要将出错的调用包装在一个函数中:

it("should not setMode with invalid mode", function()
  assert.has_error(function() display.setMode(100) end, "INVALID DISPLAY MODE: 100")
end)