Golang中如何对每个函数进行超时测试

Golang中如何对每个函数进行超时测试 -timeout 参数是针对每个包的,如何为每个测试函数设置超时?

2 回复

你好 @tisonkun

目前没有针对函数级别测试的超时标志。一个可行的选择是为长时间运行的测试函数配备一个使用 time.After() 的超时机制

func TestLongRunning(t *testing.T) {
    timeout := time.After(5 * time.Second)
    done := make(chan bool)

    go func() {
        // 执行长时间运行的操作
        time.Sleep(10 * time.Second)
        done <- true
    }()

    select {
    case <-timeout:
        t.Fatal("测试超时")
    case <-done:
        // 测试通过
    }
}

更多关于Golang中如何对每个函数进行超时测试的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中,可以通过testing包的t.SetDeadline()方法为每个测试函数单独设置超时。以下是一个示例:

func TestWithTimeout(t *testing.T) {
    // 设置测试超时为2秒
    deadline, ok := t.Deadline()
    if ok {
        t.SetDeadline(time.Now().Add(2 * time.Second))
    }
    
    // 模拟耗时操作
    time.Sleep(3 * time.Second) // 这会触发超时
    
    t.Log("测试完成")
}

func TestWithoutTimeout(t *testing.T) {
    // 不设置超时,使用默认值
    
    time.Sleep(1 * time.Second) // 这不会超时
    
    t.Log("测试完成")
}

对于需要更细粒度控制的场景,可以使用context.Context

func TestWithContextTimeout(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    
    done := make(chan bool)
    
    go func() {
        // 模拟耗时操作
        time.Sleep(3 * time.Second)
        done <- true
    }()
    
    select {
    case <-ctx.Done():
        t.Fatal("测试超时")
    case <-done:
        t.Log("测试完成")
    }
}

对于表格驱动测试,可以在每个子测试中单独设置超时:

func TestTableDriven(t *testing.T) {
    testCases := []struct {
        name string
        timeout time.Duration
    }{
        {"fast", 1 * time.Second},
        {"slow", 3 * time.Second},
    }
    
    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            deadline, ok := t.Deadline()
            if ok {
                t.SetDeadline(time.Now().Add(tc.timeout))
            }
            
            // 测试逻辑
            time.Sleep(2 * time.Second)
        })
    }
}

这些方法允许在每个测试函数级别控制超时,而不是整个测试包级别。

回到顶部