【问题标题】:Test to check if a function didn't run?测试以检查函数是否未运行?
【发布时间】:2017-01-16 00:42:04
【问题描述】:

所以我是一般测试的新手,我一直在尝试为触发另一个函数的函数编写测试。这就是我目前所拥有的,但如果函数不运行,它会有点倒退并永远阻塞:

var cha = make(chan bool, 1)                

func TestFd(t *testing.T) {                 
  c := &fd.Fdcount{Interval: 1, MaxFiles: 1}
  c.Start(trigger)
  if <- cha {                               

  }                                         
}                                           

func trigger(i int) {                       
  cha <- true                               
}               

c.Start 将在满足某些条件时触发trigger() 函数。它每隔1 秒测试一次是否满足条件。

错误情况是函数运行失败。有没有办法对此进行测试,或者有没有办法使用测试包来测试是否成功(例如t.Pass())?

【问题讨论】:

    标签: unit-testing go


    【解决方案1】:

    如果c.Start 是同步的,您可以简单地传递一个在测试用例范围内设置值的函数,然后针对该值进行测试。考虑下面示例中由 trigger 函数 (playground) 设置的 functionCalled 变量:

    func TestFd(t *testing.T) {
        functionCalled := false
        trigger := func(i int) {
            functionCalled = true;
        }
    
        c := &fd.Fdcount{Interval: 1, MaxFiles: 1}
        c.Start(trigger)
    
        if !functionCalled {
            t.FatalF("function was not called")
        }
    }
    

    如果c.Start 是异步的,您可以使用select 语句实现超时,如果在给定时间范围内未调用传递的函数(playground),则测试失败:

    func TestFd(t *testing.T) {
        functionCalled := make(chan bool)
        timeoutSeconds := 1 * time.Second
        trigger := func(i int) {
            functionCalled <- true
        }
    
        timeout := time.After(timeoutSeconds)
    
        c := &SomeStruct{}
        c.Start(trigger)
    
        select {
            case <- functionCalled:
                t.Logf("function was called")
            case <- timeout:
                t.Fatalf("function was not called within timeout")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多