Skip to content

Instantly share code, notes, and snippets.

@heyhey1028
Last active October 6, 2022 13:33
Show Gist options
  • Save heyhey1028/7fee74881fedac42930245e72ba8e66e to your computer and use it in GitHub Desktop.
Save heyhey1028/7fee74881fedac42930245e72ba8e66e to your computer and use it in GitHub Desktop.
Riverpodを使った単体テスト
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
// FirebaseAuthインスタンスのプロバイダ
final authProvider = Provider((ref) => FirebaseAuth.instance);
// AuthRepositoryのプロバイダ
final authRepositoryProvider =
Provider<AuthRepository>((ref) => AuthRepository(ref.read));
class AuthRepository {
// コンストラクタでReaderを受け取る
AuthRepository(this._read);
final Reader _read;
// Readerを使った処理
Stream<User?> get authStateChanges => _read(authProvider).authStateChanges();
}
void main() {
// AuthRepositoryで使うauthProviderの値をMockFirebaseAuthで上書き
final container = ProviderContainer(
overrides: [
authProvider.overrideWithValue(
MockFirebaseAuth(),
),
],
);
// MockFirebaseAuthで上書きされたauthProviderを含むReaderをコンストラクタに渡す
final authRepo = AuthRepository(container.read);
}
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:mocktail/mocktail.dart';
class MockUser extends Mock implements User {}
final MockUser mockUser = MockUser();
class MockFirebaseAuth extends Mock implements FirebaseAuth {
@override
Stream<User> authStateChanges() {
return Stream.fromIterable(
[mockUser],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment