JMockit:模拟方法

时间:2016-07-01 15:57:30

标签: jmockit

JMockit可以修改它嘲笑的方法的参数吗?修改它模拟的方法的返回值肯定很容易,但如何修改参数本身呢?我知道至少可以使用Verifications捕获和测试模拟参数,但事实发生后会发生这种情况。

这是我的简化代码:

class Employee{
    Integer id;
    String department;
    String status;

    //getters and setters follow
}

我想测试的方法:

  public int createNewEmployee() {
        Employee employee = new Employee();
        employee.setDepartment("...");
        employee.setStatus("...");
        //I want to mock employeeDao, but the real DAO assigns an ID to employee on save
        employeeDao.saveToDatabase(employee);
        return employee.getId(); //throws NullPointerException if mocked, because id is null
    }

1 个答案:

答案 0 :(得分:2)

Delegate上录制期望时,使用分配到result字段的employeeDao.saveToDatabase(...)对象。委托方法(具有任意名称)应声明Employee emp参数;然后只需使用您想要的任何ID值调用emp.setId(...)

例如,请参阅documentation