ARTS-S golang单元测试

golang单元测试
在$GOPATH的src目录下建目录demo_unittest
在目录demo_unittest下建文件calc.go,内容如下:

package demo_unittest

func Add(a, b int) int {
    return a + b
}

func Sub(a, b int) int {
    return a - b
}

func Mul(a, b int) int {
    return a * b
}

func Div(a, b int) int {
    return a / b
}

在目录demo_unittest下建文件tests/calc_test.go内容如下

package tests

import (
    "demo_unittest"
    "testing"
)

func TestAdd(t *testing.T) {
    result := demo_unittest.Add(1, 2)
    if result != 3 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, 3)
    }
}

func TestSub(t *testing.T) {
    result := demo_unittest.Sub(1, 2)
    if result != -1 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, -1)
    }
}

func TestMul(t *testing.T) {
    result := demo_unittest.Mul(1, 2)
    if result != 2 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, 2)
    }
}

func TestDiv(t *testing.T) {
    result := demo_unittest.Div(4, 2)
    if result != 2 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, 2)
    }
}

在目录demo_unittest/tests下建文件calc1_test.go内容如下

package tests

import (
    "demo_unittest"
    "testing"
)

func TestAdd1(t *testing.T) {
    result := demo_unittest.Add(1, 2)
    if result != 3 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, 3)
    }
}

func TestSub1(t *testing.T) {
    result := demo_unittest.Sub(1, 2)
    if result != -1 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, -1)
    }
}

func TestMul1(t *testing.T) {
    result := demo_unittest.Mul(1, 2)
    if result != 2 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, 2)
    }
}

func TestDiv1(t *testing.T) {
    result := demo_unittest.Div(4, 2)
    if result != 2 {
        t.Errorf("TextUrl was incorrect, got: %d, want: %d.", result, 2)
    }
}

在tests目录下执行如下命令,运行单元测试

go test -v

如果只想运行某一个单元测试函数,运行如下命令

go test -v -run TestMul1 demo_unittest/tests

猜你喜欢

转载自www.cnblogs.com/zhouyang209117/p/10242329.html