我正在制作一个 mpv的脚本,在其中我加载了这样的mpv库: -- script.lualocal mp = require('mp') 我正在使用被破坏的单元测试框架为此编写测试,它们包含在一个单独的文件中,如下所示: -- scri
-- script.lua
local mp = require('mp')
我正在使用被破坏的单元测试框架为此编写测试,它们包含在一个单独的文件中,如下所示:
-- script-tests.lua
describe('my script unit tests', function()
local script = require('script')
it('...', function()
assert.is_true(true)
end)
end)
当我运行单元测试时出现问题,我得到了这个:
./script.lua:1:找不到模块’mp’:找不到mp的LuaRocks模块
我知道当我的脚本在mpv中运行时mp可用,但是当我运行我的单元测试时则不行.有没有办法在运行单元测试时停止此要求?或者我是以错误的方式思考这个问题?
解
最后我创建了一个存根mp(尝试使用像Adam建议的全局标志,但它不起作用).这里是:
-- script.lua
local plugin = {}
local mpv_loaded, mp = pcall(require, 'mp')
plugin.mp = mp
---------------------------------------------------------------------
-- Stub MPV library for unit tests
if not mpv_loaded then
plugin.mp = {}
function plugin.mp.osd_message(message)
plugin.mp.message = message
end
function plugin.mp.log(level, message)
-- stub
end
function plugin.mp.add_forced_key_binding(...)
-- stub
end
function plugin.mp.remove_key_binding(...)
-- stub
end
end
---------------------------------------------------------------------
-- Display message on screen.
function plugin:show_message(message)
self.mp.osd_message(message)
end
return plugin
-- script-tests.lua
describe('my script unit tests', function()
local plugin = require('script')
it('...', function()
message = 'It is better to play than do nothing.'
plugin:show_message(message)
assert.is_same(plugin.mp.message, message)
end)
end)
如果你关心的只是一个条件要求,那就意味着要捕捉到需要的错误:
local mpv_loaded, mp = pcall(function() return require 'mp' end)
if not mpv_loaded then
-- handle the bad require, in this case 'mp' holds the error message
else
-- 'mp' contains the lib as it normally would
end
