I have been using JMockit until now.
In particular, another class called in the method under test was mocked and used to cause exception on the second time.
The following source code using JMockit works:
public class TestClass {
@ Test
public void test01 (@MockedTargetSubClass mock) {
//Arrange
new Expectations() {{
mock.someMethod((String[])any);
result=newObject[]{null,newNullPointerException}//Exception Occurs Second Time
}}
// Act
Target target = new Target();
target.targetMethod(); // NullPointerException occurs here (as expected)
// Assert
/* Confirm that Exception originally occurs here */
}
}
However, due to environmental problems, we have no choice but to use Mockito instead of JMockit.
Here's the code I tried to do the same test:
The following source code using Mockito will not work:
public class TestClass {
@ Test
public void test01(){
//Arrange
TargetSubClass mock=mock(TargetSubClass.class);
dothrow(new NullPointerException()) .when(mock).someMethod(any()); // Originally, I wanted to release it for the second time, but even the first time failed.
// Act
Target target = new Target();
target.targetMethod();//Exception does not occur here
// Assert
/* Confirm that Exception originally occurs here */
}
}
Does anyone know how to solve this problem?
Thank you for your advice.
I don't understand what the code in the question text really wants to do, but
I think is the applicable one.
when(mock.someMethod(any())))
.thenReturn(null)
.thenThrow(new NullPointerException());
For methods with a return value of void
:
doNothing().doThrow(new NullPointerException())
.when(mock).someMethod(any());
© 2024 OneMinuteCode. All rights reserved.