Testing is a very important part of coding, 📈 Test driven development is a very popular way of testing where you write test code before you actually write any ACTUAL code 😲.

A Test is supposed to ISOLATE one function of one service and make sure it works ✅. However, when this service depends on other services, it can be hard to isolate that one section and verify any error is coming from that service😞.

Here is an example of WHY we NEED to mock

  • Say we want to test service A which will transform a List of strings into a sentence.
  • Service A gets this list by calling Service B.
  • Service B is broken and returns null instead.
  • Our test for service A will fail even if we have properly implemented A.

How do we get around this?


By Mocking service B we can tell our test what to return when service B is called instead of relying on the actual implementation of B.

Case Study

We will be testing service A which prints out a sentence “Added {num1} and {num2} result is {sum}”. Service A will call 📞 Service B to get the sum of num1 and num2 to put in its sentence.

Service A

public class MyService {
	    private Unfinished unfinished;

	    public MyService(Unfinished unfinished) {
	        this.unfinished = unfinished;

	    public String doSomething(int a, int b) {
	        int result = unfinished.addNumbers(a, b);
	        return String.format("Added %d and %d result is %d", a, b, result);

#programming #mockito #testing #junit #java

Create Effective Test Code By Leveraging The Mockito Framework
1.45 GEEK