4 回答

TA貢獻1828條經驗 獲得超3個贊
您可以用 try/catch 包圍失敗的部分,并在 try 塊的末尾調用 fail()。如果拋出異常,則不應到達 fail() 指令,并且您的測試應該通過。

TA貢獻1744條經驗 獲得超4個贊
@Test有一個參數斷言一個特定的異常被拋出,你可以像這樣編寫你的測試:
@Test(expected = IOException.class)
public void testSize() throws ClientProtocolException, IOException {
...
}

TA貢獻1853條經驗 獲得超9個贊
您可以通過 3 種方式實現這一目標:
1)@Test(expected = ....在提供要檢查的異常類的地方使用 ) 注釋。
@Test(expected = IOException.class)
public void test() {
//... your test logic
}
這不是異常測試的推薦方法,除非您的測試真的很小并且只做一件事。否則,您可能會拋出異常IOException,但您無法確定是測試代碼的哪一部分引起的。
2)@Rule對類使用注解ExpectedException:
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void testExpectedException() {
exceptionRule.expect(IOException.class);
exceptionRule.expectMessage("Request too big.");
//... rest of your test logic here
}
請注意,exceptionRule必須是public。
3)最后一個,很老式的方式:
@Test
public void test() {
try {
// your test logic
fail(); // if we get to that point it means that exception was not thrown, therefore test should fail.
} catch (IOException e) {
// if we get here, test is successfull and code seems to be ok.
}
}
這是一種老式的方法,它會在本應干凈的測試中添加一些不必要的代碼。

TA貢獻2021條經驗 獲得超8個贊
還有另一種解決方案,尚未在這些答案中提出,這是我個人的偏好。assertThatThrownBy 斷言
在你的情況下
@Test
public void testSizeException(){
assertThatThrownBy(()-> Request.Post(mockAddress)
.connectTimeout(2000)
.socketTimeout(2000)
.bodyString(s, ContentType.TEXT_PLAIN)
.execute().returnContent().asString())
.isInstanceOf(IOException.class)
.hasMessageContaining("Request content exceeded limit of 2048
bytes");
}
添加回答
舉報