坏状态:在`when()`中未调用Mock方法。真正的方法叫做吗?

时间:2019-03-29 19:47:23

标签: dart flutter mockito flutter-test

我正在尝试使用Mockito对httpRequest进行模拟。

在这里我定义了一个全局http客户端:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();

然后我在集成测试中替换:

import 'package:flutter_driver/driver_extension.dart';
import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:mockito/mockito.dart';

import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  final MockClient client = MockClient();
  globals.httpClient = client;

  enableFlutterDriverExtension();

  app.main();
}

然后我尝试使用when的模仿:

test('login with correct password', () async {
      final client = MockClient();

      when(globals.httpClient.post('http://www.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });

但是我收到以下错误:

  

状态错误:when()中未调用模拟方法。是真的方法吗?

1 个答案:

答案 0 :(得分:3)

当您实现要模拟的方法而不是让Mockito这样做时,可能会发生此问题。

下面的代码将返回Bad state: Mock method was not called within when(). Was a real method called?

class MockFirebaseAuth extends Mock implements FirebaseAuth {
  FirebaseUser _currentUser;

  MockFirebaseAuth(this._currentUser);

  // This method causes the issue.
  Future<FirebaseUser> currentUser() async {
    return _currentUser;
  }
}

final user = MockFirebaseUser();
final mockFirebaseAuth = MockFirebaseAuth(user);

// Will throw `Bad state: Mock method was not called within `when()`. Was a real method called?`
when(mockFirebaseAuth.currentUser())
    .thenAnswer((_) => Future.value(user));

您想要的是:

class MockFirebaseAuth extends Mock implements FirebaseAuth {}

final user = MockFirebaseUser();
final mockFirebaseAuth = MockFirebaseAuth();

// Will work as expected
when(mockFirebaseAuth.currentUser())
    .thenAnswer((_) => Future.value(user));

当您尝试在非模拟子面板上呼叫when() 时,也会发生此问题:

class MyClass {
  String doSomething() {
    return 'test';
  }
}

final myClassInstance = MyClass();

// Will throw `Bad state: Mock method was not called within `when()`. Was a real method called?`
when(myClassInstance.doSomething())
    .thenReturn((_) => 'mockedValue');