用PowerMock mock final类constructors
也相对简单,直接贴代码
被测方法
public class EmployeeServiceWithParam { public void createEmployee(final Employee employee) { EmployeeDaoWithParam employeeDao = new EmployeeDaoWithParam(false, Dialect.MYSQL); employeeDao.insertEmploye(employee); } }
public class EmployeeDaoWithParam { public enum Dialect { MYSQL, ORACLE } public EmployeeDaoWithParam(boolean lazy, Dialect dialect) { throw new UnsupportedOperationException(); } public void insertEmploye(Employee employee) { throw new UnsupportedOperationException(); } }
测试类:
@PrepareForTest(EmployeeServiceWithParam.class) public class EmployeeServiceTestWithParamTest extends PowerMockTestCase{ @ObjectFactory public ITestObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } @Test public void test(){ EmployeeDaoWithParam employeeDao = PowerMockito.mock(EmployeeDaoWithParam.class); try { PowerMockito.whenNew(EmployeeDaoWithParam.class).withArguments(false, EmployeeDaoWithParam.Dialect.MYSQL) .thenReturn(employeeDao); EmployeeServiceWithParam service = new EmployeeServiceWithParam(); Employee employee = new Employee(); service.createEmployee(employee); Mockito.verify(employeeDao).insertEmploye(employee); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }