I have two files main.go and main_test.go
under main.go
package main
import (
"fmt"
"os"
"strconv"
)
func Sum(a, b int) int {
return a + b
}
func main() {
a, _ := strconv.Atoi(os.Args[1])
b, _ := strconv.Atoi(os.Args[2])
fmt.Println(Sum(a, b))
}
and under main_test.go I have
package main
import (
"flag"
"fmt"
"testing"
)
func TestMain(t *testing.M) {
args1 := flag.Arg(0)
args2 := flag.Arg(1)
fmt.Print(args1, args2)
os.Args = []string{args1, args2}
t.Run()
}
I am trying to run the go test by go test main_test.go -args 1 2 -v but I am not getting the output correct can anybody guide me how to write the command for the testing the main function so that it runs properly.
A Test with constant examples (test cases) would be more productive than using any interactive things in your tests because you might need it to run many times and automatically. Why aren't you doing it like my example?
main_test.go:
package main
import (
"testing"
)
func TestMain(t *testing.T) {
for _, testCase := range []struct {
a, b, result int
}{
{1, 2, 3},
{5, 6, 11},
{10, 2, 12},
} {
if Sum(testCase.a, testCase.b) != testCase.result {
t.Fail()
}
}
}
It's good to have a look at this example too: Go By Example: Testing