This is my first day writing Unit tests using Mockito and I might have started with a complex exercise.
Below is my class structure and I am writing tests for Class2.targetMethod(). Class1 static method modifies passed in object instead of returning any results.
class Class1 {
static void dbquery(OutParam out) {
// Complex code to fill in db results in OutParam object
}
}
class Class2 {
void targetMethod() {
OutParam p1 = new OutParam1();
Class1.dbquery(p1);
ResultSet rs = p1.getCursor();
...
}
}
Below is my setup for the tests:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Class1.class, Class2.class})
public class Class2Test {
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(Class1.class);
doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Exception {
OutParam result = (OutParam)invocation.getArguments()[1];
OutParam spy = spy(result);
ResultSet mockResult = mock(ResultSet.class);
doReturn(mockResult).when(spy.getCursor());
when(mockResult.getString("some_id")).thenReturn("first_id","second_id");
when(mockResult.getString("name")).thenReturn("name1","name2");
return null;
}
}).when(Class1.class, "dbquery", any());
}
}
However the tests fail with exception below - mainly due to "doReturn" line.
Any suggestions on this problem or if my approach is completely wrong.
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
Aucun commentaire:
Enregistrer un commentaire