Mocks and Stubs

Testing is an important part of coding, and software development. Sometimes though, testing can be tedious work, and creating tests that work properly according to your code can be difficult. This should be the case anyways, as testing is a key aspect to software development, but what if you could do this process a bit more quickly. Creating mocks and stubs can be a good alternative, especially if multiple people are working on different parts of the same project or software. 

In this blog post, June Jung touches upon mock and stub testing. They describe mock testing as “creating a fake version of an external or internal service that can stand in for the real one,” and stub testing as “creating a stand-in, but a stub only mocks the behavior, but not the entire object.” The whole idea of mocks and stubs is to create a fake or a stand-in that does not do anything. This may seem strange, having completely useless methods and functions, but the thing we want to test for is the interactions between the methods and functions. Seeing whether or not they return the correct return values, call the correct methods, etc. This will reduce the amount of time needed to test the functions, compared to testing full, complete functions and methods. Jung says that by using mocks and stubs, you can “reproduce more complex scenarios more easily. For instance, it is much easier to test the many error responses you might get from the filesystem than to actually create the condition.” Jung says this specifically for unit + component testing, but this principle can apply for any kind of testing. In fact, they touch upon multiple cases where mocks and stubs can be used, such as internal functions, integration testing, and contract-based testing. They also provide code examples, and graphs to help you visualize the concept, which can be helpful.

Jung says that as your code grows, your tests should as well, meaning you shouldn’t continue to use the same tests as you continue to write more code, losing the mocks and the stubs. That being said, they’re good to help start, providing a base to continue with. Jung’s blog post is a good resource, as they also have linked another post that goes into the difference between mocks and stubs. It also appears that their blog post is part of multiple posts, which may be worth looking at for more information.


Leave a comment

Design a site like this with WordPress.com
Get started