我最近發現JUnit> 4.10允許使用@Rule
和ExpectedException
。由於我對重複的代碼不是很大,我嘗試了以下方法。爲了更好地理解,我將它從幾個測試縮小到了這兩個測試。 MockitoJUnitRunner
是故意的,雖然它沒有用在小規模的例子中。是否有可能在JUnit中覆蓋預期的異常?
的pom.xml
<dependencies>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
</dependencies>
TestBase
@RunWith(MockitoJUnitRunner.class)
public class TestBase {
/** JUnit > 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);
}
}
的問題是,下面的測試沒有工作,我希望它。我正在嘗試的是默認期望的異常類型,並在某些情況下運行正常的JUnit測試。設置後,我無法重置預期的異常。
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
}
}
我已經通過複製在各方法的expectBadParam方法我期望的異常以及覆蓋在測試類的@Before
註釋發現不同的解決方案。不過,我希望有人能幫助我理解爲什麼這不起作用?
你應該改寫設置,或者不要繼承'TestBase' –
當我想要避免代碼重複時,如何重寫設置(我真正實現了該設置)有什麼幫助?例如45個測試應該拋出一個錯誤的參數異常,而4個測試應該以正常的成功運行。 同樣的建議不要從'TestBase'繼承。有多個測試正在使用該超類。爲了更好的理解,我調整了這個例子的大小。 它仍然避免了我爲什麼不能使用JUnit中的ExpectedException重置爲預期的異常。 – Dr4gon