【问题标题】:mocking creation of an array with powermock java使用 powermock java 模拟数组的创建
【发布时间】:2013-08-26 08:18:21
【问题描述】:

我想在java中为以下函数编写一个测试。我想模拟数组的创建。

public File[] myFunc()
{  

 File[] array = new File[2];

 return array;

}

我使用 powermock java 编写了以下测试:

@Test

public void test1()
{

 File f1 = createMock(File.class);

 File[] files = new File[]{f1};

 expectNew(File[].class).andReturn(fArray);

 replayAll();

 File[] res = myclass.myFunc();

 verifyAll();

assertEquals(f1, res[0]);

}

它会抛出异常并显示以下消息: org.powermock.reflect.exceptions.ConstructorNotFoundException: No constructor found in class java.io.file with parameter types:<none>

【问题讨论】:

    标签: java unit-testing powermock


    【解决方案1】:

    异常已经说明了:您尝试创建一个 File 实例而不指定构造函数参数,但是对于 java.io.File 类没有没有参数的构造函数。异常的堆栈跟踪将告诉您尝试的代码位置。我猜是File f1 = createMock(File.class);。查看 powermock 文档以获取替代方案。

    【讨论】:

      【解决方案2】:

      模拟这个数组的创建对我来说毫无意义,因为其中没有值。一个更简洁的测试是这样的:

      @Test
      public void test1() {
          File[] result = myclass.myFunc();
          assertEquals(2, result.length);
          for (File f : result) {
              assertNull(f);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多