Mock Final mockfinal相对来说就比较简单了,使用powermock来测试使用final修饰的method或class,比较简单,接口调用部分,还是service调用dao。 对于接口及场景这里就不细说了,特别简单。 service层 具体代码示例如下: 复制代码 package com.rongrong.powermock.mockfinal; /** * @author rongrong * @version 1.0 * @date 2019/11/27 21:29 */ public class StudentFinalService { private StudentFinalDao studentFinalDao; public StudentFinalService(StudentFinalDao studentFinalDao) { this.studentFinalDao = studentFinalDao; } public void createStudent(Student student) { studentFinalDao.isInsert(student); } } 复制代码 dao层 为了模拟测试,我在dao层的类加了一个final关键字进行修饰,也就是这个类不允许被继承了。 具体代码如下: 复制代码 package com.rongrong.powermock.mockfinal; /** * @author rongrong * @version 1.0 * @date 2019/11/27 21:20 */ final public class StudentFinalDao { public Boolean isInsert(Student student){ throw new UnsupportedOperationException(); } } 复制代码 进行单元测试 为了区分powermock与Easymock的区别,我们先采用EasyMock测试,这里先忽略EasyMock的用法,有兴趣的同学可自行去尝试学习。 使用EasyMock进行测试 具体代码示例如下: 复制代码 @Test public void testStudentFinalServiceWithEasyMock(){ //mock对象 StudentFinalDao studentFinalDao = EasyMock.createMock(StudentFinalDao.class); Student student = new Student(); //mock调用,默认返回成功 EasyMock.expect(studentFinalDao.isInsert(student)).andReturn(true); EasyMock.replay(studentFinalDao); StudentFinalService studentFinalService = new StudentFinalService(studentFinalDao); studentFinalService.createStudent(student); EasyMock.verify(studentFinalDao); } 复制代码 我们先来运行下这个单元测试,会发现运行报错,具体如下图显示: 很明显由于有final关键字修饰后,导致不能让测试成功,我们可以删除final关键再来测试一下,结果发现,测试通过。 使用PowerMock进行测试 具体代码示例如下: 复制代码 package com.rongrong.powermock.mockfinal; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * @author rongrong * @version 1.0 * @date 2019/11/27 22:10 */ @RunWith(PowerMockRunner.class) @PrepareForTest(StudentFinalDao.class) public class TestStudentFinalService { @Test public void testStudentFinalServiceWithPowerMock(){ StudentFinalDao studentFinalDao = PowerMockito.mock(StudentFinalDao.class); Student student = new Student(); PowerMockito.when(studentFinalDao.isInsert(student)).thenReturn(true); StudentFinalService studentFinalService = new StudentFinalService(studentFinalDao); studentFinalService.createStudent(student); Mockito.verify(studentFinalDao).isInsert(student); } } 复制代码 运行上面的单元测试时,会发现运行通过!! 优秀不够,你是否无可替代 软件测试交流QQ群:721256703,期待你的加入!! 欢迎关注我的微信公众号:软件测试君 分类: powermock 好文要顶 关注我 收藏该文 久曲健 关注 - 17 粉丝 - 217 +加关注 0 0 « 上一篇: PowerMock学习(五)之Verifying的使用 » 下一篇: adb devices无法连接mumu模拟器 posted @ 2019-11-27 22:53 久曲健 阅读(87) 评论(0) 编辑 收藏 https://www.cnblogs.com/kexing/p/11946197.htmlhttps://www.cnblogs.com/longronglang/p/11946208.html