问题
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