r/javahelp • u/nasty_haze • Dec 12 '20
Question regarding best practices when unit testing void methods
Hey gang,
So I have been brushing up on my TDD practices with JUnit5. I have noticed that when testing void methods, namely ones that insert data into a structure, I am testing the success of the insertion with toString() or search() methods.
Should I be coupling my unit tests like this?
What would be an alternative to better expose the functionality within the void method?
Or is this type of testing, much like with private methods, simply how it is done?
Thanks in advance for your insights!
17
Upvotes
8
u/nekokattt Extreme Brewer Dec 13 '20 edited Dec 13 '20
you must have something inside those methods doing something, mock those components and verify that they get called in the way you expect by using mockito.
You shouldn't be connecting to anything outside the single unit you are testing, otherwise it is not a valid unit test but an integration or functional test.
You can also make use of package private accessors or package private fields as a last resort, argue it either way you want - i personally dislike having to break encapsulation for tests - but the JDK does this for standard library stuff in several places. With modules this is a little better as private module components are a little harder to break into with reflection apparently.
Mocks are the way to go though.
Also, some frameworks like Spring have reflection tools that use reflection to extract a private field. You could make one pretty easily.
Then assuming this class:
You can just do:
Obviously if you rename your fields, this will break unless you have a very smart IDE. All trade offs. And these are whitebox testing techniques, so not necessarily suitable for anything assuming your system to be a black box.
Mutating internals is also possible by using Field#set.
But again, use mocks where possible first, they are the best solution where possible.