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?

0

2 Answers 2

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

4 Comments

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!
Cheers! Enjoy testing!
Better to use fail("Should have thrown exception!") after do stuff instead of assertTrue(passed) - one less variable.
@Cebence - good suggestion. I will update my answer.
0

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

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.