Flutter 单元测试在子类上失败

Flutter Unit Test Fails on Subclass

测试方法:

@override
  Future<Either<Failure, SampleModel>> getSampleModel(String activityType) async {
    if (await networkInfo.isConnected()) {
      final remoteModel = await remoteDataSource.getSampleModel(activityType);
      localDataSource.cacheSampleModel(remoteModel);
      return Right(remoteModel);
    } else {
      try {
        final localModel = await localDataSource.getSampleModel(activityType);
        return Right(localModel);
      } on CacheException {
        return Left(CacheFailure());
      }
    }
  }

正在尝试测试 localDataSource 上的失败场景。

失败的 class 结构如下所示:

abstract class Failure {
  Exception? exception;

  Failure() : exception = null;
}

class CacheFailure extends Failure {}

我认为很简单。这是我的测试:

test(
      'should return failure when the call to remote data source is unsuccessful',
      () async {
    // arrange
    when(mockNetworkInfo.isConnected()).thenAnswer((_) async => false);
    when(mockLocalDataSource.getSampleModel(any)).thenThrow(CacheException());
    // act
    final result = await repository.getSampleModel(activityType);
    // assert
    verifyZeroInteractions(mockRemoteDataSource);
    verify(mockLocalDataSource.getSampleModel(activityType));
    expect(result, Left(CacheFailure()));
  });

最后一行失败并出现此错误:

Expected: Left<CacheFailure, dynamic>:<Left(Instance of 'CacheFailure')>
Actual: Left<Failure, SampleModel>:<Left(Instance of 'CacheFailure')>

我很困惑,因为该方法清楚 returns a CacheFailure 但测试表明我正在返回超级 class Failure。此外,为什么这很重要? CacheFailureFailure.

可能是一个简单的疏忽,但我就是看不出来。

那个expect在我的想法中简直就是比较result == Left(CacheFailure())

使用 isA<Left<Failure, SampleModel>>() 匹配器怎么样?