我正在尝试用我的APP测试文件操作。首先,我想检查一下,每当我调用一个读取文件的函数时,这个函数都会抛出异常,因为文件不存在。
但是,我似乎不明白如何实现这一点......这是我设计的代码,但它没有运行......正常的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 :(得分: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()
代码不抛出异常并将异常生成代码移动到测试方法,使用适当的方法来测试它。