英文:
Testing the Go model
问题
这是我的一个Go模型示例:
type ObjectReference struct {
IRI string `json:"iri" bson:"iri"`
ObjectType string `json:"objectType" bson:"objectType,omitempty"`
ActivityType string `json:"activityType,omitempty" bson:"activityType,omitempty"`
Errors `bson:"-"`
}
我对ActivityType进行了验证:
objTypeSuccess := o.ObjectType == "activity"
success = success && objTypeSuccess
if !objTypeSuccess {
o.errors = append(o.errors, "Object objectType supplied: "+o.ObjectType+" is invalid. Valid object types are: [activity]")
}
其中,o *ObjectReference在func()定义中。
我试图编写一个测试,如下所示:
testObj = models.ObjectReference{
// 无效的Obj类型
IRI: "http://localhost:8001/launched",
ObjectType: ????, // 这里我不太明白如何初始化`ObjectType`。有人可以帮我吗?
ActivityType: testObjType,
}
你可以帮我解决这个问题吗?
英文:
So this is one of my Go models:
type ObjectReference struct {
IRI string `json:"iri" bson:"iri"`
ObjectType string `json:"objectType" bson:"objectType,omitempty"`
ActivityType string `json:"activityType,omitempty" bson:"activityType,omitempty"`
Errors `bson:"-"`
}
I have a validation on the ActivityType as:
objTypeSuccess := o.ObjectType == "activity"
success = success && objTypeSuccess
if (!objTypeSuccess) {
o.errors = append(o.errors, "Object objectType supplied : " + o.ObjectType + " is invalid. Valid object types are : [activity]")
}
where
o *ObjectReference is in the func() definition
I am trying to write a test as so:
testObj = models.ObjectReference{
// Invalid Obj Type
IRI: "http://localhost:8001/launched",
ObjectType: ????,
ActivityType: testObjType,
}
I don't quite understand how I could initialize the ObjectType in my testObj. Can someone help me with this?
答案1
得分: 1
ObjectReference.ObjectType 是一个类型为 string 的字段。也就是说,你可以用类型为 string 的表达式进行初始化。类型为 string 的最基本/简单的表达式是字符串字面量,比如 "hello"。
由于在你的测试代码中,你将其与值 "activity" 进行比较,我假设这就是你想要进行初始化的值。你可以这样做:
testObj = models.ObjectReference{
IRI: "http://localhost:8001/launched",
ObjectType: "activity",
ActivityType: testObjType,
}
当然,你也可以指定任何其他类型为 string 的值/表达式:
testObj = models.ObjectReference{
IRI: "http://localhost:8001/launched",
ObjectType: "NOT-AN-ACTIVITY",
ActivityType: testObjType,
}
英文:
The ObjectReference.ObjectType is a field of type string. That being said you can initialize it with an expression of type string. The most basic/simple expression of type string is a string literal such as "hello".
Since in your test code you compare it to the value "activity", I assume that is what you want to initialize it with. You can do that like this:
testObj = models.ObjectReference{
IRI: "http://localhost:8001/launched",
ObjectType: "activity",
ActivityType: testObjType,
}
But of course you can specify any other values/expressions of type stirng:
testObj = models.ObjectReference{
IRI: "http://localhost:8001/launched",
ObjectType: "NOT-AN-ACTIVITY",
ActivityType: testObjType,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论