gpt4 book ai didi

pointers - 防止在测试时更改结构指针值

转载 作者:行者123 更新时间:2023-12-01 22:41:42 27 4
gpt4 key购买 nike

我如何防止对结构值所做的任何更改仅保留在子测试中,即保持它们在子测试之外不受影响。我无法对结构进行任何更改,因为它们是使用swagger代码生成的自动生成的。这是一个例子:

package main

import (
"testing"
)

func TestTyre(t *testing.T) {
type Tyre struct {
Color *string
}
type Vehicle struct {
Tyre Tyre
}

color := "black"
tyreForTest := Tyre{Color: &color}
expectedTyreColor := color

t.Run("negativeTest", func(t *testing.T) {
tyre := tyreForTest // would have worked if there weren't any pointer variables
*tyre.Color = "blue" // here I expect value to change only for this subtest

vehicle := Vehicle{Tyre: tyre}
actualTyreColor := vehicle.Tyre.Color

ok := (expectedTyreColor == *actualTyreColor)
if ok {
t.Error("Color should be blue")
}
})
t.Run("positiveTest", func(t *testing.T) {
tyre := tyreForTest

vehicle := Vehicle{Tyre: tyre}
actualTyreColor := vehicle.Tyre.Color

ok := (expectedTyreColor == *actualTyreColor)
if !ok {
t.Error("Color should be black, instead of", *actualTyreColor)
}
})
}

输出:
=== RUN   TestTyre
=== RUN TestTyre/negativeTest
=== RUN TestTyre/positiveTest
TestTyre/positiveTest: prog.go:39: Color should be black, instead of blue
--- FAIL: TestTyre (0.00s)
--- PASS: TestTyre/negativeTest (0.00s)
--- FAIL: TestTyre/positiveTest (0.00s)
FAIL

最佳答案

您可以通过在测试用例之间不共享color变量来防止这种情况-每个测试用例都获得一个新的Tyre,但是它们都指向存储颜色值的相同内存。因此,当您在否定测试用例中更改tyre.Color时,您将更新变量color的值,而其他测试用例tyre.Color也指向该变量。

一个简单的解决方案是使用一个函数makeTyre(),该函数使用自己的内存获取全新的Tire,以存储颜色并为每个测试用例获取Tire:

package main

import (
"testing"
)

type Tyre struct {
Color *string
}
type Vehicle struct {
Tyre Tyre
}

func makeTyre() Tyre {
color := "black"
return Tyre{Color: &color}
}

func TestTyre(t *testing.T) {
expectedTyreColor := "black"

t.Run("negativeTest", func(t *testing.T) {
tyre := makeTyre()
*tyre.Color = "blue"
vehicle := Vehicle{Tyre: tyre}
actualTyreColor := vehicle.Tyre.Color

ok := (expectedTyreColor == *actualTyreColor)
if ok {
t.Error("Color should be blue")
}
})
t.Run("positiveTest", func(t *testing.T) {
tyre := makeTyre()

vehicle := Vehicle{Tyre: tyre}
actualTyreColor := vehicle.Tyre.Color

ok := (expectedTyreColor == *actualTyreColor)
if !ok {
t.Error("Color should be black, instead of", *actualTyreColor)
}
})
}

关于pointers - 防止在测试时更改结构指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61694492/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com