【问题标题】:How to mock consumer chaining with easy mock?如何使用简单的模拟来模拟消费者链接?
【发布时间】:2021-05-12 22:41:43
【问题描述】:

尝试使用简单模拟 3.3.1 测试类 Foo 的方法 foo 在链接两个以上的消费者时抛出空指针异常。

   class Foo 
    {
      // init with constructor
       Bar1 bar1; 
       Bar2 bar2;
       Bar3 bar3;
       FooBar fooBar;
    
     public fooBar foo(){
        // line throwing NPE while running unit test.
        return fooBar.get(bar1.andThen(bar2).andThen(bar3));
      }
    }
    // Bar2 and Bar 3 has similar implementation
    class Bar1 extends Consumer<T> {
         @Override
         public void accept(T t) {...}
    }
    // class which accepts consumers.
    class FooBar {
      public fooBar get(Consumer consumer) {...}
    }
    // In test class, test method as such 
   {
      expect(fooBar.get(anyObject()).andReturn(MOCKED_OBJ);
      // if chaining only two object it works as expected. 
      // fooBar.get(bar1.andThen(bar2)) its returns MOCKED_OBJ but if chaining more than two its throws NPE
   }


【问题讨论】:

    标签: java unit-testing automated-tests easymock


    【解决方案1】:

    Consumer.andThen(Consumer) 自己返回一个新的 Consumer 函数。在上述情况下,哪个会返回null,从而将第三个消费者结果添加到 NPE。

    解决方案:

        // mock a Consumer
        @Mock(type = MockType.NICE)
        private Consumer<T> consumerMock;
        // in test method 
        {
          ...
          expect(bar1.andThen(bar2)).andReturn(consumerMock);
          expect(consumerMock.andThen(bar3)).andReturn(consumerMock);
          ...
        }
    
    
    

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 2018-04-23
      • 1970-01-01
      • 2021-10-17
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多