0

I run the following test in my Eclipse (with arguments -ea):

public class ColorHelperTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testGetColorByString() { thrown.expect(AssertionError.class); assert 1 == 2; } } 

The output is:

java.lang.AssertionError at de.*.*.*.mytests.ColorHelperTest.testGetColorByString(ColorHelperTest.java:28) 

28 is the line assert 1==2

Why does this test fail?

0

3 Answers 3

2

You cannot "expect" AssertionError, this is the specific type of error that JUnit uses to signal that the test is failing.

Update: Turns out it's a bug of JUnit 4.11, and it was resolved in 4.12: https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.12.md#pull-request-583-pull-request-720-fix-handling-of-assertionerror-and-assumptionviolatedexception-in-expectedexception-rule

Sign up to request clarification or add additional context in comments.

Comments

1

The assert keyword is a JRE level flag and has nothing to do with JUnit. I think what you're really looking for is:

assertEquals(1, 2); 

2 Comments

Sorry, maybe I was misleading you, but the assert was only an example. I don't care if 1 != 2 ;-)
I want to find out how to catch AssertionErrors thrown by other methods.
1

Interesting... What version of Junit you use? Using 4.12 (in my pom.xml looks like:

 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> 

the exact same test works for me.

7 Comments

Did you set the -ea flag? Without it, the assert keyword is ignored.
I did. Also I wouldn't get an AssertionError if I didn't.
I find it very strange, that this works for you. That contradicts @Sergey ?!
I just checked with versions 4.11 and 4.12, and the behavior indeed differs. With 4.11 I receive AssertionError, with 4.12 the test passes.
Here's the reason, turns out it was a bug of versions prior to 4.12 github.com/junit-team/junit/blob/master/doc/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.