F> Hi guys,
I'm quite new with Junit...I have to test a full package..but I really
don't know how to test a class that only has constructor....and no
other methods..
How do I do that?
You test behavior. If a class has only a constructor,
(and it's not just a data container), all the behavior
must be in the constructor. Test it.
(It seems very likely, by the way, that you'd be better
off re-considering the design, or throwing out the whole
mess and trying it test-first, to see if you can find
a more testable design. But I'm going to assume you're
stuck.)
(In this example, I've assumed that there aren't any
methods, but there is accessible data in the instance
fields. It may be that you have something really bizarre,
like a constructor that you only call for the side-effect.
In that case, you could test the side effect, but it's
even more likely than before that you're having trouble
because you're trying to do something horribly, horribly
Wrong.)
class Time {
public int hour;
public int minute;
public int seconds;
Time (int secondsSinceMidnight) { ... }
}
class TimeTest extends junit.framework.TestCase {
public void testOffsetIsFromMidnight() {
Time t = new Time(0);
assertEquals(0, t.hour);
assertEquals(0, t.minute);
assertEquals(0, t.second);
}
public void testComputeHoursMinutesSecondsFromOffset() {
Time t = new Time(13*3600 + 46*60+17);
assertEquals(13, t.hour);
assertEquals(46, t.minute);
assertEquals(17, t.second);
}
public void testRollover() {
Time t = new Time(27*3600);
assertEquals(3, t.hour);
}
public void testRejectNegativeOffset() {
try {
Time t = new Time(-1);
} catch (Exception e) {}
fail("Invalid argument.);
}
}
(That was kindof fun. Everyone has my explicit permission
to use this amazing TestSuite for any purpose at all, up
to and including total world domination.)