简体   繁体   English

在jmockit中,如何模拟void方法在第一个调用而不在后续调用上引发Exception?

[英]In jmockit, how can I mock a void method to throw an Exception on the first call and not to on subsequent calls?

I can make a void method throw an exception like this: 我可以使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");
        }
    };
}

however, if I want the void method to throw an exception on the first call, but not on subsequent calls, these approaches do not seem to work: 但是,如果我希望void方法在第一次调用时引发异常,但在后续调用中不引发异常,则这些方法似乎不起作用:

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

or 要么

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

They both result in no exception being thrown. 它们都不会引发异常。

Is this possible with JMockit? JMockit有可能吗? It's not clear to me from the docs here and here . 这里这里的文档对我来说还不清楚。

The following test works fine for me: 以下测试对我来说效果很好:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM