0
0
Goprogramming~20 mins

Running tests in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Running tests
📖 Scenario: You are working on a small Go program that adds two numbers. To make sure your code works correctly, you want to write a simple test.
🎯 Goal: Create a Go function that adds two integers, then write a test function to check if it returns the correct result.
📋 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.
Run the test using go test and print the result.
💡 Why This Matters
🌍 Real World
Writing tests helps catch mistakes early and makes your Go programs more reliable.
💼 Career
Testing is a key skill for software developers to ensure code quality and maintainability.
Progress0 / 4 steps
1
Create the Add function
Write a function called Add that takes two integers named a and b and returns their sum as an integer.
Go
Hint

Define a function with two parameters and return their sum using return a + b.

2
Create the test function
Import the testing package and write a test function called TestAdd that takes t *testing.T as a parameter.
Go
Hint

Use import "testing" and define func TestAdd(t *testing.T).

3
Add a test case inside TestAdd
Inside TestAdd, call Add(2, 3) and check if the result equals 5. If not, use t.Errorf to report an error with the message "Add(2, 3) = %d; want 5".
Go
Hint

Store the result of Add(2, 3) in a variable, then compare it to 5. Use t.Errorf to show an error if it does not match.

4
Run the test and print the result
Run the test using the command go test in your terminal. Then write a comment showing the expected output: ok [package_name] 0.XXXs if the test passes.
Go
Hint

Open your terminal, run go test in the folder with your code, and check that the output shows ok meaning the test passed.