Created
June 7, 2025 06:35
-
-
Save rubywai/1d5e118ab415d29de81639a762116225 to your computer and use it in GitHub Desktop.
This file contains hidden or 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:flutter_bloc_weather/features/search/bloc/city_search_cubit.dart'; | |
| import 'package:flutter_bloc_weather/features/search/bloc/city_search_state.dart'; | |
| import 'package:flutter_bloc_weather/features/search/data/model/city_model.dart'; | |
| import 'package:flutter_test/flutter_test.dart'; | |
| import 'package:bloc_test/bloc_test.dart'; | |
| import 'package:get_it/get_it.dart'; | |
| import 'package:mockito/mockito.dart'; | |
| import 'package:flutter_bloc_weather/features/search/data/services/search_api_services.dart'; | |
| import 'api_mock.mocks.dart'; | |
| void main() { | |
| final sl = GetIt.instance; | |
| late MockSearchApiServices mockService; | |
| setUp(() { | |
| mockService = MockSearchApiServices(); | |
| // Register or replace the singleton in GetIt | |
| if (sl.isRegistered<SearchApiServices>()) { | |
| sl.unregister<SearchApiServices>(); | |
| } | |
| sl.registerSingleton<SearchApiServices>(mockService); | |
| }); | |
| tearDown(() { | |
| sl.reset(); // Clean up GetIt after each test | |
| }); | |
| final sampleCityModel = CityModel(results: [ | |
| CitySearchModel( | |
| id: 1, | |
| name: 'Yangon', | |
| latitude: 16.8, | |
| longitude: 96.2, | |
| country: 'Myanmar', | |
| ), | |
| ]); | |
| group('CitySearchCubit (with GetIt)', () { | |
| blocTest<CitySearchCubit, CitySearchState>( | |
| 'emits [Loading, Success] when API call succeeds', | |
| build: () { | |
| when(mockService.searchCities(name: "Yangon", count: 15)) | |
| .thenAnswer((_) async => sampleCityModel); | |
| return CitySearchCubit(); | |
| }, | |
| act: (cubit) => cubit.searchCity(name: "Yangon"), | |
| expect: () => [ | |
| isA<CitySearchLoading>(), | |
| isA<CitySearchSuccess>().having( | |
| (s) => s.cityModel.results.first.name, 'first city name', 'Yangon'), | |
| ], | |
| ); | |
| blocTest<CitySearchCubit, CitySearchState>( | |
| 'emits [Loading, Failed] when API throws error', | |
| build: () { | |
| when(mockService.searchCities(name: "Fail", count: 15)) | |
| .thenThrow(Exception("API failed")); | |
| return CitySearchCubit(); | |
| }, | |
| act: (cubit) => cubit.searchCity(name: "Fail"), | |
| expect: () => [ | |
| isA<CitySearchLoading>(), | |
| isA<CitySearchFailed>() | |
| .having((f) => f.errorMessage, 'errorMessage', contains("Error")), | |
| ], | |
| ); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment