Tuesday, September 28, 2021

Why to use mockito?

 Suppose we have a class which have a dependency which will provide some data and based on those data we will do some work,

public class SomeBusinessImpl {

private DataService dataService;//dependency

public SomeBusinessImpl(DataService dataService) {

super();

this.dataService = dataService;

}

int[] data = dataService.retrieveAllData();

int greatest = Integer.MIN_VALUE;

int findTheGreatestFromAllData() {

for (int value : data) {

if (value > greatest) {

greatest = value;

}

}

return greatest;

}

}

interface DataService {

int[] retrieveAllData();

}

Test class:

class SomeBusinessTest {

@Test

public void findGreatestFromAllData() {

SomeBusinessImpl someBusiness = new SomeBusinessImpl(new DataServiceStub());

int result = someBusiness.findTheGreatestFromAllData();

assertEquals(24, result);

}

}

class DataServiceStub implements DataService {//Implementation of DataService

@Override

public int[] retrieveAllData() {

return new int[] { 24, 10, 12 };

}

}

What to do if the logic inside DataServiceStub changed. Every time we will need to give different implementation of the DataService . But if we can create mock using mockito . By using mockito we can easily create dummy data .


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...