Introduction
Testing each individual unit of an application is known as unit testing. It allows the developer to test small features without having to run the complete application.
Let us assume that you have a basic understanding of programming languages and are familiar with basic Dart Introduction. In this blog, we will be covering Dart Unit Testing and its implementation in our program.
So, let's start with the basics of Dart Unit Testing.
Unit Testing in Dart
Unit testing is the process of individually evaluating each component of a software/application to ensure that it functions as intended.
It has numerous advantages, including:
- Individual components can be tested without having to run the entire software/application.
- It's simple to pinpoint faults within a single component.
Before we deep dive into Dart Unit Testing, know that you can develop your Dart sample code on DartPad.
Dart has a package named test that makes unit testing relatively simple for developers. We'll construct a few unit tests with this package in this article, showcasing various use cases and outcomes.
Setting Up Project
Because we're using the test, which is an external dart package, we'll need to establish a new project to run the project.
Create a pubspec.yaml file and include the lines below in the project.
name: PerformDartTesting
dev_dependencies:
test:
Then we must run the command below.
dart pub get
This will create a PerformDartTesting project and install the test package as a development dependency. Then we can import the test package into a main.dart file that will include all of our code.
import 'package:test/test.dart';
Writing Sample Function
First, we must create a simple function that will be used to execute our tests. The code for calculating the sum of all the items of an array is provided below.
Code:
int getSumInArray(List<int> arr) { // to get the sum of all elements in array
int ans = 0;
for (var j=0; j<arr.length; j++) {
ans += arr[j];
}
return ans;
}