首页 > 其他分享 >0141-Go-单元测试

0141-Go-单元测试

时间:2023-01-30 19:12:29浏览次数:61  
标签:func tt testing 单元测试 IntMin 0141 want ans Go

环境

  • Time 2022-08-25
  • Go 1.19

前言

说明

参考:https://gobyexample.com/testing-and-benchmarking

目标

使用 Go 语言进行测试。

示例

package main

import (
    "fmt"
    "testing"
)

func IntMin(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func TestIntMinBasic(t *testing.T) {
    ans := IntMin(2, -2)
    if ans != -2 {

        t.Errorf("IntMin(2, -2) = %d; want -2", ans)
    }
}

func TestIntMinTableDriven(t *testing.T) {
    var tests = []struct {
        a, b int
        want int
    }{
        {0, 1, 0},
        {1, 0, 0},
        {2, -2, -2},
        {0, -1, -1},
        {-1, 0, -1},
    }

    for _, tt := range tests {

        testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
        t.Run(testname, func(t *testing.T) {
            ans := IntMin(tt.a, tt.b)
            if ans != tt.want {
                t.Errorf("got %d, want %d", ans, tt.want)
            }
        })
    }
}

func BenchmarkIntMin(b *testing.B) {

    for i := 0; i < b.N; i++ {
        IntMin(1, 2)
    }
}

总结

使用 Go 语言进行单元测试。

附录

标签:func,tt,testing,单元测试,IntMin,0141,want,ans,Go
From: https://www.cnblogs.com/jiangbo4444/p/17077021.html

相关文章

  • 0142-Go-命令行参数
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/command-line-arguments目标使用Go语言的命令行参数。示例packagemainimport("fm......
  • 0143-Go-命令行标记
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/command-line-flags目标使用Go语言的命令行标记。示例packagemainimport("flag"......
  • 0144-Go-命令行子命令
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/command-line-subcommands目标使用Go语言的命令行子命令。示例packagemainimport(......
  • 0134-Go-读取文件
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/reading-files目标使用Go语言读取文件。示例packagemainimport("bufio""fmt......
  • 0135-Go-写入文件
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/writing-files目标使用Go语言写入文件。示例packagemainimport("bufio""fmt......
  • 0136-Go-行过滤器
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/line-filters目标使用Go语言行过滤器。示例packagemainimport("bufio""fmt"......
  • 0137-Go-文件路径
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/file-paths目标使用Go语言处理文件路径。示例packagemainimport("fmt""path......
  • Django django-rest-framework-simplejwt
    Django(75)django-rest-framework-simplejwt「建议收藏」发布于2022-09-1611:56:13阅读 2440 大家好,又见面了,我是你们的朋友全栈君。 前言由于之前我们一......
  • mongodb的安装与部署
    简介MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的......
  • Django-rest-framework框架/1-drf-drf入门规范
    一、Web应用模式在开发Web应用中,有两种应用模式:1.1前后端不分离之前学的,写的bbs项目,图书管理系统,用的是前后端混合开发。-后端人员,写后端,也要写【模板语法】--->xx.h......