[英]junit test assert, writing test
我正在為數據數組類編寫測試用例。 對於這一部分,索引在0到30000之間是可以的。
public short value(int index) throws Exception {
// what block-th buffer
int block = (index * REC_SIZE) / BLOCK_SIZE;
int offset = (index * REC_SIZE) % BLOCK_SIZE;
byte[] curr = bufferPool.getBuffer(block).readBuffer();
short returnValue = ByteBuffer.wrap(curr)
.getShort(offset + INDEX_VALUE);
assert ((returnValue > 0) && (returnValue <= 30000)) : "Invalid"
+ " < Value >: not between 1 to 30000";
return returnValue;
}
但我還需要測試斷言行,即
assert ((returnValue > 0) && (returnValue <= 30000)) : "Invalid"
+ " < Value >: not between 1 to 30000";
如何編寫可以檢查索引不在0到30000之間的junit測試?
您可以對測試說您希望引發異常(如果我還記得的話,從JUnit 4開始)。
@Test (expected = Exception.class)
public void myTest (){
value(3005);
}
但請注意,可以禁用斷言,因此在進行任何計算之前,我將使用IllegalArgumentException
來檢查索引的值,然后
@Test (expected = IllegalArgumentException.class)
public void myTest (){
value(3005);
}
重新閱讀您的問題,我不確定是否要測試index
的值(在這種情況下,您可以使用IllegalArgumentException
)或returnValue
(在這種情況下,您可以使用自定義異常)。
但是不要在測試用例中使用assert語句。 assert語句僅用於程序的調試模式。 如果有人通過禁用斷言來運行它,則您的檢查甚至不會受到測試。 因此,請拋出一個異常(並按我的說明在您的單元測試中捕獲它們)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.