2014-09-26 104 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

相關問題