mockito 在dart空值安全的模拟方法中使用参数匹配器时出错

6bc51xsx  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(126)

我在使用argument matcher,any的时候收到了下面的错误信息,当我在一个空的安全dart代码库中使用mockito模拟dart测试中的一个方法的时候。
错误:

The argument type 'Null' can't be assigned to the parameter type 'int'.

测试代码可在此处找到:

class MockNumberTriviaRepository extends Mock implements NumberTriviaRespository {}

void main() {
  late GetConcreteNumberTrivia usecase;
  late MockNumberTriviaRepository mockNumberTriviaRepository;

  setUp(() {
    mockNumberTriviaRepository = MockNumberTriviaRepository();
    usecase = GetConcreteNumberTrivia(mockNumberTriviaRepository);
  });

  const tNumber = 1;
  const tNumberTrivia = NumberTrivia(number: tNumber, text: "test");

  test('should get trivia for the number from repository', () async {
    //arrange
    when(mockNumberTriviaRepository.getConcreteNumberTrivia(any)).thenAnswer((_) async => const Right(tNumberTrivia));

    //act
    final result = await usecase.execute(tNumber);

    //assert
    // UseCase should simply return whatever was returned from the Repository
    expect(result, const Right(tNumberTrivia));
    // Verify that the method has been called on the Repository
    verify(mockNumberTriviaRepository.getConcreteNumberTrivia(tNumber));
    verifyNoMoreInteractions(mockNumberTriviaRepository);
  });
}

实现代码可在此处找到:

abstract class NumberTriviaRespository {
  Future<Either<Failure, NumberTrivia>> getConcreteNumberTrivia(int number);
  Future<Either<Failure, NumberTrivia>> getRandomNumberTrivia();
}

abstract class Failure extends Equatable {
  const Failure([List properties = const <dynamic>[]]);
}

class GetConcreteNumberTrivia {
  final NumberTriviaRespository respository;

  const GetConcreteNumberTrivia(this.respository);

  Future<Either<Failure, NumberTrivia>> execute(int number) async {
    return await respository.getConcreteNumberTrivia(number);
  }
}

class NumberTrivia extends Equatable {
  final String text;
  final int number;

  const NumberTrivia({required this.text, required this.number});

  @override
  List<Object?> get props => [text, number];
}
kt06eoxx

kt06eoxx1#

Mockito在Dart零安全方面有问题。请参阅https://github.com/dart-lang/mockito/blob/master/NULL_SAFETY_README.md
您可以按照上面链接中的方法重写mock类的实现以支持空参数:

class MockNumberTriviaRepository extends Mock
    implements NumberTriviaRespository {
  @override
  Future<Either<Failure, NumberTrivia>> getConcreteNumberTrivia(int? number) =>
      super.noSuchMethod(Invocation.method(#getConcreteNumberTrivia, [number]),
          returnValue: Future.value(
              Right<Failure, NumberTrivia>(NumberTrivia(text: "", number: 1))));
}

相关问题