Open In App

Overview of testing package in Golang

Improve
Improve
Like Article
Like
Save
Share
Report

In the software industry, there are clear differences between manual testing and automated testing. Where manual testing is used to ensure that the software code performs as expected and it requires time and effort. Most of the manual testing includes checking log files, external services, and the database for errors. In a dissimilar fashion, Automated testing is, well, automated where certain software/code perform the testing as the user would do. Because automated testing is done using an automation tool, exploration tests take less time and more test scripts, while increasing the overall scope of the tests.

In Golang, package testing is responsible for different types of testing maybe it is performance testing, parallel testing, functional testing, or any possible combination of these all.

The testing package provides support for automated testing of the Golang code. To run any test function use “go test” command, which automates the execution of any function of the form  TestXxx(*testing.T), where Xxx must not start with any lowercase letter.

Test Function Syntax :

func TestXxx(*testing.T)

Steps for writing test suite in Golang:

  • Create a file whose name ends with _test.go
  • Import package testing by import “testing” command
  • Write the test function of form func TestXxx(*testing.T) which uses any of Error, Fail, or related methods to signal failure.
  • Put the file in any package.
  • Run command go test

Note: test file will be excluded in package build and will only get executed on go test command.

Example:

File: main.go 

Go




package main
 
// function which return "geeks"
func ReturnGeeks() string{
    return "geeks";
}
 
// main function of package
func main() {
    ReturnGeeks()
}


 
 

Test file: pkg_test.go

 

Go




package main
 
import (
    "testing"
)
 
// test function
func TestReturnGeeks(t *testing.T) {
    actualString := ReturnGeeks()
    expectedString := "geeks"
    if actualString != expectedString{
        t.Errorf("Expected String(%s) is not same as"+
         " actual string (%s)", expectedString,actualString)
    }
}


Output:

Screen after running test case



Last Updated : 18 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads