0

I am trying to mock this line:

ResponseEntity<String> response= gatewayOutWrapper.wrap_2P_OneWay(GatewayOut::getConnectionType, wit, serialNumber, metaData);

with when(gatewayOutWrapper.wrap_2P_OneWay(GatewayOut::getConnectionType, any(), any(), any())).thenReturn(ResponseEntity.ok().body(responseBody));

But i dont know how to mock method reference as any. I tried some real values, but i alway get null when run test on that line, so this when dont fire.

Can anyone Help?

Sizor
  • 17
  • 4
  • 1
    Have you tried `when(gatewayOutWrapper.wrap_2P_OneWay(any(), any(), any(), any()))`? It works for me. – Lesiak Feb 28 '23 at 19:04

1 Answers1

0

Direct answer is that any() should work fine, as Lesiak mentioned in the comments. Java represents method references as implementations of single-method interfaces, and any can mock those interfaces just fine.

You might have found other Mockito pitfalls:

  • If you use a matcher like any for any argument when stubbing or verifying, you have to make sure all arguments use matchers. Passing a real value, including your method reference, next to matchers like any() is not allowed. eq is the default, so you can wrap with that.

  • If gatewayOutWrapper's class is final, you need to opt-in to final mocking support, or else the null values (that matchers like any() return) will make their way to a real implementation. This is supported in Mockito 2.1+, but it's still not the default behavior as of Mockito 5.

  • You might also be getting a null pointer exception if gatewayOutWrapper is a spy or it calls real methods; the solution is to use doReturn as in:

    doReturn(ResponseEntity.ok().body(responseBody))
        .when(gatewayOutWrapper)
        .wrap_2P_OneWay(any(), any(), any(), any());
    
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251