如何在不同的测试文件中分享项目

时间:2024-02-27

浏览:108

作者:佚名

有志者,事竟成!如果你在学习Golang,那么本文《如何在不同的测试文件中分享项目》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我想在许多不同的测试文件中共享项目,就像全局变量一样,但仅限于测试范围。

./1_test.go
./2_test.go
./3_test.go

// shared between these files
var item *test.global


正确答案


假设当前的包名称是 cpx,您可以对所有 3 个测试文件使用包名称 cpx_test。 go 允许同一目录中存在 1 个包(包含一个或多个文件)和 1 个测试包(包含一个或多个文件)。

cpx
├── cpx.go
├── cpx_1_test.go
├── cpx_2_test.go
└── cpx_3_test.go

通过使用此功能,您可以在 cpx_test 范围内声明仅限于 3 个测试文件的全局变量。您应该将测试中的原始包作为外部包导入。

import "gitlab.com/vaguecoder0to.n/project/cpx"

假设 cpx_1_test.go 中有以下代码段

var (
    complex1, complex2, complex3 *cpx.complex
)

func testadd(t *testing.t) {
    complex1 = &cpx.complex{
        real: 1,
        imag: 10,
    }

    complex2 = &cpx.complex{
        real: 2,
        imag: 9,
    }

    complex3 = cpx.complexadd(complex1, complex2)
}

这 3 个变量也可以被其他 2 个文件使用。但这里的限制是:

  1. 单独测试 cpx_2_test.go 和 cpx_3_test.go 文件可能会出现错误,因为变量的初始化是单独在 cpx_1_test.go 中完成的。
  2. 测试文件的执行顺序很重要。
go test cpx_1_test.go cpx_2_test.go cpx_3_test.go
  • 测试用例的顺序也很重要。测试 testadd 应在任何其他测试函数之前进行测试。
  • 或者,我在用例中使用子测试,这违背了您最初的想法,但如果单元测试是相关的,那就有意义了。即,有一些类似的分类,例如 testoperators,带有子测试 testadd、testsubtract、testmultiply、testdivision。 testing 包在 *testing 类型上提供 run 方法。t 来定义子测试。

    func testoperators(t *testing.t) {
        var complex1, complex2, complex3 *cpx.complex
        complex1 = &cpx.complex{
            real: 1,
            imag: 10,
        }
    
        complex2 = &cpx.complex{
            real: 2,
            imag: 9,
        }
    
        t.run("testadd", func(t *testing.t) {
            complex3 = cpx.complexadd(complex1, complex2)
            assert.notnil(t, complex3)
        })
    
        t.run("testsubtract", func(t *testing.t) {
            complex3 = cpx.complexsubtract(complex1, complex2)
            // tests here
        })
    
        t.run("testmultiply", multiply)
    
        // more sub tests...
    
    }
    
    func multiply(t *testing.t) {
        // tests here
    }
    

    您可以使用内联匿名函数(如在 testadd 和 testsubtract 中)或一般测试用例(如在 testmultiply 中)。如果使用函数,请确保函数名称(标识符)不以“测试”开头。否则,go 工具会将其视为一个单独的测试用例。输出将是:

    go test -v ./...
    ?       gitlab.com/VagueCoder0to.n/Project  [no test files]
    === RUN   TestOperators
    === RUN   TestOperators/TestAdd
    === RUN   TestOperators/TestSubtract
    === RUN   TestOperators/TestMultiply
    --- PASS: TestOperators (0.00s)
        --- PASS: TestOperators/TestAdd (0.00s)
        --- PASS: TestOperators/TestSubtract (0.00s)
        --- PASS: TestOperators/TestMultiply (0.00s)
    PASS
    ok      gitlab.com/VagueCoder0to.n/Project/cpx  0.004s

    今天关于《如何在不同的测试文件中分享项目》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

    本文内容来源于互联网,如有侵权请联系删除。

    相关文章

    更多

    热门专题

    更多
    首页