0

Having an assertion somewhere in a method myMethod in the production code like:

public void myMethod(List list1, List list2) {
 assert list1.size() == list2.size()
}

and a unit test

@Rule
public ExpectedException ex = ExpectedException.none();

@Test
public void test() throws Exception {
 ex.expect(java.lang.AssertionError.class);
 myMethod(Arrays.asList(1, 2), Arrays.asList(1, 2, 3));
}

I expect the unit test to successfully run but I get the AssertionError. Why is it so?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63
  • 1
    @SotiriosDelimanolis I know what the keyword does. I just wanted to know how can I use it in my unit test and the Rule for ExpectedException. – Arthur Eirich Dec 20 '16 at 14:51

1 Answers1

2

Assuming you're using 4.11, the javadoc of ExpectedException states

By default ExpectedException rule doesn't handle AssertionErrors and AssumptionViolatedExceptions, because such exceptions are used by JUnit. If you want to handle such exceptions you have to call handleAssertionErrors() or handleAssumptionViolatedExceptions().

Assuming assertions are enabled with the -ea option, just add the call the handleAssertionErrors()

@Test
public void test() throws Exception {
    ex.handleAssertionErrors();
    ex.expect(java.lang.AssertionError.class);
    myMethod(Arrays.asList(1, 2), Arrays.asList(1, 2, 3));
}

You should no longer need the above in JUnit 4.12 (or in versions 10 and under).

Deprecated. AssertionErrors are handled by default since JUnit 4.12. Just like in JUnit <= 4.10.

This method does nothing. Don't use it.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724