3

我正在尝试使用 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 返回错误:

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>

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

4

1 回答 1

3

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

it("should not setMode with invalid mode", function()
  assert.has_error(function() display.setMode(100) end, "INVALID DISPLAY MODE: 100")
end)
于 2015-08-18T00:51:34.123 回答