We have the implemetion:
@SpringBootApplication public class MockitoDemoApplication { public static void main(String[] args) { SpringApplication.run(MockitoDemoApplication.class, args); } } public class SomeBusinessImpl { private DataService dataService; public SomeBusinessImpl(DataService dataService ){ super(); this.dataService = dataService; } public int findTheGreatestFromAllData() { int[] data = dataService.retieveAllData(); int greatest = Integer.MIN_VALUE; for (int value : data) { if (value > greatest) { greatest = value; } } return greatest; } } public interface DataService { int[] retieveAllData(); }
And we want to test agaisnst it:
import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SomeBusinessMockTests { @Test public void testFindTheGreatestFromAllData() { DataService mockService = mock(DataService.class); when( mockService.retieveAllData()).thenReturn(new int[] {24, 6, 15}); SomeBusinessImpl businessImpl = new SomeBusinessImpl(mockService); int result = businessImpl.findTheGreatestFromAllData(); assertEquals(24, result); } }