如何使用简单的模拟来模拟消费者链接?

问题描述

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

   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
   }


解决方法

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