-1

I have a set method. The set method accept just a few Strings. If the String is not acceptable the set method gives out an ColorException (Own Exception). How do I make a JUnit test to test if I get a Color Exception? Here my testclass at the moment (I tried it with try catch ...):

@Test
// set&check foreground colors for drawings
public void setgetFGCol()  {
   try {
       draw.setFGColor("Red");
       assertEquals(draw.getFGColor(), "Red");
       draw.setFGColor("Not Acceptable String");
       // fail("handle fail?");
   } catch (ColorException e) {
   System.out.println("Dies ist keine bekannte Farbe");
   }
}
Sonius
  • 1,597
  • 3
  • 14
  • 33
  • Side note on code quality: using plain strings to represent colors ... bad idea. And then ... catching an exception, but just printing it - don't do that. You are basically invalidating your tests doing so. – GhostCat May 02 '16 at 10:55

3 Answers3

3

I would separate the test for a valid and invalid argument and test for the exception like this:

@Test(expected=ColorException.class)
public void setInvalidFGCol()  {  
   draw.setFGColor("Not Acceptable String");  
}  
Christoph
  • 93
  • 4
1

If it is exceptions you are expecting, you can do it like this:

@Test(expected = Exception.class)

Original answer from here.

Community
  • 1
  • 1
MichaelK
  • 2,859
  • 1
  • 14
  • 16
0

You should write two test cases so that you can easily see which test failed.

And you can declare in your second test case that the exception is expected.

@Test
// set&check foreground colors for drawings
public void setgetFGCol()  {
   draw.setFGColor("Red");
   assertEquals(draw.getFGColor(), "Red");
}

@Test(expected=ColorException.class)
// set&check foreground colors for drawings
public void setInvalidFGCol() throws ColorException {
   draw.setFGColor("Not Acceptable String");
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34