繁体   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