1

I am working on project which includes junit testing code as well. Some where i have seen that methods are declared as default(no access specifier) and they are using it in junit for code coverage. Can anyone tell that which one is the best way to unit test the code from the below options.

  1. make the methods as default(no access specifier). Since for junit we are exposing the methods outside of class. Eventually we are exposing it only for junit.
  2. We can use reflection to test the piece of code. Because junit won't be delivered in production environment.
Shriram
  • 4,343
  • 8
  • 37
  • 64
  • 1
    Why do you need to test private methods? – Oliver Charlesworth Sep 16 '16 at 13:04
  • Have you tried PowerMockito? – Celt Sep 16 '16 at 13:05
  • Related: http://stackoverflow.com/questions/6913325/annotation-to-make-a-private-method-public-only-for-test-classes – Andy Turner Sep 16 '16 at 13:06
  • I think this may be (may be, not definitively is) an indication of an over-clobbed class. The thing that is a private method you want to test might be more appropriate as a delegate. Alternatively, test the public methods and assert on behaviour. Internals should remain internal. – Taylor Sep 16 '16 at 13:12

1 Answers1

1

In essence, this is a question of style; thus it is more about opinions than real technical reasons. My "technical" thoughts here:

  • We are occasionally doing that - sometimes we add getters to our production code that allows for inspection of internal state. Simply because that is an easy, straight forward way of retrieving information.
  • With those getters in place, I can trigger one operation; and then do some sort of assert on that internal state.
  • The alternative to that would be to use crazy things such as reflection within our testcases.

Thing is: we have the convention to put a simple javadoc above such package-protected methods, like /** unit testing only */. And we agreed within our team that this is "good enough" for us. But of course: to a certain degree, this is not a good pattern: as you make something internal observable from the outside; so you somehow externalize some parts of your implementation details.

In other words: don't go overboard here. It is fair to make internal things visible that are really at the core of your implementation (and maybe work on a very high abstraction level); but you don't want to make "too many" things visible to the outside. People might otherwise wrongly believe that those things belong to the "official contract" of your class!

But as others have said, you might want to look into the things that Mockito can do for you alternatively.

GhostCat
  • 137,827
  • 25
  • 176
  • 248