-1

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.

Mesc
  • 21
  • 1
  • 9
  • 3
    Your test doesn't test anything. You can either capture stdout for testing (google it), or better, create a function `add` that accepts two numbers and returns the sum, and call it from `main`. You can then test `add` directly. – Abhijit Sarkar Jan 10 '22 at 07:40
  • Thanks @AbhijitSarkar , I am new to writing unittest in golang . I had the query of how to write the code for main function as we are reading the arguments inside the main function. – Mesc Jan 10 '22 at 07:43

2 Answers2

0

here is the code to test the main function with arguments passed to it:

func TestMain(m *testing.M) {
    a := make([]string, len(os.Args)+2)
    a[0] = os.Args[0]
    a[1] = "first arg"
    a[2] = "second arg"
    copy(a[3:], os.Args[1:])

    os.Args = a

    main()
}
evg_io
  • 1
-1

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

Navid Nabavi
  • 532
  • 6
  • 12