我是JMockit的新手,并希望在第二次运行时模拟一个java方法,并在第一次调用它时忽略它。
示例我想在下面的"第二次"返回一个字符串时模拟下面的runningMethod()。并执行其他一些操作。
@Mock publicMethod()
{
//do something if calling runningMethod() 2nd time.
}
int count = 1;
public String runningMethod()
{
if (count == 1) return "first time";
if (count == 2) return "second time";
i++;
return "some answers";
}
请帮忙。
答案 0 :(得分:1)
您可以找到答案:http://www.baeldung.com/jmockit-expectations
但这是该帖子的相关代码:
public interface ExpectationsCollaborator{
String methodReturnsString();
int methodReturnsInt();
}
@Test
public void testResultAndReturns(@Mocked Foo mock){
new StrictExpectations() {{
mock.methodReturnsString();
result = "foo";
result = new Exception();
result = "bar";
mock.methodReturnsInt(); result = new int[] { 1, 2, 3 };
mock.methodReturnsString(); returns("foo", "bar");
mock.methodReturnsInt(); result = 1;
}};
assertEquals("Should return foo", "foo", mock.methodReturnsString());
try {
mock.methodReturnsString();
} catch (Exception e) { }
assertEquals("Should return bar", "bar", mock.methodReturnsString());
assertEquals("Should return 1", 1, mock.methodReturnsInt());
assertEquals("Should return 2", 2, mock.methodReturnsInt());
assertEquals("Should return 3", 3, mock.methodReturnsInt());
assertEquals("Should return foo", "foo", mock.methodReturnsString());
assertEquals("Should return bar", "bar", mock.methodReturnsString());
assertEquals("Should return 1", 1, mock.methodReturnsInt());
}