Lua Busted 单元测试简介(Windows 环境)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013614126/article/details/82967397

简介

本文目标是在 Windows 环境下使用 Busted 进行 Lua 单元测试。

Busted 是一款 BDD 风格的 Lua 单元测试框架,支持 TAP 风格输出。

环境

  • Lua 5.3.5
  • LuaRocks 3.0.2
  • Microsoft Windows 10 企业版 10.0.14393 版本 14393

环境配置

  1. 安装 LuaRocks,参照 Windows 平台 Luarocks 3.0.2 编译安装
  2. luarocks install busted 等待安装完成即可。
  3. 可能需要修改一下 busted.bat 文件以使 busted 可以找到测试文件同目录下的模块。参见Windows下 lua busted 找不到 module 解决办法

使用方法

busted 运行提供的 lua 脚本中的测试并给出测试结果。测试风格是 describe-it 式的,可以当做句子来读。具体语法请查看官方说明。

示例

待测试模块,保存为 sample_module.lua:

-- sample_module.lua
local sample_module = {}
function sample_module.greet( ... )
    print("hello")
end
return sample_module

测试代码,保存为 busted-simple.lua 与上述代码放在同一目录:

-- busted-simple.lua
describe("Busted unit testing framework", function()
    describe("should be awesome", function()
      it("should be easy to use", function()
        print(package.path)
        assert.truthy("Yup.")
      end)
  
      it("should have lots of features", function()
        -- deep check comparisons!
        assert.are.same({ table = "great"}, { table = "great" })
  
        -- or check by reference!
        assert.are_not.equal({ table = "great"}, { table = "great"})
  
        assert.truthy("this is a string") -- truthy: not false or nil
  
        assert.True(1 == 1)
        assert.is_true(1 == 1)
  
        assert.falsy(nil)
        assert.has_error(function() error("Wat") end, "Wat")
      end)
  
      it("should provide some shortcuts to common functions", function()
        assert.are.unique({{ thing = 1 }, { thing = 2 }, { thing = 3 }})
      end)
  
      it("should have mocks and spies for functional tests", function()
        local thing = require("sample_module")
        spy.on(thing, "greet")
        thing.greet("Hi!")
  
        assert.spy(thing.greet).was.called()
        assert.spy(thing.greet).was.called_with("Hi!")
      end)
    end)
  end)

使用命令行在上述文件所在目录运行命令 busted busted-simple.lua,得到结果:

./src/?.lua;./src/?/?.lua;./src/?/init.lua;.\?.lua;C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/?.lua;C:\local\LuaRocks-3.0.2\systree/share/lua/5.3/?/init.lua;%LUA_PATH%
鈼忊棌鈼廻ello
鈼
4 successes / 0 failures / 0 errors / 0 pending : 0.016 seconds

可以看到四个测试都通过了。(乱码先忽略吧,应该是官方没有做好 utf-8 输出处理,但是核心测试功能是 ok 的)。

参考

猜你喜欢

转载自blog.csdn.net/u013614126/article/details/82967397