如何使用Powermock模拟void私有方法抛出Abstract Exception?

时间:2017-12-20 14:34:19

标签: junit powermockito

在为方法 someMethod1 编写单元测试用例时,我有一个用例,我正在尝试确保抽象异常 AnalysisException someMethod2 )时抛出>)。被测试的类是 JdbcTemplateSampleImpl

public class JdbcTemplateSampleImpl {

   public void someMethod1() {
      someMethod2();
   }

   private void someMethod2() throws AnalysisException  {
    // some code here
   }
}

我正在使用 PowerMockito 这样做

@Test(expected = com.test.AnalysisException.class)
public void abstractClassExceptionCheck2Test1()  throws Throwable  {
    JdbcTemplateSampleImpl jdbcTemplateSampleImpl1 = 
              PowerMockito.spy(jdbcTemplateSampleImpl0);
    PowerMockito.doThrow(mock(AnalysisException.class)).
             when(jdbcTemplateSampleImpl1,"classCheck2");    
    jdbcTemplateSampleImpl1.abstractClassExceptionCheck2();
}

但是在执行测试用例时,我遇到了这样的错误

java.lang.Exception:意外异常,预期“com.test.AnalysisException”但是“java.lang.NullPointerException”

1 个答案:

答案 0 :(得分:0)

doThrow方法调用之外模拟异常。

AnalysisException e = mock(AnalysisException.class);
PowerMockito.doThrow(e).
         when(jdbcTemplateSampleImpl1,"classCheck2");