title: How do I unit test Lua modules without OO?
body: <p>In Lua I can write a simple module like so</p>
  
  <pre><code>local database = require 'database'
  local M = {}
  
  function M:GetData()
      return database:GetData()
  end
  
  return M
  </code></pre>
  
  <p>Which when required, will load once, and all future versions will load the same copy. </p>
  
  <p>If I wanted to take an object-oriented approach I could do something like:</p>
  
  <pre><code>local M = {}
  M.__index = M
  
  function M:GetData() 
      return self.database:GetData()
  end
  
  return function(database)
      local newM = setmetatable({}, M)
      newM.database = database
      return newM
  end
  </code></pre>
  
  <p>Where M is only loaded once, and each copy of newM just holds its own data and uses the methods of the original M.</p>
  
  <p>When it comes to testing, with the OO approach I can just pass in a fake version of 'database' and check it gets called, but with the first approach I can't.</p>
  
  <p>So my question is how can I make the first approach support DI/testing without making it class-like?</p>
  
  <p>My thought was to wrap it in a closure something like this:</p>
  
  <pre><code>local mClosure = function(database)
      local M = {}
  
      function M:GetData()
          return database:GetData()
      end
  
      return M
  end
  
  return mClosure
  </code></pre>
  
  <p>but then every time it is called it will create a new copy of M, so it will lose the benefits of both of the previous approaches.</p>