📖 Scenario: You are writing a simple Go program and want to check that your functions work correctly. Testing helps you find mistakes early and keep your code reliable.
🎯 Goal: You will create a Go test file using the testing package. You will write a basic test function to check if a simple function returns the expected result.
📋 What You'll Learn
Create a function called Add that adds two integers and returns the sum.
Create a test function called TestAdd in a separate test file.
Use the testing package and the t *testing.T parameter in the test function.
Check if Add(2, 3) returns 5 and report an error if not.
Run the test using go test and print the test result.
💡 Why This Matters
🌍 Real World
Testing is used in real software projects to make sure code works correctly before it is shared or used by others.
💼 Career
Knowing how to write and run tests is a key skill for software developers to maintain quality and avoid bugs.
Progress0 / 4 steps
1
Create the Add function
Create a function called Add that takes two integers a and b and returns their sum as an integer.
Go
Hint
Define a function with func Add(a int, b int) int and return a + b.
2
Create the test file and import testing package
Create a new file named main_test.go. In it, import the testing package and start a test function called TestAdd with parameter t *testing.T.
Go
Hint
Use import "testing" and define func TestAdd(t *testing.T).
3
Write the test logic inside TestAdd
Inside the TestAdd function, call Add(2, 3) and check if the result equals 5. If not, use t.Errorf to report an error with a message showing the expected and actual values.
Go
Hint
Compare result and expected. Use t.Errorf to show a message if they differ.
4
Run the test and print the result
Run the test using the command go test in your terminal. The test should pass without errors and print output indicating success.
Go
Hint
Open your terminal and run go test. You should see PASS if the test succeeds.
Practice
(1/5)
1. What is the main purpose of the testing package in Go?
easy
A. To compile Go programs faster
B. To create graphical user interfaces
C. To manage database connections
D. To write functions that check if your code works correctly
Solution
Step 1: Understand the role of the testing package
The testing package is designed to help write tests that verify code correctness.
Step 2: Identify the correct purpose
It does not handle GUIs, databases, or compilation speed but focuses on testing functions.
Final Answer:
To write functions that check if your code works correctly -> Option D
Quick Check:
testing package = write test functions [OK]
Hint: Testing package is for checking code correctness [OK]
Common Mistakes:
Confusing testing with UI or database packages
Thinking it speeds up compilation
Assuming it manages runtime behavior
2. Which of the following is the correct way to name a test function in Go using the testing package?
easy
A. func TestMyFunction(t *testing.T) {}
B. func testMyFunction(t *testing.T) {}
C. func MyFunctionTest(t *testing.T) {}
D. func TestingMyFunction(t *testing.T) {}
Solution
Step 1: Recall test function naming rules
Test functions must start with uppercase 'Test' followed by the function name.
Step 2: Match the correct naming pattern
Only func TestMyFunction(t *testing.T) {} uses 'Test' prefix correctly and has the right signature.
Final Answer:
func TestMyFunction(t *testing.T) {} -> Option A
Quick Check:
Test functions start with 'Test' [OK]
Hint: Test functions start with uppercase 'Test' [OK]
Common Mistakes:
Starting function name with lowercase 'test'
Placing 'Test' at the end of the function name
Using incorrect function signature
3. What will be the output when running go test on this test file?
package main
import "testing"
func TestSum(t *testing.T) {
total := 2 + 3
if total != 5 {
t.Error("Sum was incorrect")
}
}
medium
A. Syntax error: missing return type
B. FAIL
Sum was incorrect
C. PASS
ok main 0.001s
D. No tests to run
Solution
Step 1: Analyze the test logic
The test calculates 2 + 3 and checks if it equals 5, which is true, so no error is called.
Step 2: Understand test output
Since the test passes, go test reports PASS with timing info.
Final Answer:
PASS
ok main 0.001s -> Option C
Quick Check:
Correct test = PASS output [OK]
Hint: If no t.Error called, test passes [OK]
Common Mistakes:
Assuming test fails without error call
Confusing syntax errors with test failures
Expecting output when no tests exist
4. Identify the error in this test function:
package main
import "testing"
func TestMultiply(t *testing.T) {
result := 3 * 4
if result = 12 {
t.Log("Multiplication correct")
}
}
medium
A. t.Log cannot be used inside tests
B. Using assignment '=' instead of comparison '==' in if condition
C. Test function name should be lowercase
D. Missing import of fmt package
Solution
Step 1: Check the if condition syntax
The condition uses '=' which assigns value instead of '==' which compares values.
Step 2: Understand Go syntax rules
Using '=' in if condition causes a compile error; '==' is needed for comparison.
Final Answer:
Using assignment '=' instead of comparison '==' in if condition -> Option B
Quick Check:
Use '==' for comparison in if [OK]
Hint: Use '==' for comparisons, not '=' [OK]
Common Mistakes:
Confusing assignment '=' with equality '=='
Thinking t.Log is disallowed
Ignoring function naming conventions
5. You want to write a test that fails if a function returns an empty string. Which of these test snippets correctly uses the testing package to do this?
func TestNonEmpty(t *testing.T) {
result := getName()
// Which check is correct?
}
hard
A. if result == "" { t.Error("Result should not be empty") }
B. if result != "" { t.Error("Result should not be empty") }
C. if result == nil { t.Error("Result should not be empty") }
D. if result == 0 { t.Error("Result should not be empty") }
Solution
Step 1: Understand the test goal
The test must fail if the returned string is empty, so check if result equals empty string.
Step 2: Choose the correct condition
if result == "" { t.Error("Result should not be empty") } checks if result == "" and calls t.Error, which correctly fails the test on empty string.
Final Answer:
if result == "" { t.Error("Result should not be empty") } -> Option A
Quick Check:
Fail test when string is empty [OK]
Hint: Check empty string with == "" to fail test [OK]
Common Mistakes:
Using != instead of == for empty check
Comparing string to nil or 0
Not calling t.Error on failure condition
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.