UnitTest Flutter

Hi, I am Cam.
Now we’re starting with unit testing in Flutter. This is what I understand about it, and I’d love to hear your feedback.
Add the test dependency
The
test
package provides the core functionality for writing tests in Dart. This is the best approach when writing packages consumed by web, server, and Flutter apps.Mocks are alternativer implements of real class. Ofen use library Mockito . They allow you to simulate diffirent behaviors and test to success and failure case without depending on actual external servirce such as APIs or database
"
build_runner
is an automation tool for generating code in Dart/Flutter. It is not a runtime library and is only used during development."
Now, open teminal and input:
flutter pub add dev:test
flutter pub add mockito
flutter pub add --dev build_runner
Create file test
- This folder will contain the files that we will test.
This folder will contain the files to test files in above folder.
In this structure, i aim make the base test setup for the project clearer. You only to forcus on once thing: This folder contains all test handling files for project. :)
Create a class to test.
Note: In this project, I am trying to use Clean Architecture.
Yeah! I will start by creating a screen with 2 components:
Handle logic: home_controller.dart
Handle UI: home_screen.dart
Write for class test.
This code tests the logic of the setPrompt function.
I use the group function to test alternative cases of the setPrompt function.
Result
Use Mockito to test
Here, we use Mockito to test the ApiClient in the app.
sentMultipartRequest in the ApiClient class
Import and use the mock emulator in home_controller_test.dart
Next, I ofen terminal and run:
flutter pub run build_runner build
This code helps me create the mock fileWrite test code for senMultipartRequest functions
Result
I look forward to receiving your comments to further strengthen my knowledge. Thank you!
Subscribe to my newsletter
Read articles from Hằng Nguyễn Thu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
