0

I am new to JUnit & Mockito, the below class is defined with a method execute which needs to be tested, I wonder is it possible to mock this type of class ? Please shed some light and share your thoughts.

public class MyRule implements SuperRule{    
  private OrderList orderList;
  private ScheduleList scheduleList;

  public MyRule (OrderList orderList, ScheduleList scheduleList) {
    this.orderList = orderList;
    this.scheduleList = scheduleList;
  }

  @Override
  public void execute() {
    createWeeklyClassificationRule(orderList);      
    handle(scheduleList);

  }      
  private void createWeeklyClassificationRule(OrderList orderList) {
   //......
  }      
  private void handle(ScheduleList scheduleList) { 
    //......      
  }
}
  • Please go through https://stackoverflow.com/questions/8799439/testing-private-method-using-mockito – Vivek Jan 28 '20 at 17:43
  • Does this answer your question? [How do I test a private function or a class that has private methods, fields or inner classes?](https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or) – Kaan Jan 28 '20 at 18:10

1 Answers1

0

You could mock scheduleList and orderList instead and use verify to make sure the correct methods are being called from them.

public class MyRuleTest
{
  private MyRule myRule;
  private ScheduleList scheduleListMock;
  private OrderList orderListMock;

  @Before
  public void setUp() throws Exception
  {
    scheduleListMock = mock(ScheduleList.class);
    orderListMock = mock(OrderList.class);

    myRule = new MyRule(orderListMock, scheduleListMock);
  }

  @Test
  public void testExecute()
  {
    myRule.execute();
    verify(scheduleListMock).foo();
    verify(orderListMock).bar();
  }

...

You would just replace foo and bar with whatever methods you are expecting to be called.

If you are testing MyRule, you shouldn't be mocking it. A good rule of thumb is to not mock the class that is under test.