Unit Testing is a process where we can ensure the features and functionality work perfectly. Testing is handy for verifying the behavior of a single function, method, or class. For writing the unit test case Flutter provides a core Framework which called the Test package and if you want to add UI/Widget testing then you can use the flutter_test package.
Let’s Start the Implementation part.
1. Add the test or flutter_test dependency.
The test package provides the core functionality for writing tests in Dart
1 2 |
dev_dependencies: test: |
2. Create a test file.
To create a test file we have to flow some instructions.
- Test files should always end with _test.dart
- Test files should reside inside a test folder located at the root of your Flutter application or package
1 2 3 4 5 |
numTest_app/ lib/ num.dart test/ num_test.dart |
3. Create a class to test
Here i am implementing code that validates 10 digit mobile.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class num { bool validateMobile(String value) { String patttern = r'(^(?:[+0]9)?[0-9]{10,12}$)'; RegExp regExp = new RegExp(patttern); if (value.length == 0) { return false; } else if (!regExp.hasMatch(value)) { return false; } return true; } } |
4. Write a test for our class
Inside the num_test.dart file writes the test code.
1 2 3 4 5 6 7 8 9 |
void main() { test('Mobile no test', () { final counter = num(); expect(counter.validateMobile(''), false); expect(counter.validateMobile('123'), false); expect(counter.validateMobile('test'), false); expect(counter.validateMobile('1234567890'), true); }); } |
6. Run the tests
Now run the num_test.dart class.
In conclusion, I hope this code will help you better to understand Unit Testing in the flutter. If you feel any doubt or query please comment below.
Thanks for the read this blog and if you want to visit my other blog click here.