株式会社ヴァンデミックシステム

Blog

<スポンサーリンク>

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]

<スポンサーリンク>

コメントを残す

Allowed tags:  you may use these HTML tags and attributes: <a href="">, <strong>, <em>, <h1>, <h2>, <h3>
Please note:  all comments go through moderation.

*

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)