mockito 当实际的类具有静态依赖项时,我如何编写单元测试?

blmhpbnm  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(114)
import 'package:injectable/injectable.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:wefocus/core/services/env_service.dart';

@singleton
class SupabaseService {
  final EnvService _envService;
  SupabaseService(this._envService);

  Future<void> initialize() async {
    await Supabase.initialize(url: _envService.supabaseUrl, anonKey: _envService.supabaseAnonKey);
  }
}

字符串
这是我实际的dart类。我试图用mocktail写一个单元测试,但是我不能想象我应该模拟Supply-Code吗?如果是,我怎么做?Supabase.initialize是一个静态函数顺便说一句。你能帮我吗?谢谢

snvhrwxg

snvhrwxg1#

https://github.com/dart-lang/mockito/issues/214#issuecomment-523662502
我已经找到解决办法了。

import 'package:injectable/injectable.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:wefocus/core/services/env_service.dart';

@singleton
class SupabaseService {
  final SupabaseManager _supabaseManager;

  SupabaseService(this._supabaseManager);

  void initialize() {
    _supabaseManager.initialize();
  }
}

// coverage:ignore-start
class SupabaseManager {
  final EnvService _envService;

  SupabaseManager(this._envService);

  void initialize() {
    Supabase.initialize(url: _envService.supabaseUrl, anonKey: _envService.supabaseAnonKey);
  }
}
// coverage:ignore-end

字符串
测试文件:

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:wefocus/core/services/supabase_service.dart';

class MockSupabaseManager extends Mock implements SupabaseManager {}

void main() {
  setUpAll(() {
    TestWidgetsFlutterBinding.ensureInitialized();
  });

  group('SupabaseService', () {
    late SupabaseService supabaseService;
    late MockSupabaseManager mockSupabaseManager;

    setUp(() {
      mockSupabaseManager = MockSupabaseManager();
      supabaseService = SupabaseService(mockSupabaseManager);
    });

    test('initialize should call SupabaseManager.initialize', () async {
      // arrange
      when(mockSupabaseManager.initialize()).thenAnswer((_) async {});

      // act
      supabaseService.initialize();

      // assert
      verify(mockSupabaseManager.initialize()).called(1);
    });
  });
}

相关问题