Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Can't get my JUnit test to catch my Exception

807600Oct 29 2007 — edited Nov 28 2007
This 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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 26 2007
Added on Oct 29 2007
5 comments
805 views