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