簡體   English   中英

JAVA:單元測試和參數解析時捕獲異常

[英]JAVA:Catching exception when unit testing and parameter parsing

   @Test
    public void testToString(){
        System.out.println("toString");
        Address add = new Address("Blackthorn","Kings Lynn","PE30");
        BusinessOrganisationDetails instance  = new BusinessOrganisationDetails("PEA-1234",
                "Smith",add,10,"EA",12);
        String expResult = "";
        String result = instance.toString();
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail("The test case is a prototype.");
    }

這是我的BusinessOrganisationDetails類的測試方法,我想知道在測試時是否有必要創建該類的實例並在測試時放入特定變量。 它需要以下字段。

//        String customerID, String companyName,
//            Address address,int companyDiscount,
//            String regionalCode,double totalPrice

如您所見,它需要一個地址類型的字段。 因此,就像在上面的代碼中所做的那樣,有必要在這里創建一個地址類的實例。 我收到一個錯誤消息,因為在創建BusinessOrganisationDetails類的實例時,它說我需要對IllegalCustomerIDException類進行嘗試捕獲。 我不確定給定我的方案的最佳方法

您能更好地解釋這種情況嗎? 我沒有得到您要測試的內容以及您真正擔心的是什么。 無論如何,根據我的理解,我會說測試中的try catch塊不是問題,您也可以使用它來測試異常是否正確拋出,例如,是否將錯誤的客戶ID作為參數傳遞給構造函數。 。 或者,如果您只是假設在測試中不應該引發異常,則可以在測試方法簽名中插入throws IllegalCustomerIDException

在測試中使用try / catch並沒有錯。 有兩種方法可以測試代碼是否毫無例外地完成:

@Test
public void testToString() throws IllegalCustomerIDException {
    System.out.println("toString");
    Address add = new Address("Blackthorn","Kings Lynn","PE30");
    BusinessOrganisationDetails instance  = new BusinessOrganisationDetails("PEA-1234",
            "Smith",add,10,"EA",12);
    String expResult = "";
    String result = instance.toString();
    assertEquals(expResult, result);
}

@Test
public void testToString()  {
    System.out.println("toString");
    try {
        Address add = new Address("Blackthorn","Kings Lynn","PE30");
        BusinessOrganisationDetails instance  = new  BusinessOrganisationDetails("PEA-1234",
            "Smith",add,10,"EA",12);
        String expResult = "";
        String result = instance.toString();
        assertEquals(expResult, result);
    } catch(BusinessOrganisationDetails e) {
            fail(e.getMessage);
    }
}

如果您不想測試是否引發了異常,則可以將RuleExcpectedException一起使用

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testToString() throws IllegalCustomerIDException {
    System.out.println("toString");
   exception.expect(IllegalCustomerIDException.class);
    exception.expectMessage("unkwon customer id 4711");
    Address add = new Address("Blackthorn","Kings Lynn","PE30");
    BusinessOrganisationDetails instance  = new BusinessOrganisationDetails("PEA-1234",
            "Smith",add,10,"EA",12);
}

暫無
暫無

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

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