0
0
Goprogramming~30 mins

Writing basic test functions in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Writing basic test functions
📖 Scenario: You are working on a simple calculator package in Go. You want to make sure your addition function works correctly by writing a basic test function.
🎯 Goal: Write a basic test function in Go to check if the Add function returns the correct sum.
📋 What You'll Learn
Create a function called Add that takes two integers and returns their sum.
Create a test function called TestAdd in the same package.
Use the testing package and t.Errorf to report errors.
Test that Add(2, 3) returns 5.
💡 Why This Matters
🌍 Real World
Writing tests helps catch mistakes early and ensures your code works as expected before others use it.
💼 Career
Testing is a key skill for software developers to maintain code quality and reliability in professional projects.
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
Import testing package
Add an import statement for the testing package below the package main line.
Go
Hint

Use import "testing" to import the testing package.

3
Write the TestAdd function
Write a test function called TestAdd that takes t *testing.T as a parameter. Inside it, call Add(2, 3) and check if the result is 5. If not, use t.Errorf to report an error with the message "Add(2, 3) = %d; want 5".
Go
Hint

Define func TestAdd(t *testing.T), call Add(2, 3), and check if the result is 5. Use t.Errorf to report if not.

4
Run the test and print success message
Add a main function that calls TestAdd with a dummy *testing.T to simulate running the test, then print "Test completed".
Go
Hint

Create a main function that calls TestAdd(&testing.T{}) and prints "Test completed".