通常在使用mockito时我会做类似的事情
Mockito.when(myObject.myFunction(myParameter)).thenReturn(myResult);
Run Code Online (Sandbox Code Playgroud)
是否有可能做一些事情
myParameter.setProperty("value");
Mockito.when(myObject.myFunction(myParameter)).thenReturn("myResult");
myParameter.setProperty("otherValue");
Mockito.when(myObject.myFunction(myParameter)).thenReturn("otherResult");
Run Code Online (Sandbox Code Playgroud)
因此,而不是仅仅使用参数来确定结果.它使用参数内的属性值来确定结果.
因此,当代码执行时,它的行为就像这样
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
}
Run Code Online (Sandbox Code Playgroud)
目前的解决方案,希望能提出更好的建议.
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){ …Run Code Online (Sandbox Code Playgroud) 我有这样的方法声明
private Long doThings(MyEnum enum, Long otherParam);
这个枚举
public enum MyEnum{
VAL_A,
VAL_B,
VAL_C
}
Run Code Online (Sandbox Code Playgroud)
问题:如何模拟doThings()通话?我无法匹敌MyEnum.
以下不起作用:
Mockito.when(object.doThings(Matchers.any(), Matchers.anyLong()))
.thenReturn(123L);
Run Code Online (Sandbox Code Playgroud)