-1
比方說,我創建了我自己的assertSomething(...)
方法。我如何編寫單元測試來驗證它是否正確地使測試用例失敗?如何編寫自定義JUnit斷言的測試?
比方說,我創建了我自己的assertSomething(...)
方法。我如何編寫單元測試來驗證它是否正確地使測試用例失敗?如何編寫自定義JUnit斷言的測試?
您應該看看Junit 4.7中引入的規則。特別是TestWatcher。
TestWatcher是規則的基類,它記錄了測試操作,但未對其進行修改。例如,這個類將保持每個通過和未通過測試的日誌:
public static class WatchmanTest {
private static String watchedLog;
@Rule
public TestWatcher watchman= new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
watchedLog+= description + "\n";
}
@Override
protected void succeeded(Description description) {
watchedLog+= description + " " + "success!\n";
}
};
@Test
public void fails() {
fail();
}
@Test
public void succeeds() {
}
}
如果我理解正確,我看到了未來的方式:
@Test
public void assertSomethingSuccessTest() {
// given
final Object givenActualResult = new Object(); // put your objects here
final Object givenExpectedResult = new Object(); // put your objects here
// when
assertSomething(givenActualResult, givenExpectedResult);
// then
// no exception is expected here
}
// TODO: specify exactly your exception here if any
@Test(expected = RuntimeException.class)
public void assertSomethingFailedTest() {
// given
final Object givenActualResult = new Object(); // put your objects here
final Object givenExpectedResult = new Object(); // put your objects here
// when
assertSomething(givenActualResult, givenExpectedResult);
// then
// an exception is expected here, see annotated expected exception.
}
如果您需要驗證異常以及:
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void assertSomethingFailedTest() {
// given
final Object givenActualResult = new Object(); // put your objects here
final Object givenExpectedResult = new Object(); // put your objects here
// and
thrown.expect(RuntimeException.class);
thrown.expectMessage("happened?");
// when
assertSomething(givenActualResult, givenExpectedResult);
// then
// an exception is expected here, see configured ExpectedException rule.
}
有用的信息:https://www.guru99.com/junit-assert.html – roottraveller
沒有說你不能寫一個單元測試它,就像你任何東西。 :-) – cjstehno
很抱歉,這個網頁對我的具體問題沒有幫助。我正在創建自己的JUnit斷言,我想單元測試它的代碼。所以我需要測試用例來檢查: - 測試用例在我的斷言允許時通過 - 測試用例在我的斷言不允許時失敗。 –