-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"); } } 
1
  • 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. Commented May 2, 2016 at 10:55

3 Answers 3

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"); } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

@Test(expected = Exception.class)

Original answer from here.

Comments

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"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.