2014-02-22 69 views
-3

我有一个void方法,我想测试它。我怎么做? 这里的方法:返回void的测试方法

public void updateCustomerTagCount() { 

    List<String> fileList = ImportTagJob.fetchData(); 
    try { 
     for (String tag : fileList) { 
      Long tagNo = Long.parseLong(tag); 
      Customer customer = DatabaseInterface.getCustomer(tagNo); 
      customer.incrementNoOfTimesRecycled(); 
      DatabaseInterface.UpdateCustomer(customer); 
     } 
    } catch(IllegalArgumentException ex) { 
     ex.printStackTrace(); 
    } 

} 
+0

在方法前后检查客户。 – pL4Gu33

+1

你想测试什么? – qqilihq

+0

每次有新标签时,我都要更新客户 – Sne

回答

0

当方法返回void,你不能测试方法输出。相反,您必须测试该方法的预期后果。例如:

public class Echo { 
    String x; 
    public static void main(String[] args){ 
     testVoidMethod(); 
    } 

    private static void testVoidMethod() { 
     Echo e = new Echo(); 
     //x == null 
     e.voidMethod("xyz"); 
     System.out.println("xyz".equals(e.x)); //true expected 
    } 

    private void voidMethod(String s) { 
     x = s; 
    } 
} 
0

它可能不是总是正确的,但单元测试的基本概念是检查功能运行正常,当意想不到的参数/情况给予妥善处理错误。 所以基本上单元测试是针对那些需要输入参数并返回一些输出的函数,所以我们可以编写那些单元测试。

然而,像你这样的代码包含一些其他依赖项(数据库调用),除非您编写集成测试代码或实际数据库连接相关的代码,实际上不建议在单元测试中使用这些代码。

所以你需要做的可能是引入单元测试框架,特别是Mockto/Powermock或其他一些提供对象嘲讽功能的东西。通过这些测试框架,您可以模拟将在测试单元代码之外发生的数据库操作或其他函数调用。

另外,关于如何测试void函数,没有什么可以用Assert功能来比较输出,因为它没有像你提到的那样返回任何东西。 但是,仍然有单元测试的方法。

  1. 只需调用updateCustomerTagCount()以确保函数可以工作。即使只是调用函数,这些单元测试也可以提高你的单元测试覆盖率。 当然对于你的情况,你需要模拟

ImportTagJob.fetchData();

DatabaseInterface.getCustomer(tagNo);

而且必须。

  1. 设嘲笑

ImportTagJob.fetchData();

抛出空列表以及非空列表并检查您的代码是否按预期工作。如有必要添加异常处理。在你的代码中,有两个条件取决于fieList是否为null或非null,你需要测试它。

另外,模拟这些对象,并让它们抛出IllegalArgumentException,并期望它被抛出,并在函数抛出异常时编写一个单元测试。在Junit中,它应该像

@Test(expected = IllegalArgumentException.class) 
public void updateCustomerTagCountTest(){ 
    // mock the objects 
    xxxxx.updateCustomerTagCount(); 
} 

这样,您可以确保该函数在必要时正确引发异常。