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?
2 Answers
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) { } } 4 Comments
Lukasz Medza
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!
jgitter
Cheers! Enjoy testing!
Cebence
Better to use
fail("Should have thrown exception!") after do stuff instead of assertTrue(passed) - one less variable.jgitter
@Cebence - good suggestion. I will update my answer.
The JUnit wiki lists different ways of exception testing: https://github.com/junit-team/junit/wiki/Exception-testing