This is a little script in go.
package bashutil
import (
"fmt"
"github.com/nsf/termbox-go"
)
func Center(s string) {
if err := termbox.Init(); err != nil {
panic(err)
}
w, _ := termbox.Size()
termbox.Close()
fmt.Printf(
fmt.Sprintf("%%-%ds", w/2),
fmt.Sprintf(fmt.Sprintf("%%%ds", w/2+len(s)/2), s),
)
}
Can I unit test it? How can I test it? I think is a nonsense test a snippet so little. But, ... What if I would test this code? How can I test that an output is equals as I expect?
Can I test that fmt prints something like I expect?
What means "test" ?
I think "test" need have effect on output of a function.
Your function's output is Stdout, so we need get the output first.
We can do this simply:
func TestCenter(*testing.T) {
stdoutBak := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
Center("hello")
w.Close()
os.Stdout = stdoutBak
// Check output as a byte array
outstr, _ := ioutil.ReadAll(r)
fmt.Printf("%s", outstr)
}
Thus, you can check output format, spelling, etc.