lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 2014/7/23 2:16, Tom N Harris wrote:
On Tuesday, July 22, 2014 03:10:23 PM albert_200200 wrote:
Hi, guys, I'm using lunit and lemock to test my code,
Here is the situation: the function I should mock is in the same module
of the function I'm testing.
I'm not entirely familiar with lemock, however...

      package.path   = "./?.lua;"..package.path
      local foo = require("foo")

      package.loaded.foo.dowork_internal       = nil
      package.preload["foo.dowork_internal"]   = function()
          return self.mock_dowork_internal
      end

      local val = foo.dowork(vala, valb)
      assert_equal(val, 2)
That isn't how package.preload works. The preload functions are module
loaders. The loader function is called by require to create the module table.
The value returned by the loader is then stored in package.loaded.foo and also
returned by require.

I think all you need is to assign the mock function to foo.dowork_internal.


Tom, thanks so much.
Now I modify the code as below, it worked. Thanks again.
foo.lua
---------------------------------------------------------------------------------------------------------------
local M = {}
function M.dowork_internal(a, b)
    return global_function(a, b)
end
function M.dowork(a, b)
    return M.dowork_internal(a, b)
end
return M


test.lua
---------------------------------------------------------------------------------------------------------------
require("lunit")
lunit.setprivfenv()
lunit.import "assertions"
lunit.import "checks"

require("lemock")

local ut = lunit.TestCase("module test")
function ut:setup()
    self.mc                       = lemock.controller()
    self.mock_dowork_internal     = self.mc:mock()
end
function ut:test_normal()
    local vala     = 1
    local valb     = 2

    package.path   = "./?.lua;"..package.path
    local foo = require("foo")

    package.loaded.foo.dowork_internal       = self.mock_dowork_internal

    self.mock_dowork_internal(vala, valb); self.mc:returns(2)
    self.mc:replay()


    local val = foo.dowork(vala, valb)
    assert_equal(val, 2)

    self.mc:verify()
end
lunit.run()