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?
import Main: ModuleA
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()
There are several options for Julia mocking libraries:
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.
I’m doing something like this:
inpit_data = _input_f(),
output_f = _output_f()
result = do_stuff_without_side_effects(p1, p2, inpit_data)
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