Kha*_*dan 7 unit-testing dart flutter
我期望两个实例相等。
我写了下面的代码:
test('Should return a valid model when the user is fetched from the api',
() async {
final Map<String, dynamic> jsonMap =
json.decode(fixture('login_fixture.json'));
final result = LoginModel.fromJson(jsonMap);
expect(result, testingLoginModel);
});
Run Code Online (Sandbox Code Playgroud)
它失败并显示以下消息:
Expected: <Instance of 'LoginModel'>
Actual: <Instance of 'LoginModel'>
00:01 +0 -1: Some tests failed.
Run Code Online (Sandbox Code Playgroud)
正如我们所看到的,预期结果等于实际结果“<Instance of 'LoginModel'>”
那么为什么它会失败呢?
您有两个不同的 LoginModel 实例。即使它们具有相同的值,它们也不相等。
更新您的模型
class LoginModel{
String name = "some";
@override
bool operator ==(Object other) => other is LoginModel && other.name == name;
@override
int get hashCode => name.hashCode;
}
Run Code Online (Sandbox Code Playgroud)
或使用
https://pub.dev/packages/equatable