首页 > 解决方案 > 存根函数总是返回 null

问题描述

目前我正在关注 Resocoder 的教程(DDD 课程)。在本课程中,有一个名为i_auth_facade.dart的抽象类,其中包含一个函数 getSignedInUser。

我已经模拟了该类并试图从 getSignedInUser 方法中获取用户的有效选项,但结果始终为空。

此外,当我尝试执行 AuthBloc 的authCheckRequested方法时,该方法然后在后台调用 getSignedInUser 方法,我返回 null。

我一定对 Mockito 有一些错误,因为它似乎存根不起作用。

谁能指出我正确的方向,为什么我没有取回 optionOf(User),而是 null ?

import 'package:bloc_test/bloc_test.dart';
import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:teach_mob_student/application/auth/auth_bloc.dart';
import 'package:teach_mob_student/domain/auth/i_auth_facade.dart';
import 'package:teach_mob_student/domain/auth/user.dart';
import 'package:teach_mob_student/domain/auth/value_objects.dart';
import 'package:teach_mob_student/domain/core/value_objects.dart';

class MockIAuthFacade extends Mock implements IAuthFacade {}

void main() {
  final tValidUser = User(
    id: UniqueId(),
    name: StringSingleLine('Test User'),
    emailAddress: EmailAddress('test@user.com'));


  test('Should return valid option of user', () async {
    // This is to check, if optionOf actually returns a user --> Yes it does
    Option<User> tDirectResult = optionOf<User>(tValidUser);

    // Here I stub the getSignedInUser method. If it is executed, I want to receive a valid user.
    when(MockIAuthFacade()
      .getSignedInUser()
    ).thenAnswer((_) async => Future.value(optionOf<User>(tValidUser)));

    // Here I execute the method, and I would expect to get Future<Option<User>> back, but I only get back null.
    final facade = MockIAuthFacade();

    Option<User> tStubbedResult = await facade.getSignedInUser();

    print(tDirectResult);
    print(tStubbedResult);
  });

  // Here I do the same, but I execute the authCheckRequested method of the AuthBloc, which executes the
  // getSignedInUser method. Also here I get back null as result.
  blocTest('Should return valid option of user.', 
    build: () async {
      when(MockIAuthFacade()
        .getSignedInUser()
      ).thenAnswer((_) async => Future.value(optionOf<User>(tValidUser)));

      return AuthBloc(MockIAuthFacade());
    },
    act: (bloc) async {
      bloc.add(AuthEvent.authCheckRequested());
    },
    expect: [
    ]
  );
}

标签: flutterflutter-test

解决方案


推荐阅读