0
0
Goprogramming~20 mins

Why testing is required in Go - See It in Action

Choose your learning style9 modes available
Why Testing is Required
📖 Scenario: Imagine you are building a small calculator program in Go. You want to make sure it adds numbers correctly every time. Testing helps you check that your program works as expected before you share it with others.
🎯 Goal: You will create a simple function to add two numbers, then write a test to check if the function returns the correct result. This will show why testing is important to catch mistakes early.
📋 What You'll Learn
Create a function called Add that takes two integers and returns their sum.
Create a test function called TestAdd to check if Add returns the correct sum.
Use the Go testing package to write the test.
Run the test and see the output.
💡 Why This Matters
🌍 Real World
Testing is used in real software projects to make sure programs behave correctly before users see them.
💼 Career
Knowing how to write and run tests is a key skill for software developers to deliver reliable and bug-free applications.
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 integer parameters and return their sum using return a + b.

2
Set up the test function
Import the testing package and write a test function called TestAdd that takes a parameter t of type *testing.T.
Go
Hint

Use import "testing" and define func TestAdd(t *testing.T) to start your test.

3
Write the test logic
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

Call Add(2, 3), compare with 5, and use t.Errorf to show an error if it is wrong.

4
Run the test and see the output
Run the test using go test in your terminal. Write a main function that prints Add(2, 3) to show the function works outside the test.
Go
Hint

Use fmt.Println(Add(2, 3)) inside main to print the sum.