我有一个单元测试类,需要从资源加载一个文件。所以我有这样的事情:
@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
}
}
问题是第一次调用setup()时可以找到来自资源的文件,但奇怪的是,当第二次调用setup()时,resourceFile再次为null(这对我来说是另一个谜;在我的脑海里) ,我认为应该已经设置了)所以它必须再次设置,但是然后调用getResource()返回null,因此抛出异常。这几乎就像整个MyTestClass在@Test调用之间重置。甚至在@Before方法之外初始化resourceFile也不起作用。
我对单元测试有些新意,所以如果有人能够解释这个问题,那就太棒了。
答案 0 :(得分:1)
由于测试会删除源文件,因此请在运行测试之前将资源复制到临时位置。无论如何,这是一种很好的做法,以避免破坏测试资源。
看一下使用JUnit的临时文件支持: Working with temporary files in JUnit 4.7。你不必那样做,但这是一个很好的解决方案。