2014-11-08 190 views
1

我正在嘗試使用我的APP測試文件操作。首先,我想檢查一下,無論何時我調用讀取文件的函數,該函數都會拋出異常,因爲文件不在那裏。Android JUNIT文件操作測試

但是,我似乎不明白如何實現這...這是我設計的代碼,但它不運行...正常的JUNIT說沒有找到FILEPATH,android JUNIT說,測試不能運行。

文件夾:/data/data/example.triage/files/是在虛擬設備已經上市...

@Before 
public void setUp() throws Exception { 

    dr = new DataReader(); 
    dw = new DataWriter(); 
    DefaultValues.file_path_folder = "/data/data/example.triage/files/"; 
} 

@After 
public void tearDown() throws Exception { 

    dr = null; 
    dw = null; 

    // Remove the patients file we may create in a test. 
    dr.removeFile(DefaultValues.patients_file_path); 

} 

@Test 
public void readHealthCardsNonExistentPatientsFile() { 

    try { 
     List<String> healthcards = dr.getHealthCardsofPatients(); 
     fail("The method didn't generate an Exception when the file wasn't found."); 
    } catch (Exception e) { 
     assertTrue(e.getClass().equals(FileNotFoundException.class)); 
    } 

} 

回答

0

它看起來並不像你檢查的方式外與JUnit API相關。

您是否嘗試過撥打電話:

@Test (expected = Exception.class) 
public void tearDown() { 

    // code that throws an exception 

} 

我不認爲你想要的setup()功能,能夠生成一個例外,因爲它是所有其他測試用例之前調用。

這裏的另一種方法來測試例外:

Exception occurred = null; 
try 
{ 
    // Some action that is intended to produce an exception 
} 
catch (Exception exception) 
{ 
    occurred = exception; 
} 
assertNotNull(occurred); 
assertTrue(occurred instanceof /* desired exception type */); 
assertEquals(/* expected message */, occurred.getMessage()); 

所以,我會讓你setup()代碼不會拋出異常,異常生成代碼移到測試方法,使用適當的方法來測試它。

+0

SetUp不會生成異常...它只是創建對象的新實例即時檢查.. – OHHH 2014-11-08 21:55:59

+0

好吧完美。我會在'setup()'方法中移除'throws Exception'標記,然後你不需要它。重寫'tearDown()'是否修復了JUnit問題? – 2014-11-08 22:12:26

+0

我意識到問題在於測試的工作方式......爲了測試Android應用程序的行爲,您需要一個新的應用程序來打開待測試應用程序並分析變量。我通過爲此創建一個新項目來解決問題。 – OHHH 2014-11-09 02:11:52