powermock
程序员文章站
2024-03-15 19:38:06
...
添加Maven依赖
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
</dependency>
待测模拟测试类方法
Mock的方法测试
powerMock方法
返回值为 void 方法模拟
@Test
public void testSaveUserWithPowerMock(){
UserDao uDao = PowerMockito.mock(UserDao.class);
User user = new User();
PowerMockito.doNothing().when(uDao).insertUser(user);
UserService userService = new UserService(uDao);
userService.saveUser(user);
Mockito.verify(uDao).insertUser(user);
}
模拟静态方法
public class UserDao {
public static int getCount() {
throw new UnsupportedOperationException();
}
public static void insertUser(User user) {
throw new UnsupportedOperationException();
}
}
public class UserService {
public int queryUserCount() {
return UserDao.getCount();
}
public void saveUser(User user) {
UserDao.insertUser(user);
}
}
Test
@RunWith(PowerMockRunner.class)
@PrepareForTest({UserService.class, UserDao.class})
public class UserServiceTest {
@Test
public void testQueryUserCount() throws Exception {
mockStatic(UserDao.class);
when(UserDao.getCount()).thenReturn(10);
UserService userService = new UserService();
int result = userService.queryUserCount();
assertEquals(10, result);
}
@Test
public void testSaveUser() throws Exception {
mockStatic(UserDao.class);
User user = new User();
doNothing().when(UserDao.class);
UserService userService = new UserService();
userService.saveUser(user);
PowerMockito.verifyStatic();
}
}
推荐阅读
-
testng + mockito + powerMock
-
powermock
-
SpringBoot配置Jacoco生成测试覆盖率报告(包括Powermock、Mockito用例)
-
power mock 使用 静态方法 博客分类: powermock powermock
-
java junit PowerMock 博客分类: Junit4 javajunitPowerMock
-
PowerMock用法 博客分类: 敏捷开发 powermockmockeasymock
-
EasyMock gets more power with PowerMock. javaeasymockpowermockjunit
-
PowerMock常见用法 博客分类: Junit4 PowerMockPowerMock常用方法
-
为啥写单元测试和工具 博客分类: 技术点滴 单元测试powermock
-
Mockito java.lang.NoSuchMeThodError 博客分类: powermock powermock