0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go 言語仕様10(テスト)

Last updated at Posted at 2021-02-14

概要

Go 言語の仕様まとめ。

前回:
Go 言語仕様9(構造体)

内容

  • テスト

テスト

Goでは標準でテスト用のパッケージが用意されているため、容易に単体テストができる。
手順は以下。

  • テストをしたいファイルと同じディレクトリ内にテストファイルを作成する。ファイル名は、パッケージ名_test.go
ディレクトリ構成
go/
 └ src/
   └ test/
     ├ main.go
     └ main_test.go 

  

  • main.goにテストしたい関数を作成。(型をチェックし、stringの場合にtrueを返す。)
main.go
package main

import "fmt"

func CheckTypes(t interface{}) bool {
	var returnVal bool

	switch t.(type) {
	case int:
		returnVal = false
	case string:
		returnVal = true
	case float64:
		returnVal = false
	default:
		returnVal = false
	}

	return returnVal
}

func main() {
	var f interface{} = "Golang"
	//var f interface{} = 100

	if b := CheckTypes(f); !b {
		fmt.Println("error")
	} else {
		fmt.Println("ok")
	}
}

  

  • main_test.goにCheckTypesをテストする関数を作成。
main_test.go
package main

import (
	// testingパッケージをimportする
	"testing"
)

// テストしたいときだけfalseにする
var DoTest bool = false

// 関数名はTestではじめて、テストしたい関数名をつなげる
// testing.Tを引数に指定する
func TestCheckTypes(t *testing.T) {
	if DoTest {
		t.Skip("Do nothing")
	}

	// PASS
	var f interface{} = "Golang"
	// FAIL
	//var f interface{} = 100

	var result bool = CheckTypes(f)

	// falseの場合はエラーにして、テストを終了させる
	if !result {
		t.Errorf("error")
	}
}

  

  • テストの実行

テストファイルがあるディレクトリで、go testコマンドを実行する。

エラーなしの場合
$ go test

PASS
ok      test    0.398s
エラーの場合
$ go test

--- FAIL: TestCheckTypes (0.00s)
    main_test.go:22: error
FAIL
exit status 1
FAIL    test    0.302s

go test -vで詳細を出力できる。

$ go test -v

=== RUN   TestCheckTypes
    main_test.go:22: error
--- FAIL: TestCheckTypes (0.00s)
FAIL
exit status 1
FAIL    test    0.177s

  

  • 特定のファイルを指定してテストを実施する場合
// テスト対象のファイル名を指定する
go test xxx_test.go xxx.go

  

次回

Go 言語仕様11(スコープ)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?