Issue
my function
class A {
public static int[] getArray(String text) { return new int[]{0,3}; }
}
test method:
private static MockedStatic<A> mock;
@Test
public void Should_return_array_getArray() {
mock
.when(() -> A.getArray(text)) // line: 58
.thenReturn(new int[] {0, 3});
final int[] values = A.getArray(text);
System.out.println("value:"+ values[1]);
assertEquals(3, values[1]);
}
Comes up with following error:
org.mockito.exceptions.misusing.MissingMethodInvocationException at StringTest.java:58
Solution
I am not sure what you are trying to test.. as your actual method does not take any argument but in testcase you are trying to pass text
variable...
If you want to test actual method execution, you don't need mocking. Here are example of testing actual invocation of target method and with mocking as well:
@Test
public void test_actual_static_method() {
final int[] values = A.getArray();
Assertions.assertEquals(3, values[1]);
}
@Test
public void test_mocked_static_method() {
MockedStatic<A> aMockedStatic = Mockito.mockStatic(A.class);
aMockedStatic.when(A::getArray).thenReturn(new int[] {100,200});
Assertions.assertEquals(200, A.getArray()[1]);
}
Also you will need mockito-inline
library
@Test
public void test_mocked_static_method_with_args() {
try(MockedStatic<A> aMockedStatic = Mockito.mockStatic(A.class)) {
aMockedStatic.when(() -> A.getArrayWithArg("s1")).thenReturn(new int[]{100, 200});
Assertions.assertEquals(200, A.getArrayWithArg("s1")[1]);
}
}
Answered By - Subhash
Answer Checked By - Gilberto Lyons (JavaFixing Admin)