我有一些与此非常相似的逻辑,其中我有可以在请求期间更新的单元和不同字段。
public class Unit {
int x;
int y;
public void updateX(int x) {
this.x += x;
}
public void updateY(int y) {
this.y += y;
}
}
public class UpdateUnitService{
public Unit update(int delta, BiConsumer<Unit, Integer> updater){
Unit unit = getUnit(); //method that can`t be mocked
updater.accept(unit, delta);
// some save logic
return unit;
}
}
public class ActionHandler{
private UpdateUnitService service;
public Unit update(Request request){
if (request.someFlag()){
return service.update(request.data, Unit::updateX);
}else {
return service.update(request.data, Unit::updateY);
}
}
}
而且我需要编写一些测试来检查调用了哪个函数。像这样。
verify(service).update(10, Unit::updateX);
verify(service).update(10, Unit::updateY);
如何使用 ArgumentCaptor 或其他工具编写这样的测试?
最佳答案
没有办法(在当前的 Java 实现中)比较两个 lambda 和/或方法引用。有关详细信息,请阅读 this post .
您可以做的(如果 getUnit()
是不可模拟的)是检查两个方法引用在调用时是否做同样的事情。但是您无法验证任何未知的副作用。
public void verifyUpdateTheSameField(Integer value, BiConsumer<Unit, Integer> updater1, BiConsumer<Unit, Integer> updater2) {
Unit unit1 = // initialize a unit
Unit unit2 = // initialize to be equal to unit1
actual.accept(unit1, value);
expected.accept(unit2, value);
assertThat(unit1).isEqualTo(unit2);
}
然后:
ArgumentCaptor<Integer> valueCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<BiConsumer<Unit, Integer>> updaterCaptor = ArgumentCaptor.forClass(BiConsumer.class);
verify(handler.service, times(1)).update(valueCaptor.capture(), updaterCaptor.capture());
verifyUpdateTheSameFields(valueCaptor.getValue(), updaterCaptor.getValue(), Unit::updateX);
注意:此方法仅在 Unit
覆盖 equals
时有效。
关于java - 验证 BiConsumer 作为单元测试中的方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54312623/