1

I have a problem with ExpectedException. I'm using it in many tests in one test class. Now i got the problem that our Jenkins has one failing test because this test has the expectedMessage of a previous test. I have no idea why but to prevent this fail i tried to "clear" the ExpectedMessage but it does not behave like expected:

TestClass

public class TestClass {

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

    @Test
    public void testExpectedException() throws Exception {
        //old expectation
        expectedException.expect(Exception.class);
        expectedException.expectMessage("something");

        //try to reset
        expectedException = ExpectedException.none();

        //new expectation
        expectedException.expect(Exception.class);
        expectedException.expectMessage("random");
        Thrower exe = new Thrower();
        exe.testedMethod();
    }
}

Thrower

public class Thrower {

    public void testedMethod() throws Exception {
        throw new Exception("random");
    }
}

The testExpectedException leads to the following output:

java.lang.AssertionError: 
Expected: (an instance of java.lang.Exception and exception with message a string containing "something")
     but: exception with message a string containing "something" message was "random"
Stacktrace was: java.lang.Exception: random

But i would expect that expectedException checks for a message containing random. Why does it not?

I am using JUnit 4.11.

Jérôme
  • 1,254
  • 2
  • 20
  • 25
  • Each test method should verify a *single expectation* about the codes behavior anyway, so instead of resetting the exception split that test method into two... – Timothy Truckle Jun 13 '17 at 10:10
  • The tests are created like you suggest but the problem is that the jenkins fails because he has a `expectedMessage` from a previous test. I have no idea how this can be so i decided to "reset" the `expectedException` even when the test architecture ist correct. On a local test run all tests succeed. So it seems that i have to change the way i handle the exceptions in these tests – Jérôme Jun 13 '17 at 10:15

0 Answers0