0

I am trying to mock static function(getBatchId() and sendPost()) for following code :

public void doPost(){      
String batchId = Utility.getBatchId();
                    Post post = new Post(batchId, userId, message);
                    String postJson = Utility.toJson(post);
                          Chat.sendPost(url,postJson)
}

Unit testcase code for above method :

 mockStatic(Utility.class);
        when(Utility.getBatchId()).thenReturn("demoBatchId1234");

        mockStatic(Chat.class);
        when(Chat.sendPost(url,postJson))
                .thenReturn(CompletableFuture.supplyAsync(() -> HttpResponse.create()));

I am getting following exception at when(Utility.getBatchId()).thenReturn("demoBatchId1234"); while running test case :

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:

  1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported.

  2. inside when() you don't call method on mock but on some other object.

Smile
  • 3,832
  • 3
  • 25
  • 39
avy
  • 417
  • 1
  • 9
  • 21
  • could you provide the whole test class with the imports, and so on... where does the `mockStatic` method comes from? Do you use PowerMockito? In that case, do you use the `PrepareForTest` annotation? See: http://stackoverflow.com/a/21116014/2891426 – Nagy Vilmos Sep 05 '16 at 09:49
  • Thanks @Nagy Vilmos .... problem has been solved – avy Sep 05 '16 at 10:28

1 Answers1

0

If you want to mock static methods from different class then you need to prepare all those classes for test using Junit like :

@PrepareForTest({Chat.class,Utility.class})
Smile
  • 3,832
  • 3
  • 25
  • 39
avy
  • 417
  • 1
  • 9
  • 21