一尘不染

如何验证是否调用方法

flutter

class MockView extends Mock implements ContactListViewContract {

  @override
  void onLoadContactsComplete(List<Contact> items) {

  }
  @override
  void onLoadContactsError() {}

}

void main() {

  test('ContactListPresenter test', () {
    Injector.configure(Flavor.MOCK);
    MockView view = new MockView();

    ContactListPresenter presenter = new ContactListPresenter(view);

    presenter.loadContacts();

    verify(view.onLoadContactsComplete).called(1);

  });

}

我想确保presenter.loadContacts()从代码中调用何时,然后view.onLoadContactsComplete还调用了verify,但出现错误:

用于非模仿对象

Mockito是否可以执行此操作?

更新:

abstract class ContactListViewContract {
  void onLoadContactsComplete(List<Contact> items);
  void onLoadContactsError();
}

这里的onLoadContactsComplete方法叫做

class ContactListPresenter {
  ContactListViewContract _view;
  ContactRepository _repository;

  ContactListPresenter(this._view){
    _repository = new Injector().contactRepository;
  }

  void loadContacts(){
    assert(_view != null);

    _repository.fetch()
        .then((contacts) {
          print(contacts);
          _view.onLoadContactsComplete(contacts); // here the onLoadContactsComplete method is called
        }).catchError((onError) {
          print(onError);
          _view.onLoadContactsError();
        });
  }

}

模拟存储库。提取模拟数据。

class MockContactRepository implements ContactRepository{

  Future<List<Contact>> fetch(){
    return new Future.value(kContacts);
  }

}

阅读 313

收藏
2020-08-13

共1个答案

一尘不染

调用verify方法时,您需要在模拟对象上调用实际方法

尝试

test('ContactListPresenter test', () async {
    Injector.configure(Flavor.MOCK);
    MockView view = new MockView();

    ContactListPresenter presenter = new ContactListPresenter(view);

    presenter.loadContacts();

    await untilCalled(view.onLoadContactsComplete(typed(any))); 
    //completes when view.onLoadContactsComplete(any) is called

    verify(view.onLoadContactsComplete(typed(any))).called(1);

});

如果没有一次调用该方法,则测试将失败。

2020-08-13