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

a 夏天 提交于 2019-12-24 15:32:34

问题


I can make a void method throw an exception like this:

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:

@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? It's not clear to me from the docs here and here.


回答1:


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


来源:https://stackoverflow.com/questions/35095108/in-jmockit-how-can-i-mock-a-void-method-to-throw-an-exception-on-the-first-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!