← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 8 of 10

testing Package से Tests लिखना

Go का testing package आपको छोटे checkup scripts लिखने देता है जो हर बार कुछ बदलने पर अपने आप verify करते हैं कि आपका code अब भी सही काम करता है।
Syntax
go
// file_test.go
func TestName(t *testing.T) {
    got := function(input)
    if got != want {
        t.Errorf("got %v, want %v", got, want)
    }
}

Writing a Basic Test

एक test function TestXxx नाम का होता है, एक *testing.T लेता है, और t.Errorf (या t.Fatalf) call करता है जब एक expected result actual वाले से मेल न खाए। यहां वही check सीधे main में demonstrate किया गया है ताकि यह चल सके और output print कर सके।

Note: चूंकि Judge0 एक single main.go चलाता है, यह उदाहरण assertion pattern दिखाने के लिए main() के अंदर test logic simulate करता है -- असली tests एक _test.go file में रहते हैं जो 'go test' से चलाई जाती है।

उदाहरण: Writing a Basic Test

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function add
func add(a, b int) int {
	// Send a + b back to the caller
	return a + b
}

// main is where the program starts running
func main() {
	// Short declaration: create got and infer the type
	got := add(2, 3)
	// Short declaration: create want and infer the type
	want := 5
	// Check whether got != want
	if got != want {
		fmt.Printf("FAIL: add(2,3) = %d, want %d\n", got, want)
	} else {
		fmt.Println("PASS: add(2,3) =", got)
	}
}

Table-Driven Tests

एक table-driven test input/expected-output cases की एक slice define करता है और उन पर loop करता है, हर एक के लिए एक जैसा assertion logic चलाते हुए -- test code दोहराए बिना कई cases cover करने का idiomatic Go तरीका।

उदाहरण: Table-Driven Tests

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function square
func square(n int) int {
	// Send n * n back to the caller
	return n * n
}

// main is where the program starts running
func main() {
	// Short declaration: create cases and infer the type
	cases := []struct {
		input, want int
	}{
		{2, 4},
		{3, 9},
		{5, 25},
	}
	// Loop over cases; the blank identifier _ ignores the index
	for _, c := range cases {
		// Short declaration: create got and infer the type
		got := square(c.input)
		status := "PASS"
		if got != c.want {
			status = "FAIL"
		}
		fmt.Printf("%s: square(%d) = %d\n", status, c.input, got)
	}
}

Errorf vs Fatalf

t.Errorf test को failed चिह्नित करता है लेकिन इसे चलते रहने देता है (एक test में कई issues report करने के लिए उपयोगी), जबकि t.Fatalf इसे failed चिह्नित करता है और तुरंत उस test function को रोक देता है, तब उपयोगी जब जारी रहना panic का कारण बनता।

उदाहरण: Errorf vs Fatalf

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define the function divide
func divide(a, b int) (int, bool) {
	// Check whether b == 0
	if b == 0 {
		// Send 0, false back to the caller
		return 0, false
	}
	// Send a / b, true back to the caller
	return a / b, true
}

// main is where the program starts running
func main() {
	// Check whether _, ok := divide(10, 0); !ok
	if _, ok := divide(10, 0); !ok {
		fmt.Println("caught invalid division, stopping this check (like t.Fatalf)")
	}
	fmt.Println("continuing with other checks (like t.Errorf would allow)")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी test function को exact Test prefix (और capitalized) के बिना नाम देना, जिसे 'go test' discover और चलाएगा नहीं।
  2. यह भूल जाना कि किसी test function को बिल्कुल एक parameter, *testing.T, लेना चाहिए, नहीं तो यह एक valid test के रूप में पहचाना नहीं जाएगा।
  3. किसी test द्वारा spawn किए goroutine के अंदर t.Fatal उपयोग करना, जो असुरक्षित है -- t methods को test के अपने goroutine से call किया जाना चाहिए।
चैप्टर सारांश
  • Test functions _test.go files में रहते हैं और TestXxx नाम के होते हैं, एक *testing.T parameter लेते हुए।
  • t.Errorf एक failure report करता है लेकिन test को जारी रहने देता है; t.Fatalf एक failure report करता है और तुरंत रुक जाता है।
  • 'go test' किसी package में हर TestXxx function को अपने आप discover और चलाता है।
  • input/expected pairs की एक slice पर iterate करने वाले Table-driven tests idiomatic Go testing style हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.