0

我在 Dart 中使用 Mockito 来测试异步代码。

我有这个带有异步调用的类:

class StorageService {
  FirebaseStorage _storage;
  
  Future<bool> uploadMyImage(MyImage myImage) async {
    final path = "/${myImage.id}.jpg";

    try {
      await _storage.ref(path).putData(myImage.data);
      return true;
    } on Exception {
      return false;
    }
  }
}

我正在尝试像这样测试它:

@GenerateMocks([FirebaseStorage, Reference, UploadTask, TaskSnapshot])
void main() {
  test('uploadMyImage returns true on successful upload', () async {
    // 1. given
    final mockFirebaseStorage = MockFirebaseStorage();
    final subject = StorageService(firebaseStorage: mockFirebaseStorage);

    final myImage = Generators.myImage();
    final mockReference = MockReference();
    final mockUploadTask = MockUploadTask();
    final mockTaskSnapshot = MockTaskSnapshot();

    // 2. when
    final path = "/${myImage.id}.jpg";

    when(mockFirebaseStorage.ref(path)).thenReturn(mockReference);
    when(mockReference.putData(myImage.data)).thenAnswer((_) => mockUploadTask);
    when(await mockUploadTask).thenAnswer((_) => mockTaskSnapshot);

    final result = await subject.uploadMyImage(myImage);

    // 3. then
    expect(result, true);
  });
}

单元测试永远不会完成,因为它正在等待await mockUploadTask. 我如何使它完整?

4

0 回答 0