Home  >  Article  >  Backend Development  >  Unit Test At Go

Unit Test At Go

王林
王林Original
2024-07-30 16:56:50857browse

Unit Test At Go

Go provides a testing package, containing many tools for unit testing purposes.

Preparation
Let's just practice, first prepare a Cube struct, the resulting object variable of the struct will later be used as testing material.

package main

import "math"

type Cube struct {
 Sisi float64
}
func (k Cube) Volume() float64 {
 return math.Pow(k.Sisi, 3)
}
func (k Cube) Area() float64 {
 return math.Pow(k.Sisi, 2) * 6
}
func (k Cube) circumference() float64 {
 return k.Sisi * 12
}

Save the code above in the training1.go file

package main
import "testing"
var (
cube Cube = Cube{4}
volume Should float64 = 64
area Should float64 = 96
circumference Should float64 = 48
)
func TestCalculateVolume(t *testing.T) {
t.Logf("Volume : %.2f", cube.Volume())
if cube.Volume() != volumeShould {
t.Errorf("WRONG! should be %.2f", volumeShould)
}
}
func TestCalculateSurface(t *testing.T) {
t.Logf("Area : %.2f", cube.Area())
if cube.Area() != areaShould {
t.Errorf("WRONG! should be %.2f", areaShould)
}
}
func TestCalculatePerimeter(t *testing.T) {
t.Logf("Perimeter : %.2f", cube.Perimeter())
if cube.Perimeter() != circumferenceShould {
t.Errorf("WRONG! should be %.2f", circumferenceShould)
}
}

The t.Logf() method is used to display a log. This method is equivalent to fmt.Printf() .
The Errorf() method is used to display a log followed by a statement that a fail occurred during testing.
The way to execute testing is to use the go test command. Because the struct being tested is in the bab55.go file, when executing the test using go test, the bab55_test.go and bab55.go file names need to be written as arguments. The -v or verbose argument is used to display all log output during testing.
Run the application as shown in the image below, it can be seen that no tests have failed. OK, then try changing the calculation formula for the Keliling() method. The purpose of this change is to find out how the fail marker appears when a test fails.

func (k Cube) Perimeter() float64 {
return k.Side * 15
}

After that run the test again.

The above is the detailed content of Unit Test At Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn