PowerMock笔记-final修饰类

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
 */
final public class EmployeeDao {
    /**
     * 查询员工数
     * @return
     */
    public int getEmployeeCount() {
        throw new UnsupportedOperationException();
    }

    /**
     * 添加员工
     * @param employee
     */
    public void addEmployee(Employee employee) {
        throw new UnsupportedOperationException();
    }
}

import vip.fkandy.powermock.common.Employee;

/**
 * @author chenjianfei
 */
public class EmployeeService {
    private EmployeeDao employeeDao;

    public EmployeeService(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

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

    public void addEmployee(Employee employee) {
        employeeDao.addEmployee(employee);
    }

}
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.*;

/**
 * final
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeService.class,EmployeeDao.class})
public class EmployeeServiceTest {

    @Mock
    private EmployeeDao employeeDao;

    /**
     * Mockito
     *
     *  org.mockito.exceptions.base.MockitoException:
        Mockito cannot mock this class: class vip.fkandy.powermock.final_class.EmployeeDao.

        Mockito can only mock non-private & non-final classes.
        If you're not sure why you're getting this error, please report to the mailing list.
     */
    @Test
    @Ignore
    public void getEmployeeCountWithMockito() {
        MockitoAnnotations.initMocks(this);
        EmployeeService employeeService = new EmployeeService(employeeDao);
        Mockito.when(employeeDao.getEmployeeCount()).thenReturn(10);
        int result = employeeService.getEmployeeCount();
        assertEquals(10, result);
    }

    /**
     * PowerMockito
     * 1.需要添加@RunWith(PowerMockRunner.class)
     * 和@PrepareForTest({EmployeeService.class,EmployeeDao.class})注解
     */
    @Test
    public void getEmployeeCountWithPowerMockito() {
        EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
        PowerMockito.when(employeeDao.getEmployeeCount()).thenReturn(10);

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


更多,请参看https://github.com/powermock/powermock/wiki/MockFinal



你可能感兴趣的:(PowerMock)