在jmockit中,如何模拟void方法在第一次调用时抛出异常而不是在后续调用中抛出异常?

时间:2016-01-29 22:21:57

标签: java jmockit

我可以使void方法抛出这样的异常:

class TestClass {
    public void send(int a) {};
}

@Mocked
private TestClass mock;

@Test
public void test() throws Exception {
    new Expectations() {
        {
            mock.send(var1);
            this.result = new Exception("some exception");
        }
    };
}

但是,如果我希望void方法在第一次调用时抛出异常,而不是在后续调用中抛出异常,则这些方法似乎不起作用:

@Test
public void test() throws Exception {
    new Expectations() {
        {
            mock.send(var1);
            this.result = new Exception("some exception");
            this.result = null;
        }
    };
}

@Test
public void test() throws Exception {
    new Expectations() {
        {
            mock.send(var1);
            results(new Exception("some exception"), new Object());
        }
    };
}

它们都不会导致抛出任何异常。

JMockit可以实现吗?我不清楚文档herehere

1 个答案:

答案 0 :(得分:1)

以下测试适用于我:

static class TestClass { void send(int a) {} }
@Mocked TestClass mock;
int var1 = 1;

@Test
public void test() {
    new Expectations() {{
        mock.send(var1);
        result = new Exception("some exception");
        result = null;
    }};

    try { mock.send(var1); fail(); } catch (Exception ignore) {}
    mock.send(var1);
}