title: Is It Possible to Override an Expected Exception in JUnit?
body: <p>I recently found out that JUnit > 4.10 allows the usage of <code>@Rule</code> and <code>ExpectedException</code>. Since I'm not big on duplicating code I tried the following. For a better understanding I scaled it down from several tests to just these two. The <code>MockitoJUnitRunner</code> is intentional although it's not used in the small scaled example.</p>
  
  <p>pom.xml</p>
  
  <pre><code>&lt;dependencies&gt;
    &lt;!-- Test dependencies --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;junit&lt;/groupId&gt;
      &lt;artifactId&gt;junit&lt;/artifactId&gt;
      &lt;version&gt;4.11&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.mockito&lt;/groupId&gt;
      &lt;artifactId&gt;mockito-all&lt;/artifactId&gt;
      &lt;version&gt;1.10.19&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
  </code></pre>
  
  <p>TestBase</p>
  
  <pre><code> @RunWith(MockitoJUnitRunner.class)
   public class TestBase {
     /** JUnit &gt; 4.10 allows expected exception handling like this */
     @Rule
     public ExpectedException exception = ExpectedException.none();
  
     @Before
     public void setup() {
       this.expectBadParam();
     }
  
     protected void expectBadParam() {
       this.exception.expect(NullPointerException.class);
     }
   }
  </code></pre>
  
  <p>The problem is that the following test is not working as I would expect it to. What I'm trying is by default expect an exception type and in some cases run a normal JUnit test. I can't reset the expected exception once it's set.</p>
  
  <pre><code> public class ExpectedExceptionTest extends TestBase {
     @Test
     public void error() {
       throw new NullPointerException();
     }
  
     @Test
     public void success() {
       this.exception = ExpectedException.none();
       // this should be a success
     }
   }
  </code></pre>
  
  <p>I already found a different solution by duplicating the expectBadParam method in each method I expect an exception as well as overriding the <code>@Before</code> annotation in the test class. However I'm hoping someone can help me understand why this is not working?</p>