简体   繁体   中英

Private class junit testing

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
  }
}

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM