如何在方法中编写变量参数的测试用例

时间:2017-04-06 05:40:01

标签: java junit mockito

我想为下面的课程编写单元测试。 使用变量参数调用这些方法。任何人都可以帮我编写变量参数方法的测试用例吗?

  class WCfg  {

  private void setAddr(MCfg mCfg, String... arg)
             throws Exception {
    try {

    } catch (Exception e) {
      throw new Exception("Invalid IP address.", e);
    }
  }

  public String process(String... arg) throws Exception {
    MCfg mCfg = new MCfg();

    try {      

      setAddr(mCfg, arg);

     } catch (Exception e) {
       return "Wrong argument format.";
     }

     mCfg.write();

    return "success";
  }
}

测试代码:

   import org.junit.Test;

   public class MCfgTest {

   @Test
    public void Success() throws Exception {
      WCfg wmc = new WCfg();
      wmc.process(String... arg);
    }
 }

1 个答案:

答案 0 :(得分:3)

简单;你想测试所有可能的选项" varargs"可以用:

WriteMapCfg underTest = ... 

@Test
public void testProcessWithNoArgs() {
  underTest.process();

@Test
public void testProcessWithNullArray() {
  underTest.process((String []) null);
  ...

@Test
public void testProcessWithNullString() {
  underTest.process((String) null);
  ...

@Test
public void testProcessWithOneString() {
  underTest.process("whatever");
  ...

@Test
public void testProcessWithMultipleStrings() {
  underTest.process("whatever", "whocares");
  ...

重点是:这5个案例是可能的;并且每个都需要至少一个测试用例。