To test you likely just need to split the code into two files - one is your main code for the package and the other is your test. Eg I might do:
mkdir -p $GOPATH/github.com/joncalhoun/something
nano $GOPATH/github.com/joncalhoun/something/str.go
Note: Replace nano
with whatever text editor you use
Then add the following code to it:
package something
func IntSliceToString(sl []int) string {
var str string
for _, v := range sl {
str = str + string(v)
}
return str
}
Then for the test create a file named str_test.go
in the same directory.
nano $GOPATH/github.com/joncalhoun/something/str_test.go
And add the following source code.
package something
import "testing"
func TestIntSliceToString(t *testing.T) {
expected := "1723100500"
result := IntSliceToString([]int{17, 23, 100501})
if expected != result {
t.Error("expected", expected, "have", result)
}
}
Now to run the tests you would do something like go test
in the directory with the code, along with any optional flags you want to specify.
cd $GOPATH/github.com/joncalhoun/something
go test -v
This will run tests and give you output like:
=== RUN TestIntSliceToString
--- FAIL: TestIntSliceToString (0.00s)
str_test.go:9: expected 1723100500 have 𘢕
FAIL
exit status 1
FAIL github.com/joncalhoun/something 0.005s
The failed test suggests that your code is incorrect (which it is).
In your code you are converting an integer type into a string type without actually changing the data. How you represent “17” in a string is very different from how 17
is represented in an integer. What you really need is something like either the Atoi
function (https://golang.org/pkg/strconv/#Atoi) or to use fmt.Sprintf
to get a string representation of your integer. Either will work and which is best depends on your situation and your needs.