在下面的代码中,我想为
a
编写一个单元测试,并且我想模拟 b
。
我如何使用 mockito
或任何其他库来模拟它?
class Test {
Future<void> a() async {
await b();
}
Future<void> b() async {
// code
}
}
您可以执行以下操作:
首先添加mockito:
dev_dependencies:
mockito: ^5.0.0
您可以尝试如下所示:
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
class MockTest extends Mock implements Test {}
class Test {
Future<void> a() async {
await b();
}
Future<void> b() async {
}
}
void main() {
test('Test method a', () async {
final mockTest = MockTest(); // Create an instance of the class, and mock the b method
when(mockTest.b()).thenAnswer((_) async {
print('Mocked implementation of b');
});
await mockTest.a(); // Call the method you want to test
verify(mockTest.b()).called(1); // Verify that the mocked method was called
});
}