英文:
Test to check if a function didn't run?
问题
所以我对测试还不太熟悉,我在尝试为一个触发另一个函数的函数编写测试时遇到了困难。这是我目前的代码,但如果函数没有运行,它会变得有些反向并且永远阻塞:
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()
)?
英文:
So I'm new to testing in general and I'm stuck trying to write a test for a function that triggers another function. This is what I have so far but it's kind of backwards and blocks forever if the function doesn't run:
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
will trigger the trigger()
function when certain criteria is met. It tests whether or not the criteria is met every 1
second.
The error case is when the function fails to run. Is there a way to test for this or is there a way to use the testing package to test for success (e.g. t.Pass()
)?
答案1
得分: 2
如果c.Start
是同步的,你可以简单地传递一个函数来设置测试用例范围内的一个值,然后根据该值进行测试。考虑下面示例中由trigger
函数设置的functionCalled
变量(playground):
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")
}
}
英文:
If c.Start
is synchronous, you can simply pass a function that sets a value in the test case's scope, and then test against that value. Condider the functionCalled
variable in the example below that is set by the trigger
function (playground):
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")
}
}
If c.Start
is asynchronous, you can use a select
statement to implement a timeout that will fail the test when the passed function was not called within a given time frame (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")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论