模拟大师,我对你有挑战! ;)
我有一个不带参数的方法,我想嘲笑它的行为,根据外部条件提供不同的结果。
例如,我想做这样的事情:
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()
,但无处可去。
非常感谢任何帮助!非常感谢!
答案 0 :(得分:8)
您可以使用自定义答案执行此操作
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";
}
}
答案 1 :(得分:-1)
if (sky.isBlue()) {
when(myMock.methodWithNoArguments()).thenReturn("blue");
} else if (sky.isGrey()) {
when(myMock.methodWithNoArguments()).thenReturn("grey");
}