Reputation: 343
Below is the (incomplete) piece of code containing the method "IntRelation" that I would like to test on whether it throws exceptions or not.
public abstract class IntRelation {
public IntRelation(final int n) throws IllegalArgumentException {
if (n < 0) {
throw new IllegalArgumentException ("Parameter in precondition violated.");
}
}
}
Below is the (incomplete) piece of code containing the test case for the "IntRelation" method.
public abstract class IntRelationTestCases {
protected IntRelation instance;
@Test
public void testException0() {
Class expected = IllegalArgumentException.class;
instance.IntRelation(-1);
}
}
The problem I am encountering is that in the second piece of code, NetBeans/JUnit says that it cannot find the method "IntRelation". What am I doing wrong?
Upvotes: 0
Views: 3571
Reputation: 13930
That's true. It's because you're invoking a constructor like it's a method; don't do that.
I suppose what you wanted to do was instance = new IntRelation(...);
or you meant that to actually be a method in which case you haven't defined it properly due to missing a return type.
public void IntRelation(...)
should do it in that regard.
But then you'd have an issue of an un-instantiated instance
which should lead you to a NullPointerException
.
If you want to have some data set up to test it's good practice to use annotations to get things ready for testing.
Example:
@Before
public void setUp() {
// Since your class is abstract you can do it like this
// to get an anonymous class you can test that non-abstract
// method with...
instance = new IntRelation() { };
}
then call it as usual from the test testing that unit.
@Test
public void testException0() {
...
instance.IntRelation(-1);
}
I would say, though, naming a method identical to its class name seems potentially confusing. Plus, it's against Java naming conventions to name a method with leading caps; first letter should be lower-case and the rest should camel. For example, thisIsTheCorrectWay(...)
.
Upvotes: 5