Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The first question is, "what to test?" In this case, I'll test a method called GetDirPath in the file image.go.

GetDirPath uses the Go core packages user and path to return a file path, and a directory path.


Code Block
languagetext
themeFadeToGrey
package app

import (
"os/user"
"path"

pkgerrors "github.com/pkg/errors"
)

func (v *ImageClient) GetDirPath(imageName string) (string, string, error) {
	u, err := user.Current()
	if err != nil {
 		return "", "", pkgerrors.Wrap(err, "Current user")
	}
	home := u.HomeDir
	dirPath := path.Join(home, "images", v.storeName)
	filePath := path.Join(dirPath, imageName)

	return filePath, dirPath, err
}

To Do - Explain

To test, I'll create the test file image_test.go. A test for the GetDirPath could look like this:


Here is the ImageClient type that the method GetDirPath is defined on.:

Code Block
languagetext
themeFadeToGrey
type ImageClient struct {
	storeName string
	tagMeta   string
}


To test Go packages, Go has a core package called testing which is used with the command go test. I'll create the test file image_test.go in the same package as my image.go file. A test for the GetDirPath could look like this:

Code Block
languagetext
themeFadeToGrey
import (
  "testing"
)

func TestGetDirPath(t *testing.T) {

  imageClient := &ImageClient{"test_image", "test_meta"}
  actual, dir, err := imageClient.GetDirPath("test")
  var expected = "/home/enyi/images/test_image/test"
  if actual != expected {
    t.Errorf("Path was incorrect, got: %s, want %s.", actual, expected)
  }
}


The TestGetDirPath (Test functions begin with Test) function uses the testing package to print a message before failing. You can explore the testing package here https://golang.org/pkg/testing/.


Next, we'll mock out the user package with Testify and rewrite our test.To Do - Explain



References:

  1. https://restfulapi.net/rest-architectural-constraints/

...