【发布时间】:2026-02-03 00:50:02
【问题描述】:
通常在使用 mockito 时,我会做类似的事情
Mockito.when(myObject.myFunction(myParameter)).thenReturn(myResult);
有没有可能做一些类似的事情
myParameter.setProperty("value");
Mockito.when(myObject.myFunction(myParameter)).thenReturn("myResult");
myParameter.setProperty("otherValue");
Mockito.when(myObject.myFunction(myParameter)).thenReturn("otherResult");
所以而不是仅仅使用参数来确定结果。它使用参数内的属性值来确定结果。
所以当代码执行时,它的行为是这样的
public void myTestMethod(MyParameter myParameter,MyObject myObject){
myParameter.setProperty("value");
System.out.println(myObject.myFunction(myParameter));// outputs myResult
myParameter.setProperty("otherValue");
System.out.println(myObject.myFunction(myParameter));// outputs otherResult
}
目前的解决方案,希望可以提出更好的建议。
private class MyObjectMatcher extends ArgumentMatcher<MyObject> {
private final String compareValue;
public ApplicationContextMatcher(String compareValue) {
this.compareValue= compareValue;
}
@Override
public boolean matches(Object argument) {
MyObject item= (MyObject) argument;
if(compareValue!= null){
if (item != null) {
return compareValue.equals(item.getMyParameter());
}
}else {
return item == null || item.getMyParameter() == null;
}
return false;
}
}
public void initMock(MyObject myObject){
MyObjectMatcher valueMatcher = new MyObjectMatcher("value");
MyObjectMatcher otherValueMatcher = new MyObjectMatcher("otherValue");
Mockito.when(myObject.myFunction(Matchers.argThat(valueMatcher))).thenReturn("myResult");
Mockito.when(myObject.myFunction(Matchers.argThat(otherValueMatcher))).thenReturn("otherResult");
}
【问题讨论】:
-
从你的问题中不清楚要模拟的对象是什么,被测对象是什么。
-
我添加了一个编辑来演示我希望它的行为方式。
-
无论以何种方式阅读本文,在我看来,您都在嘲笑您要测试的对象。除非你有令人信服的理由这样做,并且你这样做的方式不会妨碍对象的原始行为,否则首先会违背测试的目的。
-
是的,@ylabidi 确实有道理。您想做的事情是可能的,但它“感觉”或“闻起来”有点尴尬。你应该退后一步,问问这是否以及为什么真的有必要。这就是测试的原因之一:糟糕的设计通常会导致测试类变得困难或尴尬。
-
如果您想提出更好的建议,您不应该接受答案。一旦你接受了一个答案,大多数人就不会费心提供一个不同的答案。对于它的价值,我相信有更好的方法 - 我可能会稍后发布答案。