import java.util.Random; public class CodeWithPrivateMethod { public void meaningfulPublicApi() { if (doTheGamble("Whatever", 1 << 3)) { throw new RuntimeException("boom"); } } private boolean doTheGamble(String whatever, int bin…
在编写代码时,经常需要调用别人已经写好的工具类,而这些工具提供的方法经常是static方法,在这里,直接贴出<PowerMock实战手册>中的例子 待测试方法: public class EmployeeService { public int getEmployeeCountWithStatic() { return EmployeeUtils.getEmployeeCount(); } } 引用的工具类 public class EmployeeUtils { public static…
有些对象需要mock的对象是由工厂方法产生出来的,而工厂方法一般是静态方法,这时候就需要同时mock工厂方法及对象 被测方法: public class EmployeeServiceFactory { public void saveEmployee(Employee employee){ EmployeeDaoFactory dao = EmployeeDaoFactory.newInstance(); method("powermock"); dao.addEmployee(em…
在开发时,经常遇到这种情况,被测试方法所调用的类不是通过构造注入的,而是通过临时new出来的,如下面待测方法: public class EmployeeService { private EmployeeDao employeeDao; public int getTotalEmployeeWithTempVariable() { EmployeeDao employeeDao = new EmployeeDao(); return employeeDao.getTotal(); } } em…