英文:
Tests where a constructor is called many times?
问题
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, "不应返回错误。")
assert.Equal(t, p.FirstName, firstName, "名字错误。")
assert.Equal(t, p.LastName, lastName, "姓氏错误。")
assert.Equal(t, p.BirthYear, birthYear, "出生年份错误。")
}
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"构造函数进行更改,因为我向结构体添加了一个新属性,会发生什么情况?
然后,我将不得不更改对构造函数的所有调用的参数。
有什么解决办法吗?我应该寻找一种抽象的方式吗?
英文:
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())
}
}
This works fine. But what happens when I've written many tests, and then I need to make a change in the "NewPerson" constructor because I've added a new property to the struct?
I will then have to change all parameters of the calls to the constructors.
What's a solution for this? Should I look for a way to abstract this?
答案1
得分: 3
那种重构(未经测试)可以使用命令go fmt
来处理。
参考“使用go fmt
进行重构”:
gofmt
使用模式来识别要对代码进行的更改。模式在表达式的前半部分建立,后跟一个“->
”,然后由表达式的后半部分使用。使用标志
-d
而不是-w
,可以在运行之前检查gofmt
将要执行的操作。
gofmt -r "yourConstructor(x,y) -> yourConstructor(x, y, z)" -d ./
只有在您指定的模式是有效的go表达式时,它才起作用,如此答案中所述。
英文:
That kind of refactoring could (not tested) be taken care of with the command go fmt
.
See "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 ./
That works only if the pattern you specify is a valid go expression, as mentioned in this answer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论