Post Image
  • Post Author By M-Learnify
  • Img 8 Months, 3 Weeks ago
  •   0 Likes
  • Img0
  • Img72

Test cases in go language

Go (Golang) में Testing

Go में testing के लिए कोई external framework की आवश्यकता नहीं होती। Go की standard library में ही testing package और go test command मौजूद है। इनकी मदद से आप आसानी से अपने कोड के लिए unit tests लिख और चला सकते हैं।

1. Folder और File Naming Convention

Go अपने आप test files को पहचान लेता है अगर:

  • File का नाम _test.go से समाप्त होता है
  • Test functions का नाम Test से शुरू होता है

उदाहरण directory structure:

myproject/
├── main.go
├── math.go
└── math_test.go

2. Example Code (math.go)

मान लीजिए हमारे पास एक simple function है:

package myproject

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

3. Test File बनाना (math_test.go)

package myproject

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5

    if result != expected {
        t.Errorf("Add(2, 3) = %d; want %d", result, expected)
    }
}
टिप्पणी: हर test function का नाम Test से शुरू होना चाहिए और उसमें एक parameter होता है: t *testing.T Failure को दिखाने के लिए t.Errorf() या t.Fatalf() का उपयोग करें।

4. Tests चलाना

Terminal में चलाएँ:

go test

उदाहरण output:

PASS
ok  	myproject	0.002s

Verbose mode में चलाने के लिए:

go test -v

Verbose Output Example:

=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok  	myproject	0.002s

5. कुछ उपयोगी Commands

# सभी tests चलाने के लिए
go test

# Detailed (verbose) output
go test -v or go test ./... -v

# किसी एक specific test को चलाने के लिए
go test -v -run TestAdd

# Benchmarks चलाने के लिए
go test -bench=.

# Coverage देखना
go test -cover

# Coverage report generate करना
go test -coverprofile=coverage.out
go tool cover -html=coverage.out
⚠️ नोट: सुनिश्चित करें कि आप _test.go files को उसी package में रखें जहाँ आपका test किया जाने वाला code मौजूद है। वरना Go उन tests को नहीं पहचान पाएगा।