gpt4 book ai didi

flutter - 使用 mocktail 包进行单元测试时,类型 'Null' 不是类型 'Future' 的子类型

转载 作者:行者123 更新时间:2023-12-05 03:17:07 25 4
gpt4 key购买 nike

我们如何验证函数内部的方法是否被调用?我这里有一个示例代码。

class MockService extends Mock implements Service {}

class MockRepository extends Mock implements Repository {}

class Repository {
Repository({
required this.service,
});
final Service service;

Future<void> somethingFancy() async {
await service.doSomething();
}
}

class Service {
Future<void> doSomething() async {}
}

void main() {
final service = MockService();
final repository = Repository(service: service);

group('auth repository test', () {
test('test name', () async {
when(repository.somethingFancy).thenAnswer((_) => Future.value());
await repository.somethingFancy();

verify(service.doSomething).called(1);
});
});
}

如果我运行测试,我会得到这个错误:

type 'Null' is not a subtype of type 'Future<void>'
test/auth_repository_test.dart 20:16 MockService.doSomething
test/auth_repository_test.dart 15:19 Repository.registerUser
package:mocktail/src/mocktail.dart 210:8 when.<fn>
test/auth_repository_test.dart 29:11 main.<fn>.<fn>
===== asynchronous gap ===========================
dart:async _completeOnAsyncError
package:mocktail/src/mocktail.dart 210:8 when.<fn>
test/auth_repository_test.dart 29:11 main.<fn>.<fn>

如果我将存储库变量更改为 final repository = MockRepository();,我无法注入(inject) Service 类,因此肯定不会调用服务类中的方法。这就是为什么如果我运行这个测试:

void main() {
final service = MockService();
final repository = MockRepository();

group('auth repository test', () {
test('test name', () async {
when(repository.somethingFancy).thenAnswer((_) => Future.value());
await repository.somethingFancy();

verify(service.doSomething).called(1);
});
});
}

我收到一条错误消息说没有匹配的调用

No matching calls (actually, no calls at all).
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:test_api fail
package:mocktail/src/mocktail.dart 722:7 _VerifyCall._checkWith
package:mocktail/src/mocktail.dart 515:18 _makeVerify.<fn>
test/auth_repository_test.dart 32:13 main.<fn>.<fn>

我在这里做错了什么?非常感谢您的帮助。

最佳答案

你在测试中使用了错误的方法。

您必须模拟回答 Service#doSomething 而不是 Repository#doSimethingFancy。检查您的 when 语句。

test('test name', () async {
when(service.doSomething()).thenAnswer((_) => Future.value());
await repository.somethingFancy();

verify(service.doSomething).called(1);
});

关于flutter - 使用 mocktail 包进行单元测试时,类型 'Null' 不是类型 'Future<void>' 的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74312836/

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