使用 Mockito 验证无参数和私有方法

Verifying no argument and private methods using Mockito

我是 JUnit 和 Mockito 的新手,下面的 class 定义了一个需要测试的方法 execute ,我想知道是否可以模拟这种类型的 class ?请发表一些看法并分享您的想法。

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

您可以模拟 scheduleListorderList 并使用 verify 来确保从它们调用正确的方法。

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

...

您只需将 foo 和 bar 替换为您希望调用的任何方法即可。

如果你正在测试 MyRule,你不应该嘲笑它。一个好的经验法则是不要模拟正在测试的 class。