【问题标题】:Mocking methods in an existing lua file during Busted tests在 Busted 测试期间模拟现有 lua 文件中的方法
【发布时间】:2017-06-06 14:44:26
【问题描述】:

我想使用 Busted 为现有的 lua 文件编写单元测试。我想在测试期间交换一些方法,以便文件使用模拟/存根方法而不是真实方法运行(否则它将失败)。文件调用的一些方法是从其他 lua 库中提取的,我也想模拟这些方法。

如何做到这一点?

任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: unit-testing lua mocking resty lua-busted


    【解决方案1】:

    我不认为您可以轻松替换本地函数,但替换导出或全局函数很简单。

    例如,我需要通过http:new().request(...) 库中的http:new().request(...) 模拟一个HTTP 调用。这是我在测试中所做的:

    local http = require 'resty.http'
    http.new = function()
      return {
        request = function(self, args)
          -- ... some mock implementation
        end
      }
    end
    

    这种方法应该适用于任何导出的函数。例如,从库bar 中替换函数foo

    local bar = require 'bar'
    bar.foo = myMockImpl
    

    改变全局函数或变量可以通过覆盖_G来实现,例如这会改变全局函数或变量foo

    _G.foo = ...
    

    Busted 支持自动恢复环境。在documentation 中搜索“绝缘”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-02
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-10-20
      • 1970-01-01
      • 2023-03-10
      • 2018-06-16
      相关资源
      最近更新 更多