测试以检查功能是否未运行?

时间:2017-01-15 16:19:05

标签: unit-testing go

所以我是一般的测试新手而且我一直试图为触发另一个函数的函数编写测试。这是我到目前为止所做的,但是如果函数没有运行的话,它会向后延迟并永久阻塞:

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())?

1 个答案:

答案 0 :(得分:2)

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

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")
    }
}
相关问题