Search code examples
unit-testingagilemocking

Is the use of mocks a good programming practice or just a different way to do it?


Would you guys say that the use of mocks is better than not using mocks? Is mocking used only in unit testing or could it be used directly in the original project as the real object and switch it after?

I've been reading here and there and the most attractive thing about mocking I found was the layer isolation.


Solution

  • Would you guys say that the use of mocks is better than not using mocks?

    Is driving a motorbike better than driving a car? It depends what you're trying to achieve :).

    Why use mocks?

    Mocks versus state-based testing: While I generally like state-based testing because it feels more solid/straight forward, it's often the case that using mocks is the only way to verify that a unit of code performs its role correctly. Why? Well, when designing with the tell, don't ask principle in mind, classes often do not expose enough data to verify your expectations, so the only way to verify it's working properly is to check its behaviour/interactions with other collaborators.

    A good example is a class that sends emails when an order is finalised -- the class won't have a "number of emails sent" property or anything similar, so you need to check that the appropriate method call was made. Mocks set expectations on the interactions.

    While you can test the interactions by hand-rolling your own test double classes that expose this data (e.g. create a type that implements the required interface, then push method call information into a list, then assert against the stored state), mocking frameworks speed up the process by allowing us to only fill in the bits we actually care about.

    Should I use mocks in production code?

    Is mocking used only in unit testing or could it be used directly in the original project as the real object and switch it after?

    If by "mocking" you mean using a "a 'fake' type that can be swapped in and behave in a sensible manner", then yes -- I've often used 'fake' types such as an in memory dictionary to substitute for database connections and so forth. They can act as a useful stopgap in non-live production code.

    Similarly, if you program to an interface, you can create a working skeleton of an application with stubbed out functionality. This helps get a full programming structure fleshed out without having to focus on details. You can substitute in the real implementation once it's available (though expect some integration errors if you're not backed by integration tests).

    If, on the other hand, by "mocking" you mean "using a mocking framework in the production code", then no -- I wouldn't recommend doing that, I'd hand-write the fake implementations and stay free of the dependency, plus it'll be easier to reason about and debug.