2016-04-27 120 views
1

我在java類有方法:期待自定義異常,而不是空指針異常而JUnit的測試

@Context 
UriInfo uriInfo; 
public void processRequest(@QueryParam ("userId") @DefaultValue("") String userId) 
{ 
    String baseURI = uriInfo.getBaseUri().toString(); 
    if(userId == null) 
    { 
     //UserIdNotFoundException is my custom exception which extends Exceptition 
     throw new UserIdNotFoundException(); 
    } 
} 

當我的JUnit測試上面的方法爲預期時UserIdNotFoundException userid參數是空的,我得到以下聲明錯誤:expected an instance of UserIdNotFoundException but <java.lang.NullPointerException> is java.lang.NullPointerException

@Test 
public void testProcessRequest_throws_UserIdNotFoundException() 
{ 
    expectedException.expect(UserIdNotFoundException.class); 
    processRequest(null); 
} 

我的自定義異常類:

public class UserIdNotFoundException extends Exception 
{ 

    public UserIdNotFoundException() 
    { 

    } 

    public UserIdNotFoundException(String message) 
    { 
      super(message); 
    } 
} 

回答

2

我更喜歡註解:

@Test(expected = UserIdNotFoundException.class) 
public void testProcessRequest_throws_UserIdNotFoundException() { 
    processRequest(null); 
} 

的問題可能是你的processRequest執行可能擊中NPE你有機會來檢查用戶ID之前。

這是一件好事:您的測試顯示實施不符合您的要求。你現在可以永遠修復它。

這就是TDD的好處。

+0

我的執行如何在檢查之前觸發空指針異常。我不調用userId上的任何字符串方法。或者我沒有明白你的觀點。此外,我將userId作爲來自Url的查詢參數。唯一的可能是它可能涉及一些空的檢查。 – Ashley

+1

您必須發佈processRequest的實現以供我爲您拼寫。一個更好,更教育的想法可能是在調試器中逐步完成該過程。在processRequest的第一行放置一個斷點,看看觀察到的行爲與您的期望不符。 – duffymo

+0

我按照你的建議進行了調試。該錯誤顯示在行uriInfo.getBaseUri()。toString()它似乎。因此,我把這條線後if檢查。測試現在顯示綠色欄。但我仍然沒有得到理由。 – Ashley

0

你必須編寫自定義異常類this example可以幫助你。

示例代碼:

class UserIdNotFoundException extends Exception{ 
UserIdNotFoundException (String s){ 
    super(s); 
} 
} 

測試異常:從您的異常類

public void processRequest(String userId) 
{ 
    if(userId == null) 
    { 
     //UserIdNotFoundException is my custom exception which extends Exception 
     throw new UserIdNotFoundException("SOME MESSAGE"); 
    } 
} 

刪除默認的構造函數,JVM隱式創建爲你/

+0

我寫了我的自定義異常類,但仍然得到相同的斷言錯誤。 – Ashley

+0

更新的答案,試試。 –

+0

移除構造函數將如何解決上述問題? – Ashley

0

你可能沒有沒有設定值uriInfo並且您打電話一個空值的方法。你確定你的測試設置爲uriInfo?或者getBaseUri()可能會返回null並且調用toString()就可能會拋出NullPointerException。這可以通過在調試器中檢查返回值getBaseUri()來完成。

通常情況下,您可以使用包含bean的配置爲測試運行測試,也可以添加setter以設置測試類中的值以模擬測試或給出測試值。這應該有助於避免NullPointerException

無論哪種方式,你應該總是做一個方法中的任何真正的工作之前的失敗驗證。