Go Unit Test

スポンサーリンク

testing package

Go supports Test by default. testing package has functions to write test.

To write test, filename is
xxxxx_test.go (xxxxx is test target file).

function type is TestXxxx(t *testing.T)

Sample

Let’s write json file read code and its test

jsonfile.go

package basic2

import (
	"encoding/json"
	"fmt"
	"os"
)

type People struct {
	Name string `json:name`
	Id   int    `json:id`
}

func Decode(filename string) (person People, err error) {
	jsonFile, err := os.Open(filename)
	if err != nil {
		fmt.Println("Error : cannot open file ", err)
		return
	}
	defer jsonFile.Close()

	decoder := json.NewDecoder(jsonFile)
	err = decoder.Decode(&person)
	if err != nil {
		fmt.Println("Error decoding JSON:", err)
		return
	}
	return
}

This has public Decode method to return struct and error.

jsonfile_test.go

package basic2

import "testing"

/*
*  TestXxxx(t *testing.T)
*  filename :  xxx_test.go
 */
func TestDecodeFunc(t *testing.T) {
	person, err := Decode("person.json")
	if err != nil {
		t.Error(err)
	}
	if person.Id != 1 {
		t.Error("Wrong Id")
	}
	if person.Name != "Lala" {
		t.Error("Wrong name")
	}
}

func TestDecode2(t *testing.T) {
	t.Skip("Skip this test")
}

First test check error and property values. If no error, this test will pass.

2nd one is Skip test.

How to run test

To run test, need to go test file directory and run following command

go test

This commands execute test under target directory

To see more info,

go test -v -cover
golang
スポンサーリンク
Professional Programmer2

コメント