Mocking - a Starter for Ten

A very basic intro for complete beginners. Part of the Starter for Ten series.

What is mocking and what are mocks?

Mocking is a testing thing.

Let's say you've written some code and now you want to test it. But the code you've written works by interacting with some other code in another file. Or maybe two or three other bits of code in two or three other files.

All you want to do is test your original bit of code. You don't want to have to worry about the other bits.

This is where mocking comes in. You create pretend or 'mock' versions of those other bits. These pretend mocks don't recreate everything that the other code does, but it does recreate some of the simple bits, if you tell it to.

For example, if one of the other bits of code does lots of fancy stuff that eventually returns a value, say a string of text, to your original code, you would set up your mock so that all it did was return a dummy string of text. And then you would create a second mock for the second bit of other code, and the third, and so on.

That way, the original bit of code that you are testing can carry on doing its thing, using the dummy value your mock has given it. You can carry on testing that your original code does what it is supposed do.

How do you do mocking?

Typically, you would use a 'mocking framework'. In the Java world, the most popular one is called Mockito, and you would use it on top of JUnit, which gives you all the basic unit testing tools you need. In the JavaScript world, the popular testing framework Jest has mocking built in.

What even is a 'mocking framework'? It's a bunch of code that some clever developers have written for you. You can just use it in your own code, straight out of the box and it will do the job for you. You just have to 'import' it (see the example below). The documentation will tell you how to use it.

Here is an example of basic mocking from the Mockito docs:

//Import Mockito so we can use it
import static org.mockito.Mockito.*; 

//Create a mock 
List mockedList = mock(List.class); 

//Use that mock 
mockedList.add("one"); 
mockedList.clear();

//Verify that the 'add' and 'clear' methods were actually called above
verify(mockedList).add("one"); 
verify(mockedList).clear();

Want to learn more?

https://youtu.be/O3s5PR4JDOo