2014-11-08 191 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