I'm trying to make this test suite pass through the command prompt (hello-world_test.go):
package helloworld
import "testing"
func TestHelloWorld(t *testing.T) {
output := sayHello()
if "Hello, World!" != output {
t.Fatalf("output: %s
expected: Hello,World!", output)
}
}
my code is as follows (helloworld.go):
package helloworld
import "fmt"
func sayHello() {
fmt.Println("Hello, World!")
}
and the error code through the command prompt is:
C:\Users\Troy\exercism\go\hello-world\go test -v
# _/C_/Users/Troy/exercism/go/hello-world
.\hello-world_test.go:6: sayHello() used as value
FAIL _/C_/Users/Troy/exercism/go/hello-world [build failed]
I have developed (for this kind of unit test) godbg.Out()
and godbg.Err()
, two io.Writer
which, by default, are os.Stdout
and os.Stderr
.
That means I no longer use fmt.Println("Hello, World!")
.
Instead I do:
fmt.Fprintln(Out(), "Hello, World!")
That allows me, when I want to unit test that output (and not having the unit test own output filled with fmt.Println
results), to change the default io.Writer
with ones dedicated for that test, using the pdbg.SetBuffer()
function.
That way, my test becomes:
Convey("Test custom buffer reset on global pdbg", func() {
SetBuffers(nil)
fmt.Fprint(Out(), "test content")
So(OutString(), ShouldEqual, `test content`)
fmt.Fprint(Err(), "err1 cerr")
So(ErrString(), ShouldEqual, `err1 cerr`)
ResetIOs()
fmt.Fprint(Out(), "test2 content2")
So(OutString(), ShouldEqual, `test2 content2`)
fmt.Fprint(Err(), "err2 cerr2")
So(ErrString(), ShouldEqual, `err2 cerr2`)
})
I can now test outputs done on stdout or stderr by replacing (during the unit test only) those writers with my own.
Notes:
Apparently all i had to do to get the original test suite to pass was define the sayHello()
function as a string, and return its value "Hello, World!
. Also, i made lines 3 and 6 comments, as they do not affect the code directly:
package helloworld
//import "fmt"
func sayHello() string {
//fmt.Println("Hello, World!")
return "Hello, World!"
}
do the comments make the style of the code "tacky"?