Below is a simple class which uses stub for Testing
- Below is a simple business implementation class which EmployeeDetailsImpl which uses EmployeeService API methods
- Now to test EmployeeDetailsImpl we need to substitude the methods in service class with stub methods for which we create EmployeeServiceStub
- EmployeeServiceStub is a stub class which implements the EmployeeService and provide method definitions
- EmployeeDetailsImplTest is the test class for EmployeeDetailsImpl which performs the unittest for methods in EmployeeDetailsImpl
EmployeeService.java
import java.util.List; public interface EmployeeService { public List<String> GetEmployeeDetails(); }
EmployeeDetailsImpl.java
import com.mugil.org.api.EmployeeService; import java.util.List; public class EmployeeDetailsImpl { EmployeeService employeeService; public EmployeeDetailsImpl(EmployeeService pEmployeeService){ this.employeeService = pEmployeeService; } public List<String> getEmployeeList(){ List<String> arrEmp = this.employeeService.GetEmployeeDetails(); return arrEmp; } }
EmployeeServiceStub.java
import java.util.Arrays; import java.util.List; public class EmployeeServiceStub implements EmployeeService{ @Override public List<String> GetEmployeeDetails() { return Arrays.asList("Mugil", "Mani", "Vinu"); } }
EmployeeDetailsImplTest.java
import com.mugil.org.api.EmployeeServiceStub; import org.junit.Test; import static org.junit.Assert.assertEquals; public class EmployeeDetailsImplTest { @Test public void getEmployeeList_success(){ EmployeeServiceStub employeeService = new EmployeeServiceStub(); EmployeeDetailsImpl employeeDetailsImpl = new EmployeeDetailsImpl(employeeService); assertEquals(3, employeeDetailsImpl.getEmployeeList().size()); } }
Dis-advantage of the above implementation
- In the above implementation when ever new method is added to the API interface, it should be added to the EmployeeServiceStub which implements EmployeeService
- EmployeeServiceStub is extra java file which should be taken care, incase there are multiple services used in class multiple service stub needs to be created
Replacing stub with mocks
In the below code, the same stub service(EmployeeServiceStub.java) is replaced with mock class and its methods are replaced using when and return.This prevents the need for another class
EmployeeDetailsImplTest.java
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class EmployeeDetailsImplTest { @Test public void getEmployeeList_success(){ //Replacement code for Stub class EmployeeService employeeService = mock(EmployeeService.class); when(employeeService.GetEmployeeDetails()).thenReturn(Arrays.asList("Mugil", "Mani", "Vinu")); EmployeeDetailsImpl employeeDetailsImpl = new EmployeeDetailsImpl(employeeService); assertEquals(3, employeeDetailsImpl.getEmployeeList().size()); } }