duandiao3961 2014-04-29 19:30
浏览 54

在Go中进行错误类型检查以进行单元表测试

I want to test the type of the error returned against a table test of expected results, like so:

var tabletest = []struct{
  instruction string
  want string
  err error
}{
  {"synonym for hi", "hello", nil}, // input, retval, errtype
  {"synonym for hig", "", TranslationError{}}, 
  {"sssnymm for hi", "", InstructionError{}},
}

func TestThesaurus(t *Testing) {
  for _, testcase := range tabletest {
    got, err := Thesaurus(testcase.instruction)
    // check error type
    // check result type
  }
}

In the example above, different error sub-classes are returned based on the type of error that occurred. You may imagine that the caller of the made-up Thesaurus function would handle each error type differently.

What is the idiomatic way to assert that the type of error returned, and the type of error expected, are the same?

  • 写回答

3条回答 默认 最新

  • duanouyong4228 2014-04-29 19:30
    关注

    reflect.TypeOf does the job:

    import "reflect"
    
    ...
    
    func TestThesaurus(t *Testing) {
      for _, testcase := range tabletest {
        got, err := Thesaurus(testcase.instruction)
        // check error type
        if goterr, wanterr := reflect.TypeOf(err), reflect.TypeOf(testcase.err); 
             goterr != wanterr {
          t.Errorf("For instruction %q, unexpected error: %q. Wanted %q", 
                   testcase.instruction, goterr, wanterr)
        }
        // check result type
        if want := testcase.want; got != want {
          t.Errorf("For instruction %q, got %q, want %q.", 
                   testcase.instruction, got, want)
        }
      }
    }
    

    Whether or not it's idiomatic is for the community to decide.

    评论

报告相同问题?