Re: Basic JUnit questions
On 3/18/2010 3:22 PM, Rhino wrote:
I think I understand the basics of using JUnit - I'm still using JUnit3
for the moment - but I want to ask some things that I don't find clear in
the documentation that I've found.
Would it be reasonable to say all of the following?
1. For each class that I develop, I should have one JUnit class that
extends TestCase and that this TestCase class should test each of the
methods in the class I developed?
Sort of, I'd say. Private and even package-private classes
might get a waiver, the idea being that their "contracts" are only
with the public classes that "employ" them. Non-public nested
classes, same thing: If they're really just "implementation details"
of their containing classes, they might not need separate testing.
(For some inner classes, it won't be possible to test in isolation.)
"Each method" may be a overkill, too. Getters and setters come
to mind as "too simple to test" -- usually. I've never heard of
anyone writing a unit test for the hashCode()/equals() pair (their
agreement should be verified, but it's not clear that testing is
the best way to go about it).
[...] Whenever
the values of the two input parameters are valid, bar() should produce a
valid result, which I can predict and put in a test that would look like
this:
int actualResult = myclass.bar(4);
int expectedResult = 2;
assertTrue("The actual result, " + actualResult + ", does not equal the
expected result, " + expectedResult, actualResult==expectedResult);
But bar() also anticipates bad values for input parameters and throws
IllegalArgumentException for those. What would my test for that look
like? Any case I've ever written like that returns a Black icon. How
would I write a case involving an Exception so that it gives a Green icon
as the result?
try {
int actual = myclass.bar(invalid);
assertTrue("Got result " + actual + " from " + invalid
+ " instead of an exception", false);
}
catch (IllegalArgumentException ex) {
// Thanks; I needed that!
}
--
Eric Sosman
esosman@ieee-dot-org.invalid