Where to place test helper functions?

I have multiple tests that are using the same functions, mostly mocking and stubbing functionality. Where should such things be placed? Is there any idiomatic place to store these?

Hi mendlock, you should create a file for the test functions with a specific name. For example, If you have a function named “newDeck” you should create a function “TestNewDeck” in another file.
Here is the Golang Test
Also I attach one example.
You can also run “Go test” to run these test and creates a report with the results.
Regards :grinning:

Thanks!

I’ve understood as much. I think.
But let’s say I have two test files:

main_test.go
user_test.go

On both of those is using a function that is only for test purposes and needed by many tests.

Let’s say a function to create a mocked User if some kind.
Where should I put that?

Hi, I am not sure if there is any specification for golang testing.
I believe you should create different files for unit testing, integration testing, and system testing.
Check the following link.

You can have multiple _test.go files. And if you run “go test” inside a folder will it find all tests. For example i have three files main.go, main_test.go and mock_test.go and then runs go test -v (-v verbose) it will find the test in main_test.go and the struct in mock_test.go and output this:

$ go test -v
=== RUN   TestUsername
--- PASS: TestUsername (0.00s)
PASS
ok      _/Users/xxx/projects/zzz       0.008s

mock_test.go

package main

type MockUser struct {
}

func (u MockUser) Name() string {
	return "Peter"
}

main_test.go

package main

import "testing"

func TestUsername(t *testing.T) {
	u := MockUser{}
	name := u.Name()

	if name != "Peter" {
		t.Errorf("wanted Peter got %s", name)
	}
}

And you could use the Mockuser in more _test.go files if you want to

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.