1

can we write test cases for setAddr() method, because it is private void method, can one please help me?

class WCfg  {

private void setAddr(Cfg cfg, String... arg)
         throws Exception {
try {

} catch (Exception e) {
  throw new Exception("Invalid IP address.", e);
}
}

public String process(String... arg) throws Exception {
  MCfg mCfg = new MCfg();

  try {
    setAddr(mCfg, arg);

  } catch (Exception e) {
    return "Wrong argument format.";
  }
  cfg.write();

  return "success";
 }
}
mrs
  • 207
  • 2
  • 5
  • 13
  • 1
    You should not write test for your private methods. – mpals Apr 07 '17 at 08:35
  • 3
    You can access to the method using [reflection](http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/ReflectionUtils.html), or use [PowerMock](https://github.com/powermock/powermock) – ymonad Apr 07 '17 at 08:37
  • Hint: try your favorite search engine the next time ;-) – GhostCat Apr 07 '17 at 12:41

3 Answers3

1

Every private method is always call in some of the public or accessible method directly or in directly. So, no need to write case for them.

Then also if you want write test case for that then use :

Deencapsulation.invoke(SomeClassWherePrivateMethod.class, "methodName", argument1, argument2, argument3);

here Deencapsulation is from mockit.Deencapsulation.

You can Download jar from here.

Sunil Kanzar
  • 1,244
  • 1
  • 9
  • 21
0

If you really must you could use reflection. See example: http://onjavahell.blogspot.nl/2009/05/testing-private-methods-using.html

But also read the comments! I strongly advise against it. If you can't test your code it is most often a sign of bad design.

ipper
  • 624
  • 4
  • 13
0

As mentioned above, you should not test private method. Always test the contract of you class not the implementation. Otherwise, if the implementation of your class is changed you will got false negative test results. By that i mean that the behavior of the class is as expected but the tests will fail.

It you case, if you have complex logic in private method, you should think about extracting it to separate class. This class can be package-private, and also you can reuse the extracted code.

Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69