0
0
Goprogramming~20 mins

Testing package overview in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing package overview
📖 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.