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) {
//......
}
}
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.