子类Flutter单元测试失败

b0zn9rqh  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(137)

检测方法:

@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上测试故障情况。
失败的类结构如下所示:

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()));
  });


最后一行失败,并出现以下错误:
预期:Left<CacheFailure,dynamic>:<Left('CacheFailure'的示例)>
Actual:Left<Failure,SampleModel>:<Left(Instance of 'CacheFailure')>
我很困惑,因为该方法显然返回了CacheFailure,但测试表明我返回的是超类Failure。此外,为什么这很重要?CacheFailureFailure
可能是个小疏忽,但我就是看不出来。

2vuwiymt

2vuwiymt1#

那个expect只是在我的思想中比较result == Left(CacheFailure())
如何使用isA<Left<Failure, SampleModel>>()匹配器?

vddsk6oq

vddsk6oq2#

以下内容适用于仍在搜索解决方案的用户:

result.fold((l) => {expect(l, isA<ServerFailure>())}, (r) => {expect(r, null)});

字符串

相关问题