簡體   English   中英

任何人都可以告訴我這個偽代碼怎么了?

[英]Anyone can tell me what's wrong with this pseudo code?

我不熟悉JUnit,所以不確定這是否是assertTrue(b_exception);的問題assertTrue(b_exception); ,因為如果我放置System.out.println("something"); 在那里,它將打印出“內容” ...謝謝!

請注意,它是偽代碼,着重於邏輯。

b_exception = false;
try{
   somethingThrowError();
}catch(Error e){
   b_exception =  true;
}
assertTrue(b_exception);

我不知道您的代碼有什么問題,因為您尚未說明它是如何無法滿足您的期望的,但是測試拋出異常的正確習慣是使用JUnit 4的注釋:

@Test(expected=SpecificError.class)
public void testError(){
   somethingThrowError();
}

我只能猜測您正在尋找:

try{
  somethingThrowError();
  fail("Exception expected");
}catch(AsSpecificAsPossibleException e){
  //should happen, OK
  //optionally assert exception message, etc.
}

另請注意,捕獲Error不是一個好主意,請盡可能使用特定的異常。

更新: @Michael Borgwardt的答案實際上甚至更好,但前提是測試中只有一行(沒有其他東西可以拋出)。 另外@Test(expected不允許您執行額外的異常消息斷言(但是您應該這樣做嗎?)

不知道您認為該代碼有什么問題。
assertTrueSystem.out.println都將始終執行。
它- assertTrue -如果參數是不是會發出錯誤信號true ,或者“通過測試”如果參數為true
也許您應該使用System.out.println("b_exception = " + b_exception); 看看發生了什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM