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

Fel*_*sto 7 mockito dart flutter flutter-test

我正在尝试httpRequest使用Mockito 模拟颤振。

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

library utgard.globals;

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

http.Client httpClient = http.Client();
Run Code Online (Sandbox Code Playgroud)

然后我将其替换为集成测试:

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();
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试使用whenMockito:

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);
    });
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误:

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

And*_*eev 23

当您实现想要模拟的方法而不是让 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));
Run Code Online (Sandbox Code Playgroud)

你想要的是:

class MockFirebaseAuth extends Mock implements FirebaseAuth {}

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

// Will work as expected
when(mockFirebaseAuth.currentUser())
    .thenAnswer((_) => Future.value(user));
Run Code Online (Sandbox Code Playgroud)

当您尝试调用when()非模拟 sublass 时,也会发生此问题:

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');
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,我想模拟“toString()”,这样我就可以更清楚地看到错误,而不仅仅是类名,而且“toString()”已经从“Mock”本身定义了。 (2认同)