This is a creation in Article, where the information may have evolved or changed.
Write the Go Language program, in unit testing, often need to compare two values are equal, compare whether a value is nil, or whether to throw a panic. The following three functions are written to judge each other. Specific application, you can adjust according to the actual situation.
funcVerify (t *testing. T, Funstring, output, expectedInterface{}){ifOutput! = expected {T.errorf ("%s:output%v! =%v", fun, output, expected)}}funcVerifynil (t *testing. T, Funstring, outputInterface{}) {V: = reflect. ValueOf (Output)ifV.isvalid () &&!v.isnil () {T.errorf ("%s:output%v is not nil", fun, Output)}}funcVerifypanic (t *testing. T, Funstring, ErrtypeInterface{}, Expectedmsgstring) {msgfeild: ="Message"E: =Recover()ifE = =Nil{T.errorf ("%s:expected error [%T], but a nil!", fun, Errtype)return}ifReflect. TypeOf (errtype)! = reflect. TypeOf (e) {T.errorf ("%s:expected error [%T], but [%t]!", fun, Errtype, E)return} errmsg: = Reflect. ValueOf (E). Elem (). Fieldbyname (Msgfeild)ifErrmsg.string ()! = expectedmsg {T.errorf ("%s:expected error message [%s], but [%s]!", fun, expectedmsg, errmsg)return}}
1. Determine if the two values are equal, as shown in the following code:
verify(t, "TestStateMachine 1", sm.GetCurrentState().ID(), "s2")sm.SendEvent(e2)verify(t, "TestStateMachine 2", sm.GetCurrentState().ID(), "s3")sm.SendEvent(e3)verify(t, "TestStateMachine 3", sm.GetCurrentState().ID(), "s1")
In order to distinguish where there is no test pass, an ordinal number is added when the parameter name is passed in.
2. Determine if a value is nil, as shown in the following code:
verifyNil(t, "TestStart 1", sm.GetCurrentState())verifyNil(t, "TestStart 2", sm.GetEvent())
3. Determine if the panic has been thrown, as in the following code:
"Has no action executor for [ao2]."defer"TestHasNoActionExecutor", (*IllegalActionError)(nil), expected)
The code that throws panic is as follows:
panic (&illegalactionerror{ "has No action executor for [" + exec Name + "]. "}"