0

I am writing test for a method which takes in a String, but the String value is from a chain of method call.

// MyService myService = a wired global variable
public List<String> method() {
    List<Message> messageList = myService.getMessages(UserCtx.currentUser().getUserInfo().getUserId());
    // keep doing something else
}

UserCtx.currentUser().getUserInfo().getUserId() returns a String
Here is the unit test I wrote

myService = mock(MyService.class);
List<Message> dummyMessageList = new ArrayList<>(); 
when(myService.getMessages(anyString())).thenReturn(dummyMessageList);
List<String> result = myClass.method()

I am hoping that myService.getMessages will return dummyMessageList directly, but instead it goes into UserCtx.currentUser().getUserInfo().getUserId() and failed in the middle since there isn't a valid user context.
Can I put something like any() or anyString() in when() to bypass mocking UserCtx?
Or do I have to mock the chain UserCtx.currentUser().getUserInfo().getUserId() one by one?

Chen Sheng-Lun
  • 167
  • 1
  • 7
  • The arguments are evaluated BEFORE the method call, there is no way in which you can provide an ArgumentMatcher that will bypass the argument evaluation. – Lesiak May 21 '20 at 06:21
  • Does this answer your question? [Mocking static methods with Mockito](https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) – Progman May 21 '20 at 07:02
  • Yes, assuming UserCtx is a static class, you cannot mock it as it is. You can use PowerMockito for mocking static methods and then go ahead with your default code. – nihal Feb 03 '21 at 11:39

0 Answers0