LoginSignup
0
1

More than 3 years have passed since last update.

【Golang】テスト

Posted at

【Golang】テスト

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

//main.go
package main
//testing
//テストを書く位置は、テストしたいファイルと同じ階層に書く.
//math.go = math_test.go という名前で作成。_test.goを探して実行される
//math_test.goに移動

//ターミナルで プロジェクトの中で、go test ./... で実行できる
//詳しいテスト内容を表示 go test -v ./...
/*
?       kiso_blog/go_test   [no test files]
ok      kiso_blog/go_test/alib  0.328s
*/

//相対パスでテストをやる場合、go test ./alib 
/*
aoyagimasanori@aoyagimasanorinoMacBook-Pro go_test % go test ./alib 
ok      kiso_blog/go_test/alib  0.302s
*/

//カバー率 go test -cover ./alib 
/*
ok      kiso_blog/go_test/alib  0.246s  coverage: 100.0% of statements
*/

//mainパッケージのテスト
//go test -v
/*
=== RUN   TestIsOne
    TestIsOne: main_test.go:15: 2 != 1
--- FAIL: TestIsOne (0.00s)
FAIL
exit status 1
FAIL    kiso_blog/go_test   0.226s
*/


//ユニットテストをやる場合は、Ginkgo(rubyっぽい),Gomega(jsっぽい)などを使ったりする
import (
    "fmt"
    //ここのエラーは相対パスだから
    //"./alib"
    "kiso_blog/go_test/alib"
)

func IsOne(i int) bool {
    if i == 1{
        return true
    }else{
        return false
    }
}

func main() {
    s := []int{1,2,3,4,5}
    fmt.Println(s)
    fmt.Println(alib.Average(s))
}
//main_test.go
package main
//mainパッケージのテスト

import "testing"

var Debug bool = false

func TestIsOne(t *testing.T) {
    i := 2
    if Debug{
        t.Skip("スキップする")
    }
    v := IsOne(i)

    if !v{
        t.Errorf("%d != %d",i, 1)
    }
}
//alib/alib.go
package alib


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

//テスト用パッケージを読み込み
import "testing"

//このテストを飛ばしたい時はtrueにする
var Debug bool = false

//テスト
//Average関数のテスト例
//Test関数名にする
//引数はtにする。Errorなどの関数が使える。Skipなど
func TestAverage(t *testing.T) {
    if Debug {
        t.Skip("スキップします")
    }
    //ave3.5(1,2,3,4,5,6)は3になるらしい。
    //7までにすると、下記エラーが出る
    /*
            === RUN   TestAverage
            TestAverage: alib_test.go:22: 3じゃない 4
            TestAverage: alib_test.go:23: 4 != 3
            --- FAIL: TestAverage (0.00s)
            FAIL
            FAIL    kiso_blog/go_test/alib  0.308s
            FAIL
    */
    v := Average([]int{1, 2, 3, 4, 5}) //6,7 でエラー
    //もし、3でなければエラー
    if v != 3 {
        //エラー文字、値
        t.Error("3じゃない", v)
        t.Errorf("%d != %d", v, 3)
    }
}

0
1
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
1