gpt4 book ai didi

unit-testing - 如何验证调用或不调用方法

转载 作者:IT王子 更新时间:2023-10-29 06:41:47 25 4
gpt4 key购买 nike

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 但出现错误:

Used on a non-mockito object

有没有可能用 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);
}

}

最佳答案

当调用 verify 方法时,你需要调用 mock 上的实际方法

尝试

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

});

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

关于unit-testing - 如何验证调用或不调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48293314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com