Let’s say I have a class like this one:
public class MyClass {
private int var1;
private int var2;
public MyClass() {
var1 = 0;
var2 = 0;
}
public void setVariables() {
var1 = 1;
var2 = 1;
}
I don’t have any getter method inside my class.
Is there a way to test a void method like setVariables() with JUnit? How can I check its behavior without a direct access to variables value?
setVariables from your example is too simple to test. if your real method have any visible effects (non private state) then test that state. if state is private but has influence on other methods then test this method together with other methods. if you feel setVariables is so complex that it should be tested separately then test it. but remember: at this stage you are testing implementation, not the external contract – you will have to change your tests when you change implementation. if you want to do it, i suggest make var1 and var2 package visible – it’s very convenient for tests. if they must stay private then the only solution is reflection and libraries like whiteBox