Previously we have seen how to do Unit testing with Mockito;
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);
}
}
In this post, we are going to see, using annotation from Mockito to make testing easier:
@RunWith(MockitoJUnitRunner.class)
public class SomeBusinessMockTests { @Mock
DataService mockService; @InjectMocks
SomeBusinessImpl businessImpl; @Test
public void testFindTheGreatestFromAllData() { when( mockService.retieveAllData()).thenReturn(new int[] {24, 6, 15});
assertEquals(24, businessImpl.findTheGreatestFromAllData());
}
}
We need to place @RunWIth for the Test class, otherwise it won't work.
@Mock makes it easier to create a mock class.
@InjectMock makes it easier to inject created mock into a class.