LoginSignup
0
0

More than 3 years have passed since last update.

go修行14日目 ユニットテストとか

Posted at

testing

└── mylib
    ├── human.go
    ├── math.go
    ├── math_test.go

testされるファイル

package mylib

func Average(s []int) int {
    total := 0
    for _, i := range s {
        total += i
    }
    return int(total / len(s))
}

testするファイル

  • 3が期待される

package mylib

import "testing"

func TestAverage(t *testing.T) {
    v := Average([]int{1, 2, 3, 4, 5})
    if v != 3 {
        t.Error("Expected 3, got", v)
    }
}

run test

  • vscodeから

image.png
image.png

  • コマンドラインから
PS C:\Users\yuta\go\src\awesomeProject> go test ./...
?       awesomeProject  [no test files]
ok      awesomeProject/mylib    (cached)
?       awesomeProject/mylib/under      [no test files]
  • 数字変えるとFAILになる

package mylib

import "testing"

func TestAverage(t *testing.T) {
    v := Average([]int{1, 2, 3, 4, 5, 6,7})
    if v != 3 {
        t.Error("Expected 3, got", v)
    }
}
--- FAIL: TestAverage (0.00s)
    C:\Users\yuta\go\src\awesomeProject\mylib\math_test.go:8: Expected 3, got 4
FAIL
FAIL    awesomeProject/mylib    0.374s
FAIL
  • Skip処理

package mylib

import "testing"

var Debug bool = true

func TestAverage(t *testing.T) {
    // Debugがtrueならスキップ
    if Debug {
        t.Skip("Skip reason")
    }
    v := Average([]int{1, 2, 3, 4, 5, 6, 7})
    if v != 3 {
        t.Error("Expected 3, got", v)
    }
}

PS C:\Users\yuta\go\src\awesomeProject> go test ./... -v
?       awesomeProject  [no test files]
=== RUN   TestAverage
    TestAverage: math_test.go:10: Skip reason
--- SKIP: TestAverage (0.00s)
PASS
ok      awesomeProject/mylib    0.368s
?       awesomeProject/mylib/under      [no test files]
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