expert expert - 3 months ago 8
Java Question

Can I mock another method in then statement of first method?

Can I mock another method in

then
statement of mocked method ?

I'm mocking
ResultSet.getByte()
for 2 different arguments

when(rs.getByte("present")).thenReturn(5)
when(rs.getByte("missing")).thenReturn(0)


What I also want to have is that mocked
getByte
not only returns value but also mock
ResultSet.wasNull
to return once
false
in first case and
true
in another one.

Here is how I run scenario

val rs: WrappedResultSet = ...
val res3: Option[Byte] = rs.byteOpt("present")
val res4: Option[Byte] = rs.byteOpt("missing")
res3.isDefined should be(true)
res4.isDefined should be(false)


Implementation of
byteOpt
getter internally calls
wasNull
right after
getByte
.

Answer

Maybe do something like that:

final ResultSet rs = mock(ResultSet.class);
when(rs.getByte(anyString())).thenAnswer(new Answer<Long>() {
   @Override
   public Long answer(InvocationOnMock invocationOnMock) throws Throwable {
       String argument = (String) invocationOnMock.getArguments()[0];
       Long answer;
       if("present".equals(argument)){
          when(rs.wasNull()).thenReturn(false); //mock to return false, when present was argument
          answer = 5L;
       else {
          when(rs.wasNull()).thenReturn(true); //mock to return true, when something else was sent to method
          answer = 0L;
       }
       return answer;
   }
}