What is testing in Go, and how do I write unit tests?
Jun 20, 2025 am 08:41 AMGo's unit testing is implemented through the built-in testing package, and developers only need to follow the naming specification to write and run tests. The specific steps include: 1. Create a test file ending with _test.go; 2. Write a test function starting with Test; 3. Report an error with t.Errorf(); 4. Run the test using the go test command; 5. Test multiple use cases with table driver; 6. Run a specific test using the -run flag and obtain detailed output using the -v flag. For example, when testing the Add function, you can write the TestAdd function in math_test.go and define multiple sets of input and output through the structure for verification. In addition, you can run the specified test through go test -run TestAdd, or view detailed log information through go test -v.
Testing in Go is a built-in feature that allows developers to write and run tests directly alongside their code, without needing third-party libraries. Unit testing in Go is straightforward — it uses the testing
package and follow a simple naming convention for test functions.
How to Write a Basic Unit Test
To write a unit test in Go, you create a function in a _test.go
file. The function name must start with Test
, followed by the name of the function or method being tested.
For example, if you have a function called Add
in a file named math.go
, you'd write its test in a file named math_test.go
. Here's how a basic test might look:
package main import "testing" func TestAdd(t *testing.T) { result := Add(2, 3) expected := 5 if result != expected { t.Errorf("Expected %d, got %d", expected, result) } }
- Make sure your test files end in
_test.go
- Import the
testing
package - Use
t.Errorf()
(or similar methods) to report failures
When you're ready to run the test, use the command line:
go test
If everything passes, you'll see a PASS
message. If something fails, Go will show you exactly which test failed and why.
Table-Driven Tests: A Cleaner Way to Test Multiple Cases
Go developers often use table-driven tests to check multiple input-output combinations in a single test function. This keeps tests concise and easy to maintain.
Here's an example using the same Add
function:
func TestAdd(t *testing.T) { tests := []struct { a, b int expect int }{ {2, 3, 5}, {0, 0, 0}, {-1, 1, 0}, {100, 200, 300}, } for _, tt := range tests { result := Add(tt.a, tt.b) if result != tt.expect { t.Errorf("Add(%d, %d): expected %d, got %d", tt.a, tt.b, tt.expect, result) } } }
This approach makes it easy to:
- Add more test cases quickly
- See what's being tested at a glance
- Reuse the same assertion logic across all cases
Many Go projects prefer this style because it reduces duplication and improves readingability.
Running Specific Tests and Getting More Output
If you have a lot of tests and want to run just one, you can use the -run
flag followed by a regular expression matching the test name:
go test -run TestAdd
To get more detailed output, including logs from t.Log()
or fmt.Println()
, add the -v
flag:
go test -v
You can also combine flags:
go test -v -run TestAdd
These options are handy when debugging failing tests or when you're working on a specific part of your codebase.
That's the basics of writing and running tests in Go. It's not complicated, but there are some small rules to remember, like naming conventions and where to place your test files.
The above is the detailed content of What is testing in Go, and how do I write unit tests?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

Routing in Go applications depends on project complexity. 1. The standard library net/httpServeMux is suitable for simple applications, without external dependencies and is lightweight, but does not support URL parameters and advanced matching; 2. Third-party routers such as Chi provide middleware, path parameters and nested routing, which is suitable for modular design; 3. Gin has excellent performance, built-in JSON processing and rich functions, which is suitable for APIs and microservices. It should be selected based on whether flexibility, performance or functional integration is required. Small projects use standard libraries, medium and large projects recommend Chi or Gin, and finally achieve smooth expansion from simple to complex.

Go's flag package can easily parse command line parameters. 1. Use flag.Type() to define type flags such as strings, integers, and booleans; 2. You can parse flags to variables through flag.TypeVar() to avoid pointer operations; 3. After calling flag.Parse(), use flag.Args() to obtain subsequent positional parameters; 4. Implementing the flag.Value interface can support custom types to meet most simple CLI requirements. Complex scenarios can be replaced by spf13/cobra library.

Createormodifylaunch.jsoninVSCodebyopeningtheRunandDebugview,selectingyourenvironment(e.g.,Python,Node.js),andconfiguringitforyourtestframework(e.g.,pytest,Jest).2.Setbreakpointsinyourtestfile,selectthedebugconfiguration,andstartdebuggingwithF5topaus

The if-else statement in Go does not require brackets but must use curly braces. It supports initializing variables in if to limit scope. The conditions can be judged through the elseif chain, which is often used for error checking. The combination of variable declaration and conditions can improve the simplicity and security of the code.

In Go, constants are declared using the const keyword, and the value cannot be changed, and can be of no type or type; 1. A single constant declaration such as constPi=3.14159; 2. Multiple constant declarations in the block are such as const(Pi=3.14159; Language="Go"; IsCool=true); 3. Explicit type constants such as constSecondsInMinuteint=60; 4. Use iota to generate enumeration values, such as const(Sunday=iota;Monday;Tuesday) will assign values 0, 1, and 2 in sequence, and iota can be used for expressions such as bit operations; constants must determine the value at compile time,

gorun is a command for quickly compiling and executing Go programs. 1. It completes compilation and running in one step, generates temporary executable files and deletes them after the program is finished; 2. It is suitable for independent programs containing main functions, which are easy to develop and test; 3. It supports multi-file operation, and can be executed through gorun*.go or lists all files; 4. It automatically processes dependencies and uses the module system to parse external packages; 5. It is not suitable for libraries or packages, and does not generate persistent binary files. Therefore, it is suitable for rapid testing during scripts, learning and frequent modifications. It is an efficient and concise way of running.
