[英]Why does getClass().getResource() return null upon second @Test in Powermock unit test
我有一個單元測試類,它需要從資源中加載文件。 所以我有這樣的事情:
@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也不起作用。
我對單元測試有些陌生,所以如果有人可以闡明這個問題,那將是很棒的。
由於測試會刪除您的源文件,因此在運行測試之前,請將資源復制到一個臨時位置。 無論如何,這是一個好習慣,以避免損壞測試資源。
看一下使用JUnit的臨時文件支持: 在JUnit 4.7中使用臨時文件 。 您不必那樣做,但這是一個很好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.