Loading...
Loading...
Define and generate mock objects for external dependencies using `package:mockito` and `build_runner`. Use when unit testing classes that depend on complex external services like APIs or databases.
npx skill4agent add dart-lang/skills dart-generate-test-mockshttp.ClientUriUri.parse(string)pubspec.yamlpackage:httpdart pub add httpdart pub add dev:test dev:mockito dev:build_runnerimport 'package:http/http.dart' as http;package:mockitobuild_runner@GenerateNiceMocks@GenerateMocksMockSpec<Type>().mocks.dartbuild_runnerdart run build_runner buildpackage:testwhen(mock.method()).thenReturn(value)thenAnswer((_) async => value)FutureStreamthenReturnverify(mock.method()).called(1)anyanyNamedcaptureAnyhttp.Clienttarget_test.dart@GenerateNiceMocks([MockSpec<Dependency>()])partimport.mocks.dartdart run build_runner buildgroup()test()when()verify()expect()dart testbuild_runnerdart testdart run build_runner build@GenerateNiceMocksArgumentErrorthenReturnthenAnswerbuild_runner.mocks.dartlib/api_service.dartimport 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final http.Client client;
ApiService(this.client);
Future<String> fetchData(String urlString) async {
final uri = Uri.parse(urlString);
final response = await client.get(uri);
if (response.statusCode == 200) {
return jsonDecode(response.body)['data'];
} else {
throw Exception('Failed to load data');
}
}
}test/api_service_test.dartimport 'package:test/test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:http/http.dart' as http;
import 'package:my_app/api_service.dart';
// Generate the mock class for http.Client
([MockSpec<http.Client>()])
import 'api_service_test.mocks.dart';
void main() {
group('ApiService', () {
late ApiService apiService;
late MockClient mockHttpClient;
setUp(() {
mockHttpClient = MockClient();
apiService = ApiService(mockHttpClient);
});
test('returns data if the http call completes successfully', () async {
// Arrange: Stub the async HTTP GET request using thenAnswer
when(mockHttpClient.get(any)).thenAnswer(
(_) async => http.Response('{"data": "Success"}', 200),
);
// Act
final result = await apiService.fetchData('https://api.example.com/data');
// Assert
expect(result, 'Success');
// Verify the mock was called with the correct Uri
verify(mockHttpClient.get(Uri.parse('https://api.example.com/data'))).called(1);
});
test('throws an exception if the http call completes with an error', () {
// Arrange
when(mockHttpClient.get(any)).thenAnswer(
(_) async => http.Response('Not Found', 404),
);
// Act & Assert
expect(
apiService.fetchData('https://api.example.com/data'),
throwsException,
);
});
});
}