4 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以用 try/catch 包圍失敗的部分,并在 try 塊的末尾調(diào)用 fail()。如果拋出異常,則不應(yīng)到達(dá) fail() 指令,并且您的測(cè)試應(yīng)該通過(guò)。

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

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以通過(guò) 3 種方式實(shí)現(xiàn)這一目標(biāo):
1)@Test(expected = ....在提供要檢查的異常類的地方使用 ) 注釋。
@Test(expected = IOException.class)
public void test() {
//... your test logic
}
這不是異常測(cè)試的推薦方法,除非您的測(cè)試真的很小并且只做一件事。否則,您可能會(huì)拋出異常IOException,但您無(wú)法確定是測(cè)試代碼的哪一部分引起的。
2)@Rule對(duì)類使用注解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
}
請(qǐng)注意,exceptionRule必須是public。
3)最后一個(gè),很老式的方式:
@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.
}
}
這是一種老式的方法,它會(huì)在本應(yīng)干凈的測(cè)試中添加一些不必要的代碼。

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
還有另一種解決方案,尚未在這些答案中提出,這是我個(gè)人的偏好。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");
}
添加回答
舉報(bào)