Assume that we build an application that needs integrating with e-commerce website like TIKI, Shopee, etc. The application has a problem in developing phase because whenever we execute full flow of code, we make a transaction with TIKI and we lost money. In order to circumstantiate this problem, we need to mock the action of making request to e-commerce website.
In traditional approach, when making a request to a website (I use HTTP protocol with synchronous communication for simplicity), we build the request by determine URL firstly, then we determine parameters to make the request, then we fire request to e-commerce website and wait for the response and take that response to execute the rest of the code
This coding style faces the difficulty I mentioned earlier and I do not have any idea how to fix this problem, so I use other way, instead of using make request code block, I delegate making request and getting response tasks to an object , and in testing phase, I just mock the making request by replace the object above by other object (this is in production environment).
By using object instead of block of code, I could mock the object’s methods easily, so what is mocking? Instead of making real request to the e-commerce website and waiting for the website to process your request and response to you, you just store the request and the expected response corresponding to the request you have made to database or memory, then you just execute the rest code flow (this is in testing environment).
We could drive code flow to mock object by making mock object class is subclass of real object class, then we override making request and getting response method of real object.
In order to make your code testable, you must wrap function or block of code in an object’s method, then you could make subclass of the wrapped class and override the method you need to mock. You could mock everything like date time, communication with other services, etc. You need mocking because it helps your test is consistence (imagine your test case fail today but it passes tomorrow because you did not mock get date time method). In next post, I will show you how to implement mock with Spring.