-1

How can I test this private method? I am not able to pass the environment variable of my own to test it. Thanks.

@Value("{jobParameters['businessId']}")
String environment;

public void A() {
  B(environment)
}

private void B(String env) {
 switch(env) {
   case 'a': //do something
     break;
   case 'b': //do something
     break;
   default: //do something
  }
}
CodeScale
  • 3,046
  • 1
  • 12
  • 20
ANMOL JAIN
  • 43
  • 1
  • 7
  • Does this answer your question ? https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or?rq=1 – Sandeep Lakdawala Apr 25 '20 at 06:34
  • Does this answer your question? [How do I test a private function or a class that has private methods, fields or inner classes?](https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or) – Progman Apr 25 '20 at 07:52

2 Answers2

1

Some solutions

  • You can't do that with Mockito but you can use Powermock (aside to Mockito) and mock private methods
  • Change visibility of your method -> Very bad practice but I saw lot of code that use "package" visibility only to having the capability to test these methods.
  • If you do true OO you normally don't need to test these methods.. only test methods exposed by your objects. We just don't care about private methods because from the standpoint of testing private methods don't exist (blackbox tests).
CodeScale
  • 3,046
  • 1
  • 12
  • 20
0

As mentioned above, you should not test private methods. But if you really want to do that, you can also use reflections to call your private method from your unit test and pass the environment variable to it.

Rahul Jain
  • 142
  • 2
  • 11