欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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>

待测模拟测试类方法
powermock
Mock的方法测试
powermock
powerMock方法
powermock
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);
    }

模拟静态方法

powermock
powermock

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();
    }
}
相关标签: 单元测试