golang 示例测试example_Golang基础入门11 | Testing

本文介绍了软件测试的重要性,特别是在Go语言中的测试方法。通过创建_test.go文件并定义Test函数进行测试,同时展示了如何自定义测试用例。此外,还探讨了Go中的基准测试,用于衡量代码性能,并给出基准测试示例。最后,提到了Go单元测试的官方文档资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

a5ef3fc3430f38e1e8b204fd7d2eaa85.png

软件测试

编写软件,在发布软件之前或之后都可能发现错误。 软件中发生的错误可能是错误,漏洞和其他类似的东西。 可以通过测试软件本身来发现软件中的许多潜在错误。 软件测试不仅要确保软件的正确性,而且还要确保软件符合用户的要求。

Go中的测试

在Go中测试软件可以通过创建扩展名为_test.go的文件来完成。 该文件必须与需要测试的对象位于同一程序包中。 要在测试文件中创建测试,请使用Test ..(t * testing.T)创建一个函数。 要运行测试,请使用go test命令。

// main.go
package main

import "fmt"

func main() {
    fmt.Println("The result of 12 + 14 = ", sum(12, 14))
}

//create a sum function
func sum(x, y int) int {
    return x + y
}

// main_test.go
package main

import "testing"
//create a test
func TestSum(t *testing.T) {
    result := sum(12, 14) //get the result
    expected := 26
    if result != expected {
        t.Error("Expected", expected, "Got", result)
    }
}

// output (go test)
// PASS
// ok      review-again/uji        4.023s

下面是个测试失败的例子

// main_test.go
package main

import "testing"

func TestSum(t *testing.T) {
    result := sum(12, 14)
    expected := 36 //change the expected value
    if result != expected {
        t.Error("Expected", expected, "Got", result)
    }
}

// output (go test)
// --- FAIL: TestSum (0.00s)
//     main_test.go:9: Expected 36 Got 26
// FAIL
// exit status 1
// FAIL    review-again/uji        4.670s

可以通过创建包含测试用例和预期结果的自定义struct来自定义测试。

package main

import "testing"

func TestSum(t *testing.T) {
    //create a custom struct
    type testSample struct {
        data1  int
        data2  int
        answer int
    }

    //create a testcases that consist of testSamples
    testCases := []testSample{
        testSample{12, 14, 26},
        testSample{5, 5, 10},
        testSample{45, 45, 90},
    }

    //run a test for each test case
    for _, v := range testCases {
        result := sum(v.data1, v.data2)
        if result != v.answer {
            t.Error("Expected: ", v.answer, "Got: ", result)
        }
    }
}

// output (go test)
// PASS
// ok      review-again/uji        4.055s

Benchmarking in Go

基准测试基本上是衡量软件的性能,以确保可以有效地使用软件。 Go中的基准测试可以通过使用Benchmark ...(b * testing.B)创建一个函数来完成。

这是Go中基准测试的示例,在这种情况下,SquareRoot()和AnotherSquareRoot()函数用于基准测试示例。

// main.go
package simplesqrt

import "math"

//SquareRoot returns square root of number
func SquareRoot(f float64) float64 {
    return math.Pow(f, 0.5)
}

//AnotherSquareRoot return square root of number using math.Sqrt()
func AnotherSquareRoot(f float64) float64 {
    return math.Sqrt(f)
}

// main_test.go
package simplesqrt

import (
    "fmt"
    "testing"
)

//The usage of SquareRoot Function
func ExampleSquareRoot() {
    fmt.Println("The result of square root of 16 = ", SquareRoot(16))
    //Output: The result of square root of 16 =  4
}

//Benchmark for SquareRoot() function
func BenchmarkSquareRoot(b *testing.B) {
    for i := 0; i < b.N; i++ {
        SquareRoot(16)
    }
}

//Benchmark for AnotherSquareRoot() function
func BenchmarkAnotherSquareRoot(b *testing.B) {
    for i := 0; i < b.N; i++ {
        AnotherSquareRoot(16)
    }
}

// output (go test -bench .)
// goos: windows
// goarch: amd64
// pkg: review-again/simplesqrt
// BenchmarkSquareRoot-4           200000000                7.63 ns/op
// BenchmarkAnotherSquareRoot-4    2000000000               0.44 ns/op
// PASS
// mok      review-again/simplesqrt 9.401s

根据输出,有两个基准结果:

  • BenchmarkSquareRoot-4已完成2亿次操作,每次操作的速度为7.63纳秒
  • BenchmarkAnotherSquareRoot-4已完成20亿次操作,每次操作的速度为0.44纳秒

资料来源

  • Go单元测试文档

这是golang基本教程系列的最后一部分,我希望本文对帮助学习Go编程语言有所帮助。 如果您有任何想法或反馈,可以在下面的评论留言。

关注公众号【技术全沾】学习更多有趣的编程知识。

Golang基础入门系列:

  1. 简介
  2. 常量
  3. 条件选择
  4. 循环
  5. Array,Slice 和 Map
  6. Function
  7. Struct 和 Interface
  8. 错误处理
  9. 协程
  10. Channel
  11. Testing
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值