Can't get my JUnit test to catch my Exception
807600Oct 29 2007 — edited Nov 28 2007This is also posted in: Desktop Forum on accident.
I've read through a lot of the posts, but nothing seems to work. Basically I'm writing a JUnit test for one of my classes and I'm trying to test one of my constructors' exceptions, but it won't catch the exception! Please take a look:
This is part of my original class.
public YearMonthDay(int year, int month, int day)
{
// Instantiate a calendar to let it validate our date.
try
{
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.clear();
// Set Calendar values to passed in parameters
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
//System.out.println("cal: " + cal.getTimeInMillis());
}
catch (Exception e)
{
//This is only here for testing current testing purposes
System.out.println("Exception: " + e + " : " + month);
throw new IllegalArgumentException("Invalid date parameters: " + year
+ ", " + month + ", " + day);
}
this.year = year;
this.month = month;
this.day = day;
}
This is part of my JUnit test where I'm sending "INVALID" dates to see if the exception will be caught.
public void testExceptionValidCalendarDate()
{
boolean caught = false;
try
{
YearMonthDay testInvalidDate = new YearMonthDay(2007, 15, 40);
//System.out.println("testFalse :" + testFalse.toString());
}
catch (IllegalArgumentException e)
{
caught = true;
}
assertTrue("testExceptionValidCalendarDate, did not get IllegalArgumentException", caught);
}
I did read somewhere that the set() command only sets the fields, it doesn't do much checking, its not till you call something like "get()" that throws an exception. For instance, notice the commented portion "System.out....,,cal.getTimeInMillies()." if you allow that to be run, it throws an error, but I need for this constructor to set fields based on passed in parameters AND throw an exception if Year, Month or Day is invalid! Please help.