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!
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.
public <T> getField(Object owner, String name) {
try {
Field f = Objects.requireNonNull(owner)
.getClass().getDeclaredField(name);
f.setAccessible(true);
return (T) f.get(owner);
} catch (Exception ex) {
throw new RuntimeException("reflective access failure", ex);
}
}Then assuming this class:
class Foo {
private String bar;
...
}You can just do:
String bar = ReflectionUtils.<String>getField(fooObj, "bar");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.
5
u/Python4fun Dec 13 '20
You can use a mock dependency and check whether a method is called, and what arguments are passed to it.
5
u/LiteratureStriking Dec 13 '20
I am testing the success of the insertion with toString() or search() methods.
Yes, this is exactly what you should do. This preserves the encapsulation of your classes. Except for toString(). Don't do that. Tests that hack string representations can be really flaky.
Should I be coupling my unit tests like this?
This isn't really coupling, it demonstrates the logical consistency of the methods of your class.
2
u/kakipipi23 Dec 13 '20
Sometimes the functionality can be decoupled in such way that one method returns the changes that needs to be done and another one is just updating your data structure / db in a general manner. If it fits your use case go ahead and do that.
Ill give an example: lets say you have a business logic that receives an account, updates the balance according to some independent logic and saves it. You can have one method that does all that, or you can have an update method that calculates the balance update and then another one to save an account.
Hope I was clear :)
2
u/proskillz Some Skillz Dec 13 '20
You have a couple of options, generally I would simply not write void methods, which solves this quite effectively. ;) Each method should return a value, making until testing very easy.
Add a test seam that gives you package private getters for the member variables you're testing
Use refection to access private methods/member variables
Both of these are hacks though. Testable code won't need these solutions.
2
u/DJDavio Dec 13 '20
If you're testing a layer, such as the web or service layer, you could mock the underlying layer and see whether it has been called by your method.
•
u/AutoModerator Dec 12 '20
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.