doumao8355 2016-06-02 19:12
浏览 20
已采纳

测试返回值的存在是否可能是具体的或为零

How would you write a test for a function that returns a value that could either be nil or a concrete value? I don't care about the actual value itself, I just care about whether the value has been returned or not.

type CustomType struct{}

func TestSomeFunc(t *testing.T) {
  case := map[string]struct {
    Input string
    Expected *CustomType // expected result
    Error error // expected error value
  } {
    "test case 1": 
      "input",
      &CustomType{}, // could be nil or a concrete value    
      nil,
    "test case 2": 
      "input",
      nil, // could be nil or a concrete value    
      ErrSomeError,
  }

  actual, err := SomeFunc(case.Input)
  if (actual != case.Expected) {
    t.Fatalf(...)
  }
}

and the function to be tested could look something like:

func SomeFunc(input string) (*CustomType, error) {
  foo, err := doSomething()
  if err != nil {
    return nil, err 
  }
  return foo, nil
}

I guess the logic I want is:

if ((case.Expected != nil && actual == nil) || 
    (case.Expected == nil && actual != nil)) {
    t.Fatalf(...)
}

Is there a better way of just asserting for existence rather than comparing concrete types?

  • 写回答

1条回答 默认 最新

  • dtjxhf595733 2016-06-02 19:26
    关注

    It's not much shorter than what you have, but I think what you want is for the test to pass only when (case.Expected == nil) == (actual == nil), comparing the (true or false) results of two comparisons against nil. Here's a short program demonstrating:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        isNil, isNotNil, otherNotNil := []byte(nil), []byte{0}, []byte{1}
        fmt.Println("two different non-nil values\t", (otherNotNil == nil) == (isNotNil == nil))
        fmt.Println("a nil and a non-nil value\t", (isNil == nil) == (isNotNil == nil))
        fmt.Println("two nil values\t\t\t", (isNil == nil) == (isNil == nil))
    }
    

    As user icza points out, you can change the outer == into a != (giving you something like (actual == nil) != (expected == nil)) to get true when there is a mismatch rather than when there is a match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验