我们编写代码的时候,总会写一些工具类,为了方便调用喜欢使用static关键字来修饰对应方法。
那么现在举例说明,还是准备两个接口,第一个是查询学生总数,第二个是新增学生两个接口,具体示例代码如下:
packagecom.rongrong.powermock.mockstatic;importcom.rongrong.powermock.service.Student;/***@authorrongrong
*@version1.0
* @date 2019/11/23 8:08*/
public classStudentStaticService {/*** 获取学生总数
*@return
*/
public intgetStudentTotal(){returnStudentUtils.getStudent();
}/*** 创建一个学生
*@paramstudent*/
public voidcreateStudent(Student student){
StudentUtils.createStudent(student);
}
}
接着我们再来看看这个静态工具类StudentUtils,具体代码示例如下:
packagecom.rongrong.powermock.mockstatic;importcom.rongrong.powermock.service.Student;/***@authorrongrong
*@version1.0
* @date 2019/11/23 7:38*/
public classStudentUtils {/*** 获取学生总数
*@return
*/
public static intgetStudent(){throw newUnsupportedOperationException();
}/*** 创建一个学生
*@paramstudent*/
public static voidcreateStudent(Student student){throw newUnsupportedOperationException();
}
}
接下来我们用传统方式,来做单元测试,示例代码如下:
@Testpublic voidtestGetStudnetTotal(){
StudentStaticService staticService= newStudentStaticService();int studentTotal =staticService.getStudentTotal();
assertEquals(studentTotal,10);
}
@Testpublic voidtestCreateStudent(){
StudentStaticService staticService= newStudentStaticService();
staticService.createStudent(newStudent());
assertTrue(true);
}
接着运行下测试用例,结果肯定报错了,为什么报错,这里就不再细说了,参考之前文章,报错,如下图所示:
接下来我们使用powermock来进行测试,具体示例代码如下:
@Testpublic voidtestGetStudentWithMock(){//先mock工具类对象
PowerMockito.mockStatic(StudentUtils.class);//模拟静态类调用
PowerMockito.when(StudentUtils.getStudent()).thenReturn(10);//构建service
StudentStaticService service = newStudentStaticService();int studentTotal =service.getStudentTotal();
assertEquals(10,studentTotal);
}
@Testpublic voidtestCreateStudentWithMock(){//先模拟静态工具类
PowerMockito.mockStatic(StudentUtils.class);//模拟调用
PowerMockito.doNothing().when(StudentUtils.class);//构建service
StudentStaticService service = newStudentStaticService();
Student student= newStudent();
service.createStudent(student);//这里用powermock来验证,而不是mock,更体现了powermock的强大
PowerMockito.verifyStatic();
}
再次运行,测试通过,如下图所示:
运行之前先让powermock为我们准备了StudentUtils工具类,而且采用mockstatic的方法,最后我们用powermock.verifyStatic()验证,而不是mock,更体现了powermock的强大。