Testing with Fakes
Most unit tests should use fakes instead of making network requests to Google services.
- Code that uses
CacheServicecan be tested by injecting the fakeFakeCacheService. - Code that uses
DiscussServicecan be tested by injecting the fakeFakeDiscussService. - Code that uses
FileServicecan be tested by injecting the fakeFakeFileService. - Code that uses
GenerativeServicecan be tested by injecting the fakeFakeGenerativeService. - Code that uses
ModelServicecan be tested by injecting the fakeFakeModelService. - Code that uses
PermissionServicecan be tested by injecting the fakeFakePermissionService. - Code that uses
PredictionServicecan be tested by injecting the fakeFakePredictionService. - Code that uses
RetrieverServicecan be tested by injecting the fakeFakeRetrieverService. - Code that uses
TextServicecan be tested by injecting the fakeFakeTextService.
Import the fakes from the testing library:
import 'package:google_cloud_ai_generativelanguage_v1beta/testing.dart';
Option A: Using Constructor Closures (Recommended)
You can inject behavior by passing optional function callbacks to the fake's
constructor. Methods that are not provided will throw an UnsupportedError.
import 'package:google_cloud_ai_generativelanguage_v1beta/generativelanguage.dart';
import 'package:google_cloud_ai_generativelanguage_v1beta/testing.dart';
final fake = FakeFileService(
createFile: (request) async {
// Assert request contents here if needed.
return CreateFileResponse();
},
);
Option B: Subclassing the Fake
For more complex test setups or shared states, you can subclass the fake and
override its methods. Methods that are not overridden will throw an
UnsupportedError.
import 'package:google_cloud_ai_generativelanguage_v1beta/generativelanguage.dart';
import 'package:google_cloud_ai_generativelanguage_v1beta/testing.dart';
final class MyFakeFileService extends FakeFileService {
@override
Future<CreateFileResponse> createFile(
CreateFileRequest request,
) async {
// Assert request contents here if needed.
return CreateFileResponse();
}
}
A Simple Test
import 'package:google_cloud_ai_generativelanguage_v1beta/generativelanguage.dart';
import 'package:google_cloud_ai_generativelanguage_v1beta/testing.dart';
import 'package:test/test.dart';
Future<void> functionUnderTest(FileService service) async {
// Application logic here.
await service.createFile(CreateFileRequest());
// More application logic here.
}
void main() {
test('test', () async {
final fake = FakeFileService(
createFile: (request) async {
// Assert request contents here.
return CreateFileResponse();
},
);
// Instead of verifying that `functionUnderTest` completes, you should verify
// the relevant properties of the result.
await expectLater(functionUnderTest(fake), completes);
});
}