During week 10, we experimented with stubs and mocks. Stubs and mocks are two forms of testing doubles that allow a team to write tests before the whole program has been written. Stubs and mocks simulate the code’s fleshed out methods and allow for testing methods to be written in advance.
Stubs are methods or classes that are either empty or return a set value so they can run and be tested. Stubs are state testers and focus on testing the outcome of methods. Mocks are more dynamic, the test block can define what it wants the outcome of any method to be and then test for that outcome. It can also test for multiple set outcomes in the same block. Mocks are behavior testers and test the interactions between methods, rather than the outcome.
The reference I found was a blog that compares and contrasts stubs and mocks by BairesDev to get a better idea of their use cases. They explained what stubs and mocks are, the advantages and disadvantages of each, and the situations to use both of them.
Advantages for stubs are their predictability and isolating the method. They will always return what you are expecting because of how simple they are. Since stubs do not involve any other calls or methods, they are great at isolating testing to just that method. Disadvantages are user error and the lack of behavior testing. The user might have a discrepancy in what they return in the stub and what they expect in the test. If your method needs to interact with other methods, stubs are not great for testing behavior because they only look at the outcome.
Advantages for mocks are being better at testing subtle bugs and issues and testing the interactions between methods in your code. Since mocks are behavioral tests, if the methods don’t interact how they’re expected to, the test will not pass, which goes beyond what stubs do. Disadvantages are increased complexity and brittle tests. Mocks make your tests more complex than if you were testing the fully written code, which may take more time to adapt to once the program is finished. Brittle tests can occur if tests are too connected to the mock expectations, and small changes can cause a lot of errors.
Overall, stubs are useful when testing independent methods and those that only need to be tested for the outcome. Mocks are useful when methods are dependent on others and can find errors that might not show up if you were just testing outcomes. Both are great when writing tests, but have different applications and both should be used when testing programs.
Source: https://www.bairesdev.com/blog/stub-vs-mock/
From the blog CS@Worcester – ALIDA NORDQUIST by alidanordquist and used with permission of the author. All other rights reserved by the author.