0

I have a class like this

public class Foo {

 public String getData(String id) {
    JsonObject json = this.somePrivateMethod(id);
    String d = // some manipulation
    return d;
 }
 private JsonObject somePrivateMethod(String id) {
 
   
 }
}

I am trying to write the unit test for getData Now, I want to mock this somePrivateMethod with two jsons

goodJson = {1: 2}, badJson = {"foo" : "bar"}

How do I mock that private method in java.

frazman
  • 32,081
  • 75
  • 184
  • 269
  • Does this answer your question? [Testing Private method using mockito](https://stackoverflow.com/questions/8799439/testing-private-method-using-mockito) – Jeff Holt Jun 15 '22 at 01:34
  • Powermock: https://stackoverflow.com/questions/7803944/how-to-mock-private-method-for-testing-using-powermock – Mikhail Jun 15 '22 at 02:20
  • If you're testing `getData`, then you shouldn't stub `somePrivateMethod`. The behaviour of `somePrivateMethod` is part of the contract of `getData`, and therefore, there should be a valid test of `getData` that would only pass if `somePrivateMethod` were not stubbed. As a general rule, if the answer is "PowerMock", then you've asked the wrong question. – Dawood ibn Kareem Jun 15 '22 at 02:46

1 Answers1

0

You can use frameworks like Mockito to achieve the mocking.

when(good.getData()).then(json)

So when your test case runs and when it encounters getData() method then it responses the json object from the then() method

raj240
  • 646
  • 7
  • 17