Senior
How to test the FastestSearcher function using unit tests?
sobes.tech AI
Answer from AI
To unit test the FastestSearcher function, it is necessary to isolate it from external dependencies and verify the correctness of the logic for selecting the fastest result.
Main steps:
- Create mocks or stubs for search sources that return results with different delays.
- Run FastestSearcher with these mocks.
- Check that the function returns the result from the fastest source.
- Check error handling and timeouts.
Example of a test using the testing package:
func TestFastestSearcher(t *testing.T) {
slow := func() (string, error) {
time.Sleep(100 * time.Millisecond)
return "slow result", nil
}
fast := func() (string, error) {
time.Sleep(10 * time.Millisecond)
return "fast result", nil
}
result, err := FastestSearcher([]func() (string, error){slow, fast})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if result != "fast result" {
t.Errorf("Expected 'fast result', got %s", result)
}
}
This approach allows testing that the function indeed chooses the fastest response.