func TestAdd(t *testing.T) { result := add(2, 3) if result != 5 { t.Errorf("Expected 5, but got %d", result) } t.Logf("Addition test passed!") } func add(a, b int) int { return a + b }
func TestSquare(t *testing.T) { testCases := []struct { input int expected int }{ {2, 4}, {-3, 9}, {0, 0}, } for _, tc := range testCases { result := square(tc.input) if result != tc.expected { t.Errorf("Expected %d, but got %d", tc.expected, result) } t.Logf("Square test for input %d passed!", tc.input) } } func square(n int) int { return n * n }In this example, the `TestSquare` function is used to test the `square` function, which should square an integer. The test uses a slice of struct literals to create test cases for the function. The for loop iterates over these test cases and tests each one using the `square` function. If the result is not equal to the expected value, an error message is printed using `t.Errorf`. If the test passes, the `t.Logf` method is used to log a success message. The package library for these examples is the built-in `testing` package in Go.