LoginSignup
2
2

More than 5 years have passed since last update.

Hello World の次にテストを練習する

Last updated at Posted at 2017-06-16

概要

Go には標準のテストツールが用意されており、Hello World の書き方を学んだらすぐにテストの練習を始めることができます。

Hello World の復習

Hello Wolrd を表示するプログラムを書いてみましょう。hello.go としてます。

hello.go
package main

func main() {
    println("hello world")
}

print および printlnbuiltin モジュールなので、明示的に import を書かなくてすみます。

実行してみましょう。

go run hello.go

モジュールのインポートの練習として printlnfmt.Println に置き換えてみましょう。

hello.go
package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}   

関数を定義する

テストの練習のために関数を定義します。Hello World という文字列を返す関数を定義してみましょう。hello.go は次のように書き換えられます。

hello.go
package main

func getGreeting() string {
    return "Hello World"
}

func main() {
    println(getGreeting())
}

最小限のテストコードを書く

テストの練習にとりかかってみましょう。hello_test.go という名前のテストを書いてみましょう。

hello_test.go
package main

import (
    "testing"
)

func TestHello(t *testing.T) {
}

テストを実行してみましょう。

bash
go test

結果は次のようになります。

PASS
ok      _/Users/masakielastic/test/golang-project   0.019s

よりくわしい情報を表示させたいのであれば -v オプションを指定します。

go test -v

個別にファイルの名前を指定することができます。

go test hello_test.go

失敗させてみよう

t.Fail() を追加してみましょう。

hello_test.go
package main

import (
    "testing"
)

func TestHello(t *testing.T) {
    t.Fail()
}

go test -v を実行すると結果は次のようになります。

--- FAIL: TestHello (0.00s)
FAIL
exit status 1
FAIL    _/Users/masakielastic/test/golang-project   0.018s

自分が書いたメッセージを表示させるために t.Error() を使ってみましょう。

hello_test.go
package main

import (
    "testing"
)

func TestHello(t *testing.T) {
    t.Error("失敗しました。")
}

結果は次のようになります。

=== RUN   TestHello
--- FAIL: TestHello (0.00s)
    hello_test.go:8: 失敗しました。
FAIL
exit status 1
FAIL    _/Users/masakielastic/test/golang-project   0.019s

自分で定義した関数をテストする

hello.go で定義した getGreeting 関数を hello_test.go でテストしてみましょう。

hello_test.go
package main

import (
    "testing"
)

func TestHello(t *testing.T) {
    expected := "Hello World"
    actual := getGreeting()

    if expected != actual {
        t.Error("期待される文字列を得られませんでした。")
    }
}

go test -v を実行すれば PASS が表示されます。

アサートを使う

毎回 if 文を書くのはめんどうなので、Testify を導入してアサートを使えるようにしてみましょう。次のコマンドで最新のパッケージをインストールします。

go get github.com/stretchr/testify/assert
hello_test.go
package main

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func TestHello(t *testing.T) {
    expected := "Hello World"
    actual := getGreeting()

    assert := assert.New(t)
    assert.Equal(expected, actual, "同じ値でなけければなりません。")
}

require を使う

assert の代わりに require を使ってみましょう。

hello_test.go
package main

import (
    "testing"
    "github.com/stretchr/testify/require"
)

func TestHello(t *testing.T) {
    expected := "Hello World"
    actual := getGreeting()

    require.Equal(t, expected, actual, "同じ値でなけければなりません。")
}
2
2
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
2
2