Proper testing method for function in go

huangapple go评论83阅读模式
英文:

Proper testing method for function in go

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我刚开始学习Go语言,并开始尝试测试。我的方法返回一个包含MD5哈希值的[]byte。

func myHash(s string) []byte {
    h := md5.New()
    io.WriteString(h, s)
    return h.Sum(nil)
}

这个方法运行正常,哈希值看起来也没问题,但是当我使用下面的方法进行测试时:

func TestMyHash(t *testing.T) {
    s := "linux"
    bf := "e206a54e97690cce50cc872dd70ee896"
    x := myHash(s)
    if !bytes.Equal(x, []byte(bf)) {
        t.Errorf("myHash ...")
    }
}

测试总是失败。起初我以为可能是将字符串转换为[]byte或反之的问题,但是尝试了多次后,我只能在这里提问了。

你能给我一个测试函数的示例吗?我是否漏掉了必要的东西?

提前感谢。

英文:

I'm new to go and started to play around with testing.
My method returns a []byte with a md5 hash in it.

func myHash(s string) []byte {
    h := md5.New()
    io.WriteString(h, s)
    return h.Sum(nil)
}

It's working and the hashes look ok, but when I'm testing it with this method:

func TestMyHash(t *testing.T) {
    s := "linux"
    bf := ("e206a54e97690cce50cc872dd70ee896")
    x := hashor(s)
    if !bytes.Equal(x, []byte(bf)) {
        t.Errorf("myHash ...")
    }
}

It will always fail. First I thought it could be some issue with the casting of a string to []byte or vice versa, but after trying ot over and over again I just need to ask here.

Can you give me an example how to test my function? Do I miss something necessary?

Thanks in advance.

答案1

得分: 6

你可能正在将哈希的原始字节与哈希的十六进制格式进行比较。你可能想要像这样做:

got := fmt.Sprintf("%034x", myHash("linux"))
want := "00e206a54e97690cce50cc872dd70ee896"
if got != want {
    t.Errorf("got %q, want %q", got, want) 
}
英文:

You are probably comparing the raw bytes of the hash with the hexadecimal formatted version of a hash. You might want to do something like this:

got := fmt.Sprintf("%034x", myHash("linux"))
want := "00e206a54e97690cce50cc872dd70ee896"
if got != want {
    t.Errorf("got %q, want %q", got, want) 
}

huangapple
  • 本文由 发表于 2013年8月16日 22:02:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/18275191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定