doilux’s tech blog

ITに関する備忘録。 DDP : http://doiluxng.hatenablog.com/entry/2018/01/01/195409

そうだテストを書こう

テストのことを忘れてた。とりあえずクイックソートのコードを書いてみた。

func Sort(in []int) []int {
    if len(in) == 0 || len(in) == 1 {
        return in
    }

    m := in[0]

    lt := make([]int, 0)
    gt := make([]int, 0)

    for _, v :=range in[1:] {
        if v < m {
            lt = append(lt, v)
        } else {
            gt = append(gt, v)
        }
    }

    lt = Sort(lt)
    gt = Sort(gt)

    lt = append(lt, m)
    lt = append(lt, gt...)

    return lt
}

テストコード

import (
    "testing"
    "reflect"
)

func TestSort(t *testing.T) {
    expect := []int{1,2,3,4,5}
    actual := Sort([]int{5,4,3,2,1})
    if reflect.DeepEqual(actual, expect) {
        t.Log("Success")
    } else {
        t.Errorf("Failed: expect %s but actual is %s", expect, actual)
    }
}

これだといろんなデータパターンのテストをするのに大変なので、以下の記事を参考にSpockのあれっぽくしてみる。

qiita.com

import (
    "testing"
    "reflect"
)

type sortTest struct {
    in  []int
    out []int
}

var sortTests = []sortTest{
    {[]int{3, 2, 1}, []int{1, 2, 3}},
    {[]int{3, 3, 1}, []int{1, 3, 3}},
    {[]int{2, 1}, []int{1, 2}},
    {[]int{1, 2}, []int{1, 2}},
    {[]int{1}, []int{1}},
    {[]int{}, []int{}},
}

func TestSort(t *testing.T) {
    for _, v := range sortTests {
        expect := v.out
        actual := Sort(v.in)
        if reflect.DeepEqual(actual, expect) {
            t.Log("Success")
        } else {
            t.Errorf("Failed: expect %s but actual is %s", expect, actual)
        }
    }
}