【问题标题】:Mockito NullPointerException Inner Method codeMockito NullPointerException 内部方法代码
【发布时间】:2015-04-13 04:28:00
【问题描述】:

我是 Mockito junit 测试的新手,遇到了一个问题。如果你们能帮我解决这个问题,我将不胜感激。

class Activity{
   Connection conn;
   public SomeObject firstMethod() {
          /* *some code*  */
          SomeObject obj = secondMethod();
          return obj;
   }

   public SomeObject secondMethod(){
         /* *some code* */
         PreparedStatement ps = null;

         try{
             ps = conn.createStatement();
             ps.setBytes(1, *someString*);
         }catch(Exception e) { ... }

         /* *some code* */
         return someObject;
   }
}

下面是我写的测试类。 secondMethod() 的单元测试完美运行。

class ActivityTest{

  Activity activity;
  @Before
  public void setUp(){
     activity = new Activity();
     Connection conn = mock(Connection.class);
     activity.setConnection(conn);
  }

  @Test
  public void testSecondMethod(){
        /*  *works perfectly* */ 
  }

 @Test
 public void testFirstMethod(){

     SomeObject someObj = new SomeObject();

     // *I get error on below line*
     when(activity.secondMethod()).thenReturn(someObj);

     SomeObject result = activity.firstMethod();
     assertEquals(someObj, result);
 }
}

我在 when(activity.secondMethod()).thenReturn(someObj) 上收到 NullPOinterException。当我跟踪错误堆栈时,空值是preparedStatement 对象ps。它发生在 secondMethod() 中的 ps.setBytes() 上。

我不明白这部分。为什么我会因为 ps 为空而得到异常。我为包含该代码的 secondMethod() 编写了一条规则。 我是否需要模拟 PreparedStatement obj.模拟所有内部对象也没有意义,因为我已经为它们所在的方法定义了规则。

你们能帮帮我吗?

谢谢

【问题讨论】:

    标签: java unit-testing junit nullpointerexception mockito


    【解决方案1】:

    好吧,那是因为您正在调用 secondMethod() 函数的实际实现。当然,您可以通过尝试模拟所有内部对象来避免这种情况。

    但是,在这种情况下。我认为您也可以尝试使用doReturn/when 函数而不是when/thenReturn 函数。

    样本是这样的。

    doReturn(someObj).when(activity).secondMethod();
    

    希望对你有所帮助;)

    【讨论】:

      猜你喜欢
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      相关资源
      最近更新 更多