Testing using local files

Issue

I’m looking for what best practice I should use when it comes to testing with Go using local files.

By using local files, I mean that in order to test functionality, the application needs some local files, as the application reads from these files frequently.

I’m not sure if I should write temporary files myself just before running the tests using the ioutil package tempdir and tempfile functions, or create a test folder like so;

testing/...test_files_here
main.go
main_test.go

and then read from the contents inside

testing/...

Solution

This is my current test setup:

app/
   main.go
   main_test.go
   main_testdata

   package1/
     package1.go 
     package1_test.go 
     package1_testdata1

   package2/
     package2.go 
     package2_test.go 
     package2_testdata1

All the test data that is specific to a single package, is placed within the directory of that package. Common test data that will be used by multiple packages are either placed in the application root or in $HOME.

This set up works for me. Its easy to change the data and test, without having to do extra typing:

vim package1_test_data1; go test app/package1

Answered By – Anfernee

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.