DEV Community

Cover image for How to generate golang unit test code in VS code
vinay
vinay

Posted on

How to generate golang unit test code in VS code

#go
  1. Go for Function name --->right click and in that we have so many option--->select --go: generate unit test for function

main.go

package main

import "fmt"

func Add(a int, b int) int {
    return a + b
}

func main() {
    b := Add(10, 20)
    fmt.Println(b)

}
Enter fullscreen mode Exit fullscreen mode

main_test.go

package main

import "testing"

func TestAdd(t *testing.T) {
    type args struct {
        a int
        b int
    }
    tests := []struct {
        name string
        args args
        want int
    }{
        {
            name: "hello",
            args: args{
                a: 1,
                b: 2,
            },
            want: 3,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := Add(tt.args.a, tt.args.b); got != tt.want {
                t.Errorf("Add() = %v, want %v", got, tt.want)
            }
        })
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)