Dart – Unit Testing
Unit Testing is a process of testing individual components of a software/application separately, to ensure that each component is functioning as intended.
It provides multiple advantages such as –
- Ability to test out individual components without running the whole software/application.
- Pinpoint errors easily inside a specific component.
Dart provides a package called test which lets the developer carry out unit testing very easily. In this article, we’ll write a few unit tests using this package, demonstrating various use cases and results.
Setting up the Project:
Since we’re using test, which is an external dart package, a separate project has to be created to run the project.
We’ve to create a pubspec.yaml file, and add the following lines to the project.
name: DartTesting dev_dependencies: test:
Then we’ve to run the following command
dart pub get
This will initialize a project with the name DartTesting and also install the test package as a dev dependency
Next, we can create a main.dart file which will contain all our code and import the test package there.
import 'package:test/test.dart';
Writing a Sample Function:
First, we’ve to write a simple function on which we can run our tests. Provided below is the code for calculating the sum of all the elements of an array.
Dart
// Get sum of all elements of an array int getSumOfArray(List< int > arr) { int res = 0; for (var i=0; i<arr.length; i++) { res += arr[i]; } return res; } |
Writing a Unit Test:
A unit test can be written for the above function by using the test() function. It takes in 2 Arguments
- A string value containing a description of the unit test
- A test assertion by using the expect() function. The expect() function has to be provided with 2 values:
- Expected Value, which is provided manually by the developer.
- Actual Value, which is obtained by running the concerned function
- If these values match, then the Unit Test is successful, or else it is considered to be failing.
Provided below is the code for a unit test for getSumOfArray() function. Since the expected and actual values match, it’ll be a successful test.
Dart
main() { // Successful test for sum of array test( 'Get sum of array - success' , () { int expectedValue = 15; int actualValue = getSumOfArray([1, 2, 3, 4, 5]); expect(expectedValue, actualValue); }); } |
Output
00:00 +0: Get sum of array - success 00:00 +1: All tests passed! Exited
Handling Failing Tests:
In this case, the expected value is different from the actual value, due to which the test will fail.
Dart
main() { // Unsuccessful test for sum of array test( 'Get sum of array - failure' , () { int expectedValue = 40; int actualValue = getSumOfArray([1, 2, 3, 4, 5]); expect(expectedValue, actualValue); }); } |
Output
00:00 +0: Get sum of array - failure 00:00 +0 -1: Get sum of array - failure [E] Expected: <15> Actual: <40>