2014-09-26 61 views
0

我有一个单元测试类,它需要从资源加载文件。所以,我有这样的事情:为什么在PowerMock单元测试中第二个@Test getClass()。getResource()返回null

@RunWith(PowerMockRunner.class) 
@PrepareForTest(MyClass.class) 
public class MyClassTest { 

    private File resourceFile; 

    @Before 
    public void setup() { 

     // The first time this is called, resourceFile is set up correctly 
     // However, the second time, the call to getResource() returns a null and thus 
     // an exception is thrown. 
     if (resourceFile == null) { 
      resourceFile = new File(getClass().getResource("/file.wav").getPath()); 
     } 
    } 

    @Test 
    public void firstTest() { 
     // resourceFile is available here 
    } 

    @Test 
    public void secondTest() { 
     // resourceFile is null here 
    } 
} 

的问题是,从资源文件,可以发现在第一时间设置()被调用,但奇怪的是,当设置第二个()调用发生时,的resourcefile再次为null(这是我的另一个谜团;在我看来,我认为应该已经设置好了),所以它必须重新设置,但是随后调用getResource()返回null,从而引发异常。这几乎就像整个MyTestClass在@Test调用之间重置。即使在@Before方法之外初始化resourceFile也不起作用。

我在单元测试方面有点新,所以如果有人能够解决这个问题,那就太好了。

+2

嗨,junit为每个测试创建一个测试类的新实例。看看[这个问题](http://stackoverflow.com/questions/19381352/does-junit-reinitialize-the-class-with-each-test-method-invocation)。对于你的测试用例,我建议你使用'@BeforeClass'(静态)而不是'@Before'。关于getResource()nullPointer,我一直无法重现它(我已经运行完全相同的测试,对我来说resourceFile在两个测试中都可用) – troig 2014-09-26 07:31:59

+2

您的任何测试是否删除资源文件? – 2014-09-26 11:00:50

+0

是否真的与powermock有关,你是否只用junit测试? – gontard 2014-09-26 12:55:07

回答

1

由于测试会删除源文件,因此在运行测试之前将资源复制到临时位置。无论如何,这是很好的做法,以避免破坏测试资源。

看看使用JUnit的临时文件支持: Working with temporary files in JUnit 4.7。你不必这样做,但它是一个很好的解决方案。

+0

标记为答案,因为这是我最终做的。 – BrianP 2014-09-28 13:45:10

相关问题