Overview of Testing Package in Golang


In this golang article, we will learn the overview testing package using two test functions as well as using iteration.

Testing is of two types: manual testing and automated testing, manual testing is done manually with defined set of test cases whereas in automated testing a program is created with code to test the software. Here we will use two test function as well as iteration method to show the importance of testing package.

Algorithm

  • Step 1 −Import the required packages in the program

  • Step 2 − Create a test function in which the function will be called which is to be tested

  • Step 3 − Check and analyze the function using test cases, use go test command to know about error, it will return Pass if no error is obtained

Example 1

In this Example, two test functions are created to know the error in the function being checked. The result of the function will be recorded in short variable and then matched with correct output.

package mypackage

import "testing"

func Test_function(t *testing.T) {
	
   result := first_function()
   if result != "Hello, alexa!" {
      t.Errorf("Expected 'Hello, alexa!' but got '%s'", result)
   }
}

func Test_another_function(t *testing.T) {
	
   result := Another_function()

   
   if result != 64 {
      t.Errorf("Expected 64 but got %d", result)
   }
}

Output

Pass

Example 2

In this Example, a test function will be created in which some test cases will be created. Then, the test cases will be iterated and tested on the function one calls.

package mypackage

import (
   "math"
   "testing"
)

func Test_calculate_squareRoot(t *testing.T) {
	
   test_cases := []struct {
      input    float64
      expected float64
   }{
      {4, 2},
      {9, 3},
      {16, 4},
      {25, 5},
      {36, 6},
   }

   for _, testCase := range test_cases {
	
      result := CalculateSquareRoot(testCase.input)

		
      if math.Abs(result-testCase.expected) > 0.001 {
         t.Errorf("Expected %f but got %f", testCase.expected, result)
      }
   }
}

Output

Pass

Conclusion

We executed and concluded the program of seeing the implementation process of testing package. In the first Example, we created two test functions and in each test function we checked the output of the functions with the exact output. In the second Example, we created a test case struct and iterated over it to check the error.

Updated on: 03-May-2023

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements