Dart Unit Testing

 

What is Unit Testing?

Unit testing is a part of the software development process where particular unit/components of an application are tested. Unit testing of each component is necessary to enhance the application performance. We can say that a unit is the smallest testable chunk of a program that can be logically isolated in a system. In various programming languages, the individual program, a subroutine, a function, a method, or a class can be represented as a Unit. There can be many individual units within the module. In object-oriented programming, the method that belongs to base class/superclass, an abstract class can be represented as smaller units. Below image displays the type of testing.

Dart Unit Testing

Unit Testing Task

The unit testing task is given below.

  • Unit Test Plan
    Prepare
    Review
    Rework
    Baseline
  • Unit Test Cases/Scripts
    Prepare
    Review
    Rework
    Baseline
  • Unit Test
    Perform

Advantage of Unit Testing

Few advantages of unit testing are given below.

  1. We can maintain code easily
  2. It makes code more reusable.
  3. It makes development faster.
  4. The code can be easily debugged.
  5. It detects the cost of testing and fixing defects, because any error is captured in the early stage.

Dart Unit Testing

In Dart, we required to include an external library named "test", which facilitates a standard way of writing and running individual unit test. Unit testing can be achieved using the following steps.

Step - 1: Installing "test" package

To include the unit testing in our project, we must install a third-party packages "test" in our current working project. Let's open the pubspec.yaml in the our project and type the following statement.

  1. dependencies:  
  2. test:  

Now, right-click on pubspec.yaml file and click on Pub: get dependencies. This will install the "test" package in our project.

Dart Unit Testing

We can also install it by using the following command.

  1. pub get  

Step - 2: Importing "test" package

Type the following line to import the "test" package in your project.

  1. import "package:test/test.dart";  

Step - 3: Writing Test Cases

The top-level test() function is added by the Test cases. In the test() function, we make the test assertion using the expect() function. The expert() function takes two arguments actualValue and MatchValue.

Syntax:

  1. test("Test Description", () {  
  2.    expert(actualValue, matchingValue)  
  3. });  

Group of Test Cases

We can create a group of multiple test cases using the group() function. It helps grouping of test cases based on some criteria. The description of each group is specified in the beginning of its test's description.

Syntax:

The syntax is given below.

  1. group("Test_Group_Name", () {   
  2.    test("test_case_name_1", () {   
  3.       expect(actual, equals(exptected));   
  4.    });    
  5.    test("test_case_name_2", () {   
  6.       expect(actual, equals(expected));   
  7.    });   
  8. })   

Example - 1(Passing Test)

Here is the example where we define an add() method for unit test. It accepts two parameters as an integer values and returns an integer representing the sum. To test the add() method, understand the following example -

Step - 1: We import the test package.

Step -2: We define the test using the test() function and it uses the expert() function to impose an assertion.

  1. import 'package:test/test.dart';        
  2. // Importing  the test package   
  3.   
  4. int add(int x,int y)                    
  5. // this function to be tested {   
  6.    return x+y;   
  7. }    
  8. void main() {   
  9.    // Defining the test function   
  10.    test("test to check add method",(){    
  11.       // Arrange   
  12.       var expected = 30;   
  13.         
  14.       // Act   
  15.       var actual = add(10,20);   
  16.         
  17.       // Asset   
  18.       expect(actual,expected);   
  19.    });   
  20. }  

Output:

00:00 +0: test to check add method 
00:00 +1: All tests passed! 

Example - 2 A unsuccessful Test

We define the sub() method which has a logical mistake. Let's have a following example.

  1. import 'package:test/test.dart';   
  2. int add(int x,int y){   
  3.    return x+y;   
  4. }  
  5. int sub(int x,int y){   
  6.    return x-y-1;   
  7. }    
  8. void main(){   
  9.    test('test to check sub',(){   
  10.       var expected = 10;     
  11.       // Arrange   
  12.         
  13.       var actual = sub(30,20);    
  14.       // Act   
  15.         
  16.       expect(actual,expected);    
  17.       // Assert   
  18.    });   
  19.    test("test to check add method",(){   
  20.       var expected = 30;     
  21.       // Arrange   
  22.         
  23.       var actual = add(10,20);    
  24.       // Act   
  25.         
  26.       expect(actual,expected);    
  27.       // Asset   
  28.    });   
  29. }  

Output:

00:00 +0: test to check sub 
00:00 +0 -1: test to check sub 
Expected: <10> 
Actual: <9> 
package:test  expect 
bin\Test123.dart 18:5  main.<fn> 
   
00:00 +0 -1: test to check add method 
00:00 +1 -1: Some tests failed.  
Unhandled exception: 
Dummy exception to set exit code. 
#0  _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:938) 
#1  _microtaskLoop (dart:async/schedule_microtask.dart:41)
#2  _startMicrotaskLoop (dart:async/schedule_microtask.dart:50) 
#3  _Timer._runTimers (dart:isolate-patch/timer_impl.dart:394) 
#4  _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:414) 
#5  _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) 

In the above example, the add() function is tested successfully but the sub() function failed the unit test due to logical error.

Grouping Test Cases

We can write the multiple test cases in the form of group. The group() is used to grouped together these methods. It helps to write much cleaner code.

In the following example, we are writing a test case for the split() function and the trim() function. We grouped together these function and name it String.

Let's understand the following example -

Example -

  1. import "package:test/test.dart";   
  2. void main() {   
  3.   
  4.    group("String", () {   
  5.      // First test case  
  6.       test("testing on split() method of string class", () {   
  7.          var string = "Hii,Hello,Hey";   
  8.          expect(string.split(","), equals(["Hii""Hello""Hey"]));   
  9.       });   
  10.       // Second test case  
  11.       test("testing on trim() method of string class", () {   
  12.          var string = "  Hii ";   
  13.          expect(string.trim(), equals("Hii"));   
  14.       });   
  15.    });   
  16. }  

Output:

00:00 +0: String testing on split() method of string class 
00:00 +1: String testing on trim() method of string class 
00:00 +2: All tests passed

Comments