• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JUnit testing

 
James Clarke
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Iam doing some unit testing using netbeans IDE and JUnit.
Can JUnit be used to check the values of local variables in various parts of a method.eg. can the values of var1 and var2 determined using JUnit:

public void sampleMethod(){
String var1 = null;
if(somecondition){
var1 = "21312"
}
if(someOtherCondition){
String var2 = SampleClass.getSomeString();
doSomethingWithVar2(var2);
}
if(var1!=null){
useVar1(var1);
}
}

As far as I can see JUnit can only be used to test the return values from methods, is this correct ?

thanks,

James
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JUnit can also be used to test for certain side effects of method calls, but that's rather deep in the bag of tricks.

It cannot be used to test the values of local variables. If you feel the need to do that, it is almost invariably an indicator that your design could use some improvement.

Unfortunately, your example code is too general to give more specific advice. If you post some real code, I'm sure we can be more helpful.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So one thing that Ilja means by "improving the design" is that you can take any condition or logic that leads to setting the value of a local variable, and break it out into a separate small method. Then you can test that small method by checking its return value! In this way, test-driven design leads you toward designs with many small, testable methods. If the small methods have good names, then this kind of code is very easy to read, too -- a plus!
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
So one thing that Ilja means by "improving the design" is that you can take any condition or logic that leads to setting the value of a local variable, and break it out into a separate small method.


Mhh, yes, that's one possible solution - there are of course uncounted others. What a good solution looks like very much depends on what the code really looks like.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic