Last active
October 6, 2022 13:33
-
-
Save heyhey1028/7fee74881fedac42930245e72ba8e66e to your computer and use it in GitHub Desktop.
Riverpodを使った単体テスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
// AuthRepositoryで使うauthProviderの値をMockFirebaseAuthで上書き | |
final container = ProviderContainer( | |
overrides: [ | |
authProvider.overrideWithValue( | |
MockFirebaseAuth(), | |
), | |
], | |
); | |
// MockFirebaseAuthで上書きされたauthProviderを含むReaderをコンストラクタに渡す | |
final authRepo = AuthRepository(container.read); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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