4. Mocking advanced
Based on the previous examples, there might and will be more complex problems in unit testing. One of the big issues and mainly this is the crux of the issue is that, controlling the external dependencies. Whether these are written by someone at the company or these would are 3rdParty dependencies, during unit testing these need to be controlled. Therefore let’s take a look at the usual suspects that might one might come across during implementing unit tests for various problems
Supporting video
Mocking static functions
Mockint static functions can be quite tricky sometimes, which will be demonstrated in StaticUtilsTest.java. The main problem with the static functions inside StaticUtils is that, during calls or instantiation of a static method or class, they will have unique characteristics compared to non-static ones. They can be accessed without the instantiation of a class or any type, it can only access static data and they belong to the class or “namespace” where they reside. These can be quite tricky to mock, because there is no instance to tweak here. To overcome this caveat mockito since version 5 does give us the functionality to mock static functions with the MockedStatic type allocator and mockStatic functionality. After the type has be declared with the MockedStatic allocator one can use the usual directives to alter the behaviour of the class under test.
Tasks 1.
- Test the static method
rangeinside StaticUtils.java
Supporting video
Mocking the GetHttpRequest() function
This example single handedly to most complicated task that you might face during your unit testing endeavours. As described in Mocking basics the GetHttpRequest() function has challenging problems by generally instantiating a lot of classes locally, which are final and abstract as well. To overcome these issues one can utilize various techniques to climb this mountain of “trainwreck of mocks” situation as follows
- Since there are multiple classes that need to be mocked away and they are encapsulated, this approach looks like backpropagation in machine learning. So we start from the innermost mock and go on to the outermost step-by-step.
- First we mock
URLConnectionin NetworkConnectionTest.java - As a next step
InputStreamis mocked so when we return it at line 46 in the CUT we will have control over it - The main hurdle is solved in the line 28 where the
MockedConstructionis used with combination with a lambda capturing themockandcontextto implement mocking.
TL;DR the main problem was the dynamic allocation of a public final class the URL class, which was hard to hijack.
Tasks 2.
- Finish the chain of mocks technique to gain complete control over the
GetHttpRequest()function and it’s internals