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
How do we get around this?
MOCKING!!!
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.
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.
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