Search code examples
functionunit-testingmockingdphobos

How to mock standard library functions in D


I have a function that calls isFile (from std.file) on a filename and then proceeds appending .1, .2, .3 etc, checking whether each one of those is present.

I want to unit test the function, but to do so I need to mock isFile.

I looked around a bit and I found ways to mock classes but not single functions.


Solution

  • Since my answer is slightly different from Adam's, I will add it, and he can add his.

    You can use "Scoped imports" for that purpose. See the respective section in the documentation http://dlang.org/module.html

    Here's also a working example, how you can mock an isFile function inside a unittest block (assuming it is defined in module "mocks")

    import std.file; 
    import std.stdio;
    
    int main(string[] args) 
    { 
        writeln(isFile("qq.d")); 
        return 0; 
    } 
    
    unittest 
    { 
        import mocks;
        writeln(isFile("qq.d")); 
    }