mockito测试私有方法的catch块

y4ekin9u  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(543)

我需要编写一个测试来验证当私有方法_c抛出ioexception时,方法_b返回true。但是

public final class A{

 public static Boolean Method_B(){

try{

 //call a private method C which throws IOException
    Method_C

}

catch(final IOException e) {
return Boolean.True
}

}

private static Method_C() throws IOException {
        return something;
    }

我尝试的是:

@Test
public void testSomeExceptionOccured() throws IOException {
     A Amock = mock(A.class);
     doThrow(IOException.class).when(Amock.Method_C(any(),any(),any(),any()));
     Boolean x = A.Method_B(some_inputs);
     Assert.assertEquals(Boolean.TRUE, x);
}

我遇到编译错误:1.无法模拟最终类2.方法c在
对如何纠正这一问题有何建议?

dxxyhpgq

dxxyhpgq1#

您需要在try-catch中使用finally

import java.io.*;
public class Test {
 public static Boolean Method_B() {
    try {
        System.out.println("Main working going..");
        File file = new File("./nofile.txt");
        FileInputStream fis = new FileInputStream(file);

    } catch (IOException e) {
        // Exceptiona handling
        System.out.println("No file found ");
    } catch (Exception e) {
        // Exceptiona handling
        System.out.println(e);
    } finally {
        return true;
    }
}
public static void main(String args[]) {
    if (Test.Method_B()) {
        System.out.println("Show true ans");
    } else {
        System.out.println("Sorry error occure");
    }

}
}

相关问题