Is Mocking discouraged? I would like to isolate testing

EDIT: SimpleMock.jl allows mocking without needing macros in the live code, unlike Mocking.jl

Let’s say I have 2 modules (e.g. below) and I want to test out ModuleB in an isolated way; i.e. without running the code in ModuleA.

Is there a way to mock out or patch ModuleA when I unit test ModuleB ? If not, what are some alternative testing strategies I could use?

module ModuleA 
    function f_a()
        println(1)
    end
end
module ModuleB
    import Main: ModuleA
    function g()
        ModuleA.f_a()
    end
end

I’m coming from Python, where it’s common to mock calls from other files and instead just assert that the other file was called, instead of actually calling it.

I have never seen it used, but making an object that spits out mock functions is not hard.

struct Mock end
Base.getproperty(::Mock, s::Symbol) = (args...) -> println("Mock call to ", s, "(", join(repr.(args), ", "), ")")

const ModuleA = Mock()
ModuleA.f_a()

May be you need something like this : GitHub - invenia/Mocking.jl: Allows Julia function calls to be temporarily overloaded for purpose of testing

1 Like

There are several options for Julia mocking libraries:

4 Likes

I would avoid mocking whenever possible. Design your program in a functional style so that any I/O is on the outside and you can test the body of your program without substituting anything. When you need to do I/O to test against a web service, try to use the actual web service’s test endpoint unless it’s too slow. At that point you can make a fake FakeClient that behaves just like RealClient but faster – still saving data, just in memory instead of over the net. Not tracking method calls like some mocks would.

1 Like

I’m doing something like this:

function _input_f()
    return data
end

function _output_f(data)
end

function logic(
    p1, p2;
    inpit_data = _input_f(),
    output_f = _output_f()
)
    result = do_stuff_without_side_effects(p1, p2, inpit_data)
    output_f(result)
end

That’s very easy to test. Are there any disadvantage in that style?

Thanks! It looks like SimpleMock provides the cleanest tests since it doesn’t require modifications to the live code

This would redefine ModuleA, and I would also want to test the un-replaced ModuleA at some point