0
0
Goprogramming~30 mins

Test-driven basics in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Test-driven basics
📖 Scenario: You are building a simple calculator function in Go. You will write the function step-by-step using test-driven development (TDD). This means you will first write tests that describe what the function should do, then write the function code to pass those tests.
🎯 Goal: Create a Go function called Add that takes two integers and returns their sum. You will write tests first, then write the function to pass those tests.
📋 What You'll Learn
Create a test function called TestAdd in a file named main_test.go.
Write a test case inside TestAdd that checks if Add(2, 3) returns 5.
Create the Add function in main.go that takes two int parameters and returns their sum.
Run the test to confirm it passes and print the result.
💡 Why This Matters
🌍 Real World
Writing tests before code helps catch mistakes early and ensures your code works as expected.
💼 Career
Test-driven development (TDD) is a common practice in software engineering jobs to improve code quality and reliability.
Progress0 / 4 steps
1
Write the test function
Create a test function called TestAdd in main_test.go. Inside it, use t.Errorf to fail the test with the message "Test not implemented". This sets up the test file.
Go
Hint

Remember to import the testing package and define TestAdd with t *testing.T parameter.

2
Write the test case for Add(2, 3)
In TestAdd, write a test case that calls Add(2, 3) and checks if the result equals 5. Use if and t.Errorf to report failure with message "Add(2, 3) = %d; want 5".
Go
Hint

Call Add(2, 3) and compare the result to 5. Use t.Errorf to show an error if they don't match.

3
Write the Add function
Create the Add function in main.go. It should take two int parameters named a and b, and return their sum as an int.
Go
Hint

Define Add with two int inputs and return their sum.

4
Run the test and print success message
Run the test using go test. Then add a main function in main.go that calls Add(2, 3) and prints the result using fmt.Println.
Go
Hint

Use fmt.Println to print the result of Add(2, 3) in main.