[Unit Testing] Using Mockito Annotations - @Mock, @InjectMocks, @RunWith

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.

上一篇:OpenGL10-骨骼动画原理篇(1)


下一篇:Eclipse sysout 和 fore 不起作用