1

I know that a part of my program will fail when I try and test it and I wan't the test to pass when it fails. So I was wondering if it is possible to assert a failure?

Lukasz Medza
  • 469
  • 2
  • 8
  • 23

2 Answers2

3

If you're using Junit 4, use the expected behavior:

@Test(expected=SomeException.class)
public void testThings() {
    // do stuff
}

If you're using Junit 3, you'll have to catch it

public void test() {
    try {
        // do stuff
        fail("Expected SomeException");
    } catch (SomeException e) {
    }
}
jgitter
  • 3,396
  • 1
  • 19
  • 26
  • I'm using Junit 4 and I'm trying to have it expect NoSuchElementException but I don't think my syntax is right: @Test(expected=NoSuchElementException) EDIT: My bad I didn't import the exception. Thank you for help! – Lukasz Medza Apr 25 '14 at 13:52
  • Cheers! Enjoy testing! – jgitter Apr 25 '14 at 13:57
  • Better to use `fail("Should have thrown exception!")` after `do stuff` instead of `assertTrue(passed)` - one less variable. – Cebence Apr 25 '14 at 14:00
  • @Cebence - good suggestion. I will update my answer. – jgitter Apr 25 '14 at 14:06
0

The JUnit wiki lists different ways of exception testing: https://github.com/junit-team/junit/wiki/Exception-testing

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72