引入包,測試版本:<powermock.version>1.7.1</powermock.version>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
測試類
//aService類的findStudyInfoById方法內部實現,調用了bDao的方法,
//單元測試只需關心aService當前層的正確性,bDao的正確性由它自己的單元測試保證,
//所以需要模擬一個假的bDao場景,來配合完成aService的單元測試
public class MockTest {
//注入要測試類,注意這裏注入寫實現類,不能寫接口注入
@InjectMocks
private AServiceImpl aService;
//mock這個類,幫助測試aService,而不測試實際的bDao
@Mock
private BDao bDao;
//初始化測試數據
@Before
public void initMock() {
MockitoAnnotations.initMocks(this);
Student student = new Student;
student.setName("測試");
student.setId(1);
//初始化mock類的場景,如果傳入一個int,返回自己mock的student數據
when(bDao.findStudyInfoById(anyInt())).thenReturn(student);
}
@Test
public void findStudyInfoById() throws Exception {
List<Student> students = aService.findStudyInfoById(1);
Assert.assertTrue(rstudents.size()==1);
}
}