Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 有可能对不带参数的方法进行条件模拟吗?_Java_Mockito - Fatal编程技术网

Java 有可能对不带参数的方法进行条件模拟吗?

Java 有可能对不带参数的方法进行条件模拟吗?,java,mockito,Java,Mockito,莫基托大师们,我有一个挑战给你们 我有一个不带参数的方法,我想模拟它的行为,根据外部条件提供不同的结果 例如,我想做这样的事情: MyInterface myMock = mock(MyInterface.class); Sky sky = buildRandomSkyColor(); when(myMock.methodWithNoArguments()).thenReturn("blue").if(sky.isBlue()); when(myMock.methodWithNoArgumen

莫基托大师们,我有一个挑战给你们

我有一个不带参数的方法,我想模拟它的行为,根据外部条件提供不同的结果

例如,我想做这样的事情:

MyInterface myMock = mock(MyInterface.class);
Sky sky = buildRandomSkyColor();

when(myMock.methodWithNoArguments()).thenReturn("blue").if(sky.isBlue());
when(myMock.methodWithNoArguments()).thenReturn("grey").if(sky.isGrey());
在Mockito上是否可能有这种有条件的行为?我也尝试过使用
doStub()
doAnswer()
,但没有成功


非常感谢您的帮助!非常感谢

您可以使用自定义答案来执行此操作

if (sky.isBlue()) {      
  when(myMock.methodWithNoArguments()).thenReturn("blue");
} else if (sky.isGrey()) {
  when(myMock.methodWithNoArguments()).thenReturn("grey");
}
MyInterface myMock = mock(MyInterface.class);
Sky sky = buildRandomSkyColor();

when(myMock.methodWithNoArguments()).thenAnswer(new Answer<String>(){
    String answer(InvocationOnMock invocation) {
        if(sky.isBlue())
            return "blue";
        else
            return "gray";
    }
}
MyInterface myMock=mock(MyInterface.class);
天空=天空颜色();
当(myMock.methodWithNoArguments())。然后回答(new Answer()){
字符串应答(调用锁调用){
if(sky.isBlue())
返回“蓝色”;
其他的
返回“灰色”;
}
}

您可以使该方法返回一个依赖于类成员的值,例如(字段,其他方法)这是否有效?我推测OP希望被模拟的方法在调用时返回天空的颜色,而不是在创建模拟时返回天空的颜色(这是该代码所做的)。