PowerMock学习(六)之Mock Final的使用
2024-08-28 13:18:37
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);
}
}
运行上面的单元测试时,会发现运行通过!!
最新文章
- PHP JSON数组与对象的理解
- VMware10.06精简版安装后台运行
- Twitter Snowflake 的Java实现
- error while loading shared libraries: /usr/lib64/libc.so.6: invalid ELF header
- [转]单例模式——C++实现自动释放单例类的实例
- 【笨嘴拙舌WINDOWS】GDI映射方式
- <;PHP>;字符串处理代码
- JS帮你计算属相
- ACM POJ 2192 Zipper
- C#+QI的例子
- eclipse查看类源码出现failed to create the part&#39;s controls的解决方法
- display、visibility、visible区别
- Ubuntu如何安装vncserver
- 萌新 学习 vuex
- LAMP架构(三)
- Jenkins-job迁移
- Java java.lang.SecurityException: Prohibited package name
- java list集合运算
- 【Laravel5.5】 Laravel 在views中加载公共页面怎么实现
- webp格式