5

Suppose you are testing a class a public method A and a private method B and now B can only be tested indirectly. What is the best way to test B directly?

1) Make B public

2) Make B `public only during during testing.

3) Make B protected

4) Make B have default access.

Mat.S
  • 1,814
  • 7
  • 24
  • 36
  • 1
    Maybe I'm completely lost here... but if you can't test the code from your private method from the public methods that you have created. Then you probably have some useless code in that private method right? – shibbybird Aug 04 '13 at 04:03
  • 1
    In general, if you want to write tests for a `private` method, you should separate it out as another class so you can do so without nasty reflection hacks. – Jeffrey Aug 04 '13 at 04:17
  • 3
    The answers cover most of the issues, but #2 is absolutely wrong. Your unit testing should be integrated as part of your build process, and it should test the code exactly as you intend to deploy it. – chrylis -cautiouslyoptimistic- Aug 04 '13 at 06:25

3 Answers3

3

Testability of code should not dictate access level for your method.

When you make a method private, it is usually for the purpose of modularizing your code, or maybe some other refactoring. If it is not an API which is exposed, it is not a candidate for unit testing anyway.

So, the question you must first ask is: "Do I need to expose B()?" If the answer is still no - then the question about testing it directly becomes irrelevant.

A very useful link for Unit testing approaches is from Clean code talks.

Neel
  • 2,100
  • 5
  • 24
  • 47
2

The best way is to make beta method package private and place SomehtingTest class in the same package as Something class.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

The best way would be to make it public but if that is not possible then you can also use reflection to test it.

Full details can be seen here How do I test a class that has private methods, fields or inner classes?

Community
  • 1
  • 1
Lokesh
  • 7,810
  • 6
  • 48
  • 78