如何在flutter中模拟数据库



我试着模拟数据库来测试我的本地api,我在官方文档中搜索,发现mockito可以很好地使用远程api,但也不能开箱即用地使用本地数据库,有什么办法解决它吗?

在这些情况下,您有两个选项(以及许多其他选项(。即使我的示例假设您正在进行HTTP调用,也没关系。您可以使用这些策略,而不管我所公开的具体用例是什么!


第一个是使用";战略模式"为API创建一个接口,然后在测试和生产API之间切换。这里有一个简单的例子:

abstract class HttpRepository {
const HttpRepository();
Future<Something> sendRequest();
}

现在可以创建两个具体类:一个用于实际的API调用,另一个只是用于测试的mock。

/// Use this in your tests
class MockHttpRepository extends HttpRepository {
const MockHttpRepository();
@override
Future<Something> sendRequest() async {
// Simulating the HTTP call
await Future.delayed(const Duration(seconds: 2));
return Something();
}
}
/// Use this in your Flutter code to make the actual HTTP call or whatever else
class ApiHttpRepository extends HttpRepository {
const ApiHttpRepository();
@override
Future<Something> sendRequest() async {
// Doing a real HTTP call
final response = await makeGetOrPost();
return Something.withData(response);
}
}

通过这种方式,您将在Flutter应用程序中使用ApiHttpRepository,在测试中使用MockHttpRepository。尽可能使用const构造函数。


另一种方法是使用mock来模拟假HTTP调用或其他任何东西。基本上,您使用when来";"陷阱";方法调用并返回一个可以控制的假响应。

// 1. "Enable" mocking on your type
class MockRepo extends Mock implements ApiHttpRepository {}
// 2. Mock methods
const ApiHttpRepository repo = MockRepo();
when(repo.sendRequest()).thenAnswer((_) async => Something());

在这种情况下,我们使用thenAnswer,因为sendRequest()的返回类型是Future<T>。在你的情况下,如果你正在从数据库中读取数据,你只需要:

  1. 让你的课"可模仿的";使用extends Mock implements YourClass
  2. 在mockable实例上使用when并控制输出

如果该方法在所有其他情况下都返回Future<T>thenReturn,请确保使用thenAnswer

最新更新