有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用JUNIT的java Android文件操作测试

我正在尝试用我的应用程序测试文件操作。首先,我想检查一下,每当我调用一个读取文件的函数时,这个函数都会抛出一个异常,因为文件不在那里

然而,我似乎不明白如何做到这一点。。。这是我设计的代码,但它不运行。。。正常的JUNIT说找不到文件路径,安卓 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));
    }

}

共 (1) 个答案

  1. # 1 楼答案

    看起来您并没有以与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()代码不抛出异常,并将生成异常的代码移动到一个测试方法中,使用适当的方法对其进行测试