Outline
In Flutter
, sometimes we use the build_runner
package to generate the code we need for development. In particular, when making a test code, we often use Mockito
to make a test Mock
.
- build_runner: https://pub.dev/packages/build_runner
- Mockito: https://pub.dev/packages/mockito
In this blog post, I will introduce how to use the build_runner
and Mockito
packages to make a Mock
file in the lib
folder.
Create Mock in the lib folder
Normally, we use the build_runner
and Mockito
packages to genrate the Mocke
for testing, so we can’t use them in the files in the lib
folder. However, when making a package for other users like me, we sometimes use Mock
in the files in the lib
folder as follows.
...
@GenerateMocks([
HttpClient,
HttpClientRequest,
HttpClientResponse,
HttpHeaders,
StreamSubscription,
])
R runWithNetworkImages<R>(R Function() body) {
return HttpOverrides.runZoned(
body,
createHttpClient: (_) => _createMockImageHttpClient(),
);
}
...
In this blog post, I will show you how to make a Mock
in the lib
folder like this.
build.yaml file
The build_runner
can be configured with the build.yaml
file. With this build.yaml
file, you can also make a Mock
in the files in the lib
folder.
So, to make a Mock
in the files in the lib
folder, create a build.yaml
file in the root directory of the project and modify it as follows.
targets:
$default:
builders:
mockito|mockBuilder:
generate_for:
- 'lib/src/run_with_network_images.dart'
As above, when you specify the file in the lib
folder for the target of the Mock
generated by Mockito
in the build.yaml
file, you can also make a Mock
in the files in the lib
folder.
Completed
Done! we’ve seen how to generate the Mock
file in the lib
folder by using the build_runner
and Mockito
packages. This is not often the case, but it is good to know that you can configure the build_runner
with the build.yaml
file.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.