Mockito when().thenReturn calls the method unnecessarily

后端 未结 5 2344
挽巷
挽巷 2021-02-19 02:23

I\'m working a bit on an inherited code. I\'ve written a test that is supposed to catch NullPointerException (for it is trying to call a method from null object)



        
5条回答
  •  感情败类
    2021-02-19 02:48

    Mockito cannot mock static method. Your when check is not valid:

      when(BasketHelper.getAction(request)).thenReturn(0);
      when(BasketHelper.getActionProduct(site, request)).thenReturn(product);
    

    That is another reason why we want to reduce the use of static method as it is hard to mock.

    There is no easier way to mock the behavior if your class stays like this. However if you want to change your design and make both methods non-static. The correct way of using "when" is to apply the check on mocked object. For example:

      BasketHelper basketHelper = mock(BasketHelper.class);
      when(basketHelper.getAction(request)).thenReturn(0);
      when(basketHelper.getActionProduct(site, request)).thenReturn(product);
    

    But once again, this only work if you re-designed your class's getAction and getProduct method to be NON-STATIC.

    I remember there are some other testing framework that does support mocking static method.

提交回复
热议问题