0
0
Goprogramming~10 mins

Writing basic test functions in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Writing basic test functions
Write test function with prefix Test
Use *testing.T parameter
Call function to test
Check result with if condition
Call t.Error or t.Fail if test fails
Run tests with 'go test'
See pass/fail output
This flow shows how to write a test function in Go, check results, and report failures using the testing package.
Execution Sample
Go
func TestAdd(t *testing.T) {
  result := Add(2, 3)
  if result != 5 {
    t.Error("Expected 5, got", result)
  }
}
A simple test function that checks if Add(2, 3) returns 5 and reports an error if not.
Execution Table
StepActionEvaluationResult
1Call TestAdd with *testing.TN/ATest function starts
2Call Add(2, 3)Add returns 5result = 5
3Check if result != 55 != 5 is falseNo error reported
4Test function endsN/ATest passes
💡 Test ends after checking condition; no error means test passes
Variable Tracker
VariableStartAfter Step 2Final
resultundefined55
Key Moments - 3 Insights
Why must the test function name start with 'Test'?
Go's test runner looks for functions starting with 'Test' to know which functions to run as tests, as shown in step 1 of the execution_table.
What happens if the condition in the if statement is false?
If the condition is false (like in step 3), t.Error is not called, so the test passes silently.
Why do we pass *testing.T as a parameter?
The *testing.T parameter provides methods like Error to report failures, as used in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'result' after step 2?
A5
Bundefined
C0
Derror
💡 Hint
Check the 'Evaluation' and 'Result' columns in row 2 of the execution_table.
At which step does the test report an error if the result is wrong?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Evaluation' columns in step 3 where the condition is checked.
If the Add function returned 4 instead of 5, what would happen in the execution_table?
ATest function would not run
BStep 3 condition would be true and t.Error called
CStep 2 would fail to assign result
DTest would pass anyway
💡 Hint
Refer to step 3 where the condition checks if result != 5.
Concept Snapshot
func TestXxx(t *testing.T) {
  result := FunctionToTest(args)
  if result != expected {
    t.Error("message", result)
  }
}
Run tests with 'go test' command.
Full Transcript
In Go, test functions must start with 'Test' and take a *testing.T parameter. Inside, you call the function you want to test and check its result. If the result is not what you expect, call t.Error to report failure. The test runner runs all such functions and shows pass or fail. This example tests Add(2,3) expecting 5. The execution steps show calling the test, running Add, checking the result, and passing the test if no error is reported.