Testing in Go: Test Fixtures

For those who have written unit tests in Go, the stripped down nature of the language might have produced some inconvenient duplication and seeming messiness in each test. For example, if you have a test for creating a new item, adds a generated identifier and saves in an in-memory data-store, it may look as follows:

func TestIdentifierGenerated(t *testing.T) {
   userStore := &databasemocks.MockUserStore{}
   service := users.NewUserCreationService(userStore)   
   newUser := users.User{	
	FirstName:    "Jack",	
	LastName:     "Parow",	
	MobileNumber: "+27839023001",	
	EmailAddress: "jack@parow.com",	
	Password:     "P@ssword",
	}
    service.CreateUser(newUser)
    if userStore.SavedUsers[0].Identifier = "" {
       t.Errorf("User identifier not generated")   
    }
}

As tests get more complicated, and there are more dependencies and collaborators, constructing the object under test becomes tedious. A solution, that still fits in the Go paradigm is to use the Xunit testing pattern of delegating the creation of the test fixture to a common method that can be uses by other tests as follows:

type userCreationTestFixture struct {
    userStore *databasemocks.MockUserStore
    service   *users.UserCreatioinService
}
func createTestFixture() *userCreationTestFixture {
    userStore := &databasemocks.MockUserStore{}    
    return &userCreationTestFixture{
        userStore: userStore,
        service:   users.NewUserCreationService(userStore),
    }
}

func TestIdentifierGenerated(t *testing.T) {
   testFixture := createTestFixture()   
   newUser := users.User{	
	FirstName:    "Jack",	
	LastName:     "Parow",	
	MobileNumber: "+27839023001",	
	EmailAddress: "jack@parow.com",	
	Password:     "P@ssword",
    }
       
    testFixture.service.CreateUser(newUser)      
    if testFixture.userStore.SavedUsers[0].Identifier = "" {
       t.Errorf("User identifier not generated")   
    }
}

In this way, all common setup methods are delegated to the `createTestFixture` method, making the individual tests cleaner and more maintainable. The fixture creation function can also be parameterized to allow for the flexibility to deal with multiple scenarios where needed.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s