douren4075 2017-10-13 09:08
浏览 31

让'go test -run <case>'成功成为'go test'的一般规则是什么?

I found the 'go test' PASS, but if I specific sub test, it will fail, here I give a global variable sample, 'go test' will PASS, and 'go test -run f/sample2' will FAIL.

I'm wonder what's the general rules should I follow to prevent such problems?

t.go

package main

import "fmt"

var g string

func f(s string) string {
        g = g + s
        return s + g
}
func main() {
        fmt.Println(f("a"))
}

t_test.go

package main

import (
        "testing"
)

func Test_f(t *testing.T) {
        tests := []struct {
                name string
                g    string
                s    string
                r    string
        }{
                {"simple", "g1", "s1", "s1s1"},
                {"simple2", "g2", "s2", "s2s1s2"},
                {"simple3", "g3", "s3", "s3s1s2s3"},
        }
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
                        //g = tt.g
                        r := f(tt.s)
                        if r != tt.r {
                                t.Error("r=", r, "expect r=", tt.r)
                        }
                })
        }
}

If global variable is the problem, I often write something like osExit fmtPrint to replace os.Exit and fmt.Print on testing, how to overcome these?

  • 写回答

1条回答 默认 最新

  • dtfpznrbn503027700 2017-10-13 10:43
    关注

    The way to prevent such problems is to not have tests that depend on each other. In your case, the global variable is indeed a problem. If you run the tests in order, they have the expected global state. If you run them out of order, they don't, due to the inter-dependency between the tests.

    The solution is to have each test work independently, by having it set up its own expected state. In this case, that would mean setting the global g variable to the expected value for each test.

    A better solution is to refactor so you don't have global variables at all.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度