dea*_*mon 0 java collections static-methods jmockit mocking
我想测试,无论是否Collection.sort(...)使用JMockit调用:
final List<Employee> employees = new ArrayList<>();
new Expectations() {
{
Collections.sort((List<Employee>) any);
result = employees;
}
};
assertThat(EmployeeRepository.getAllOrderedByName()).isSameAs(employees);
Run Code Online (Sandbox Code Playgroud)
这是我测试中的示例存储库的实现:
public class EmployeeRepository {
private static List<Employee> employees = new ArrayList<>();
public static List<Employee> getAllOrderedByName() {
Collections.sort(employees);
return employees;
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行单元测试时,我得到一个NullPointerException Collections.sort.由于调试器永远不会到达方法中的断点,因此在自我模拟中似乎是一个问题getAllOrderedByName.
如何使用anyJMockit存储静态方法?
在您的测试代码中,Collections永远不会指定类被模拟.因此,该Collections.sort((List<Employee>) any);调用抛出NPE,因为值为anynull并且执行实际sort方法.
您可能假设在期望块内的任何方法调用都会被自动模拟,但这不是 JMockit API的工作方式.相反,你需要明确指定哪些类型的嘲笑,宣称一个模拟现场或注释的一个模拟参数@Mocked,@NonStrict,@Cascading,或@Capturing.
此外,在这种情况下Collections.sort是一个返回的方法void,因此记录它的返回值是没有意义的.
此外,写这样的测试并不是我推荐的.它应该验证生成的集合是否已排序,而不是模拟Collections类.
| 归档时间: |
|
| 查看次数: |
5835 次 |
| 最近记录: |