vendredi 18 septembre 2020

Tests failing in go for joining of strings in golang

I am working on on learning about testing in go and checking out benchmarking and was trying to write tests for the following package mystr:

mystr/main.go:

package mystr

import "strings"

func Cat(xs []string) string {

        s := ""
        for _, v := range xs {
                s += v
                s += " "
        }
        return s
}

func Join(xs []string) string {
        return strings.Join(xs, " ")
}

mystr/main_test.go:

package mystr

import (
        "testing"
        "fmt"
)

func TestCat(t *testing.T) {
        type test struct {
                data []string
                answer string
        }

        tests := []test{
                test{[]string{"Hi", "There"}, "Hi There"},
                test{[]string{"Hello", "There"}, "Hello There"},
                test{[]string{"Hola", "Alli"}, "Hola Alli"},
        }

        for _, v := range tests {
                x := Cat(v.data)
                fmt.Println(x)
                if x != v.answer {
                        t.Error("For the test case", v.data, "Expected", v.answer, "Got", x)
                }
        }
}

func TestJoin(t *testing.T) {
        type test struct {
                data []string
                answer string
        }

        tests := []test{
                test{[]string{"Hi", "There"}, "Hi There"},
                test{[]string{"Hello", "There"}, "Hello There"},
                test{[]string{"Hola", "Alli"}, "Hola Alli"},
        }

        for _, v := range tests {
                x := Join(v.data)
                if x != v.answer {
                        t.Error("For the test case", v.data, "Expected", v.answer, "Got", x)
                }
        }
}

Running the tests yields:

[dkennetz@funcomp  mystr]$ go test
Hi There
Hello There
Hola Alli
--- FAIL: TestCat (0.00s)
    main_test.go:24: For the test case [Hi There] Expected Hi There Got Hi There
    main_test.go:24: For the test case [Hello There] Expected Hello There Got Hello There
    main_test.go:24: For the test case [Hola Alli] Expected Hola Alli Got Hola Alli
FAIL
exit status 1
FAIL    mystr   0.002s

The tests appear to be identical but I am sure there is something I am missing!

Aucun commentaire:

Enregistrer un commentaire