How to test multiple implementations of a common interface without duplicating the testcode in Go?

38 views Asked by At

How would I streamline the following testing scenario in Go?

Say I have some interface I with a corresponding implementation A and most of my tests for A basically look like:

func TestSomething(t *testing.T) {
    instances := setupI(5)
    // actual testing code...
}

func setupI(n: int) []I {
    instances := make([]I, n)
    for i := 0; i < n; i++ {
        instances[i] = A { ... } // concrete implementation A used here
    }
    return instances
}

Some other tests are specific to the details hidden behind the interface I, so tests like the following are used instead:

func TestSomethingForA(t *testing.T) {
    instance := A { ... }
    // actual testing code...
}

Say now I have two more implementation for I named B and C. How do I also test B and C with all the tests of the first kind? Of course a simple way would be to copy the common testcode two more times, and, for example, add a parameter to setupI(...) to initialize instances with the different implementations. However, I would like to avoid copying the code and having to keep three different places in sync down the road. Any better ideas?

0

There are 0 answers