gpt4 book ai didi

go - 测试多次调用构造函数的地方?

转载 作者:IT王子 更新时间:2023-10-29 01:39:43 25 4
gpt4 key购买 nike

import (
"testing"
"github.com/stretchr/testify/assert"
)

func TestNewPerson(t *testing.T) {
firstName := "Barack"
lastName := "Obama"
birthYear := 1990

p, err := NewPerson(firstName, lastName, birthYear)

assert.Equal(t, err, nil, "Should not return error.")
assert.Equal(t, p.FirstName, firstName, "First name came wrong.")
assert.Equal(t, p.LastName, lastName, "Last name came wrong.")
assert.Equal(t, p.BirthYear, birthYear, "Birth year name came wrong.")
}

func TestFullName(t *testing.T) {
tests := []struct{
firstName string
lastName string
fullName string
}{
{"Hello", "World", "Hello World",},
{"Barack", "Hussein Obama ", "Barack Hussein Obama",},
}

for _, obj := range tests {
p, _ := NewPerson(obj.firstName, obj.lastName, 1990)

assert.Equal(t, obj.fullName, p.FullName())
}
}

这很好用。但是当我编写了很多测试,然后我需要在“NewPerson”构造函数中进行更改时会发生什么,因为我向结构添加了一个新属性?

然后我将不得不更改对构造函数的调用的所有参数。

有什么解决方案?我应该寻找一种方法来抽象它吗?

最佳答案

那种重构可以(未测试)用 command go fmt 来处理.

参见“Refactoring with go fmt”:

gofmt uses patterns to identify changes to make to your code. Patterns are established in the first half the expression followed by a ‘->’ then used by the second half of the expression.

Use the flag -d instead of -w to check what gofmt will do prior to running it.

gofmt -r "yourConstructor(x,y) -> yourConstructor(x, y, z)" -d ./

仅当您指定的模式是有效的 go expression 时才有效,如 this answer 中所述.

关于go - 测试多次调用构造函数的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695252/

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