【问题标题】:How to Assert file existing in other module - JUNIT如何断言其他模块中存在的文件 - JUNIT
【发布时间】:2017-05-30 03:57:37
【问题描述】:

我的目录结构如下所示

Root
|--A
   |--src
   |--target
   |--output.xml 

|--B
   |--src
       |--test
            |--java
                 |--MyTest.java

我的 Junit 测试方法如下所示`

@Test
public void testXmlGeneration() {
   File file = new File("output.xml");
    assertTrue(file.exists());
}

我想检查 output.xml 是否在目录 A 中生成。上面的测试失败了

java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:86)
    at org.junit.Assert.assertTrue(Assert.java:41)

我也尝试了下面的方法,但它失败了 NullPointerException。`

    File file = new File(this.getClass().getClassLoader().getResourceAsStream("A/output.xml").toString());
assertTrue(file.exists());

NullPointerException 堆栈跟踪如下

java.lang.NullPointerException
    at com.B.StatisticsTest.testXmlGeneration(StatisticsTest.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

【问题讨论】:

  • 尝试将完整路径指定为 new File("Root/A/output.xml") 并共享 NPR 堆栈跟踪。
  • 它因 java.lang.AssertionError 而失败。 StackTrace 与上面相同。 @nullpointer

标签: java maven junit junit4


【解决方案1】:
   File file = new File(this.getClass().getClassLoader().getResourceAsStream("A/output.xml").toString());

它的 .toString() 方法。它不会被视为文件,这就是为什么您会收到该错误,您可以尝试如下所示

  @Test
  public void test() {
    File f = new File(this.getClass().getClassLoader().getResource("A/output.xml").getFile());      
    assertTrue(f.exists());
  }

【讨论】:

  • 使用上面相同的堆栈跟踪失败并出现 NullPointer 异常。
  • (this.getClass().getClassLoader().getResource("A/output.xml").getFile()) 将返回一个文件以防万一没有这样的文件它会返回 nullpointer
  • 虽然文件存在,但我怀疑可能存在一些配置问题!无论如何感谢您的快速回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 2018-12-23
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多