防止在测试时改变结构指针的值。

问题描述 投票:0回答:1

我如何防止对结构值的任何修改只保留在子测试中,即保持它们在子测试之外不受影响。我不能对结构做任何修改,因为它们是用swagger codegen自动生成的。下面是一个例子。

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
pointers go
1个回答
0
投票

您可以通过不共享 color 测试用例之间的变量--每个测试用例都会得到一个新的 Tyre 但它们都指向同一个存储颜色值的内存。所以,当你改变 tyre.Color 在负测试情况下,你更新变量的值 color 和其他测试用例 tyre.Color 也指向该变量。

简单的解决方法是在函数中加入一个 makeTyre() 获得全新的Tyre,它有自己的内存来存储颜色,并为每个测试案例获得Tyre。

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)
                }
        })
}
© www.soinside.com 2019 - 2024. All rights reserved.