【问题标题】:Mockito to test the catch block of private methodMockito 测试私有方法的 catch 块
【发布时间】:2023-03-06 11:48:01
【问题描述】:

我需要编写一个测试来验证当私有method_C抛出IOException时,Method_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. Method_C在A中有私有访问权限

关于如何纠正此问题的任何建议?

【问题讨论】:

标签: java unit-testing junit mockito powermockito


【解决方案1】:

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");
    }

}
}

【讨论】:

  • 您不需要使用finally,这并不能回答问题。
  • 再次阅读问题
猜你喜欢
  • 1970-01-01
  • 2021-08-16
  • 2021-05-02
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多