我是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";
}


请协助。

最佳答案

您可以找到答案: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());
}

关于java - JMockit-第二次模拟并忽略第一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40463003/

10-11 22:26
查看更多