loading

Dart Unit Testing

Unit testing is a software development process step that involves testing specific application units or components. Every component must undergo unit testing in order to improve the application’s performance. The smallest testable section of a program that can be rationally isolated inside a system is referred to as a unit. A program, a subroutine, a function, a method, or a class can all be represented as a Unit in a variety of programming languages. The module may contain a large number of distinct units. Smaller units can be used to represent an abstract class’s method that belongs to its base class or superclass in object-oriented programming. The sort of testing is seen in the image below.
Dart Unit Testing -

Unit Testing Task

The task for unit testing is listed below.

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

Advantage of Unit Testing

Below are a few benefits of unit testing.

1.We can easily maintain code.
2.It increases code reusability.
3.Development is accelerated by it.
4.Debugging the code is a simple process.
5.Due to the early detection of errors, it can identify the cost of testing and defect repair.

Dart Unit Testing

It is necessary to include the external library “test” in Dart in order to write and execute individual unit tests in a standard manner. The following procedures can be used to accomplish unit testing.

Step – 1: Installing “test” package

We need to install a third-party package called “test” in our ongoing working project before we can incorporate unit testing into it. Now that the pubspec.yaml file is open in our project, type the following text.

				
					dependencies:  
test:  
				
			

Now select Pub: obtain dependencies by doing a right-click on the pubspec.yaml file. The “test” package will be installed in our project as a result.

Dart Unit Testing -

We can use the following command to install it as well.

				
					pub get  
				
			

Step – 2: Importing “test” package

To import the “test” package into your project, type the following line.

				
					import "package:test/test.dart";  
				
			

Step – 3: Writing Test Cases

The Test cases add the top-level method test(). We use the expect() method in the test() function to create the test assertion. ActualValue and MatchValue are the two arguments that the expert() function accepts.

Syntax

				
					test("Test Description", () {  
   expert(actualValue, matchingValue)  
});  
				
			

Group of Test Cases

With the group() function, we may put several test cases together into a group. It facilitates test case grouping according to certain standards. Each group’s description is given at the outset of the exam description.

Syntax

				
					group("Test_Group_Name", () {   
   test("test_case_name_1", () {   
      expect(actual, equals(exptected));   
   });    
   test("test_case_name_2", () {   
      expect(actual, equals(expected));   
   });   
})  
				
			

Example - Passing Test

This is an example of how to define a unit test add() method. It returns an integer that represents the total of the two integer parameters that it accepts. Learn how to use the add() method by understanding this example:

Step 1: The test package is imported.

Step 2: The test is defined using the test() method, and an assertion is imposed using the expert() function.

				
					import 'package:test/test.dart';        
// Importing  the test package   
  
int add(int x,int y)                    
// this function to be tested {   
   return x+y;   
}    
void main() {   
   // Defining the test function   
   test("test to check add method",(){    
      // Arrange   
      var expected = 30;   
        
      // Act   
      var actual = add(10,20);   
        
      // Asset   
      expect(actual,expected);   
   });   
}  
				
			

Output

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

Example - A unsuccessful Test

We define a logical error in the sub() method. Let’s look at the next illustration.

				
					import 'package:test/test.dart';   
int add(int x,int y){   
   return x+y;   
}  
int sub(int x,int y){   
   return x-y-1;   
}    
void main(){   
   test('test to check sub',(){   
      var expected = 10;     
      // Arrange   
        
      var actual = sub(30,20);    
      // Act   
        
      expect(actual,expected);    
      // Assert   
   });   
   test("test to check add method",(){   
      var expected = 30;     
      // Arrange   
        
      var actual = add(10,20);    
      // Act   
        
      expect(actual,expected);    
      // Asset   
   });   
}  
				
			

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)
				
			

The add() function in the example above passes the test, but the sub() function’s logical fault caused it to fail the unit test.

Grouping Test Cases

Multiple test cases can be written in a group format. These methods are grouped together using the group() function. Writing much cleaner code is helpful.

We are creating a test case for the divide() and trim() functions in the example that follows. These functions were combined and given the name String.

Example

				
					import "package:test/test.dart";   
void main() {   
  
   group("String", () {   
     // First test case  
      test("testing on split() method of string class", () {   
         var string = "Hii,Hello,Hey";   
         expect(string.split(","), equals(["Hii", "Hello", "Hey"]));   
      });   
      // Second test case  
      test("testing on trim() method of string class", () {   
         var string = "  Hii ";   
         expect(string.trim(), equals("Hii"));   
      });   
   });   
}
				
			

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
				
			
Share this Doc

Dart Unit Testing

Or copy link

Explore Topic