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

本文介绍如何在Windows环境中使用Busted进行Lua单元测试。Busted是一款BDD风格的Lua单元测试框架,支持TAP风格输出。文章详细描述了环境配置过程,包括LuaRocks的安装和Busted的安装步骤,以及可能遇到的问题和解决方案。同时,提供了测试代码示例和运行命令,展示了Busted的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

本文目标是在 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 的)。

参考

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值