PowerMock笔记-静态方法


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author chenjianfei
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private String name;
    private Integer age;
}
import vip.fkandy.powermock.common.Employee;

/**
 * @author chenjianfei
 */
public class EmployeeDao {
    /**
     * 查询员工数
     * @return
     */
    public static int getEmployeeCount() {
        throw new UnsupportedOperationException();
    }

    /**
     * 添加员工
     * @param employee
     */
    public static void addEmployee(Employee employee) {
        throw new UnsupportedOperationException();
    }
}
import vip.fkandy.powermock.common.Employee;

/**
 * @author chenjianfei
 */
public class EmployeeService {

    public int getEmployeeCount() {
        return EmployeeDao.getEmployeeCount();
    }

    public void addEmployee(Employee employee) {
        EmployeeDao.addEmployee(employee);
    }
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import vip.fkandy.powermock.common.Employee;

import static org.junit.Assert.*;

/**
 * Mock静态方法
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(EmployeeDao.class)
public class EmployeeServiceTest {
    /**
     * 有返回值的测试用例
     */
    @Test
    public void getEmployeeCount() {
        //Enable static mocking for all methods of a class
        PowerMockito.mockStatic(EmployeeDao.class);
        PowerMockito.when(EmployeeDao.getEmployeeCount()).thenReturn(10);

        EmployeeService employeeService = new EmployeeService();
        int result = employeeService.getEmployeeCount();
        assertEquals(10, result);
    }

    /**
     * 无返回值的测试用例
     */
    @Test
    public void addEmployee() {
        PowerMockito.mockStatic(EmployeeDao.class);
        //Use doNothing() for setting void methods to do nothing
        //
        PowerMockito.doNothing().when(EmployeeDao.class);

        EmployeeService employeeService = new EmployeeService();
        employeeService.addEmployee(new Employee("Andy", 28));
        //Verifies certain behavior of the mockedClass happened once,
        // Alias to verifyStatic(classMock, times(1))
        PowerMockito.verifyStatic(EmployeeDao.class);
    }
}
更多,请参看 https://github.com/powermock/powermock/wiki/MockStatic


你可能感兴趣的:(PowerMock)