| Author |
JUnit testing
|
James Clarke
Ranch Hand
Joined: Oct 04, 2004
Posts: 148
|
|
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
Joined: Jul 11, 2001
Posts: 14112
|
|
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.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
|
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!
|
[Jess in Action][AskingGoodQuestions]
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
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.
|
 |
 |
|
|
subject: JUnit testing
|
|
|