如何用Flutter模拟Supabase进行单元测试?

afdcj2ne  于 2023-04-13  发布在  Flutter
关注(0)|答案(1)|浏览(96)

我尝试在Flutter中使用Supabase进行单元测试,如以下代码:

import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class TestMClass {
  SupabaseClient client;
  TestMClass({
    required this.client,
  });
  Future<AuthResponse> signinMc() async {
    final respnse = await client.auth
        .signInWithPassword(email: 'example@gmail', password: 'password');
    return respnse;
  }
}

class MockSupabaseClient extends Mock implements SupabaseClient {}

void main() async {
  
  final MockSupabaseClient mockClient = MockSupabaseClient();

  final TestMClass testMCass = TestMClass(client: mockClient);
  setUp(() {});
  group('TestAuthBloc', () {
    test('description', () async {
      final auth = await testMCass.signinMc();
      expect(auth, isA<AuthResponse>());
    });
  });
}

它抛出此错误:....
类型“Null”不是类型“GoTrueClient”的子类型
我如何用Flutter模拟或做Supabase函数的单元测试?

7kjnsjlb

7kjnsjlb1#

你可以像这样使用Fake类:

import 'package:flutter_test/flutter_test.dart';
import 'package:supabase/supabase.dart';

void main() {
  test('Fake Supabase', () async {
    final supabase = FakeSupabase();

    final response = await supabase.auth.signInWithPassword(
      email: 'test@gmail.com',
      password: 'passsword',
    );
    expect(response.session, isA<Session>());
  });
}

class FakeSupabase extends Fake implements SupabaseClient {
  @override
  get auth => FakeGotrue();
}

class FakeGotrue extends Fake implements GoTrueClient {
  final _user = User(
    id: 'id',
    appMetadata: {},
    userMetadata: {},
    aud: 'aud',
    createdAt: DateTime.now().toIso8601String(),
  );
  @override
  Future<AuthResponse> signInWithPassword(
      {String? email,
      String? phone,
      required String password,
      String? captchaToken}) async {
    return AuthResponse(
      session: Session(
        accessToken: '',
        tokenType: '',
        user: _user,
      ),
      user: _user,
    );
  }
}

相关问题