当前位置:网站首页>Go unit test
Go unit test
2022-06-23 09:43:00 【51CTO】
The test is divided into 4 A hierarchical
- unit testing : Test the code
- Integration testing : Test the interface of a service
- End to end testing ( Link test ): Input test cases from the entrance of a link , Verify the output system results
- UI test

Common mistakes :
- There is no assertion . A test without assertion is soulless . Characteristics of single test :
- A:(Automatic, automation ): Unit tests should be executed fully automatically , And non-interactive
- I:(Independent, independence ): To ensure that unit tests are stable, reliable and easy to maintain , Unit test cases must never call each other , Nor can it depend on the order of execution .
- R:(Repeatable, repeatable ): Unit tests are often placed in continuous integration , Every time we have code check in Unit tests will be executed .
Single measurement
Code bug It's always inevitable , The earlier the problem is found, the lower the cost of solving it , Single test can expose errors as early as possible . The way to improve code , Make the project more high-quality delivery . There are at least three advantages :
- Improve code quality Writing a single test is part of the self-test , Add corresponding single test when writing new code , Can help us find most of bug, It helps to reduce the adjustment during joint commissioning , Improve the efficiency of joint commissioning .
- Spend less time on functional testing The cost of functional testing is relatively high , Because it is often necessary to perform a series of operations to verify whether the results meet expectations . If a problem is found , Communication and retesting often take a lot of time .
- Spend less time on regression testing Regression testing is designed to avoid introducing... When making changes to an application bug. Testers should not only test their new features , Also test pre-existing features , To verify that the previously implemented features are still working as expected . Pass the unit test , After each build , Rerun the entire test process , To ensure that new code does not break existing functionality
- Test exception scenarios Some unusual scenes QA Poor construction , For example, whether the concurrent disbursement is safe , Transaction exception related tests, etc . Problems often occur in these abnormal scenarios , It may cause online problems or even accidents . And the unit test can pass mock It is convenient to simulate various abnormal scenarios .
Go Unit test tools
gomonkey
introduce gomonkey It has the following benefits :
- Isolate the code under test
- Speed up test execution
- Make execution certain
- Simulate special situations
Function list
- Support for a function to play a pile
- Support for a function to play a specific pile sequence
- Support a pile for a member method
- Support a specific sequence of piles for a member method
- Support a pile for a function variable
- Support for a function variable to play a specific pile sequence
- Supports piling for an interface
- It supports driving a specific pile sequence for an interface
- Support a pile for a global variable
Functions , For variables mock Implementation principle gostub It's all through reflect Package implementation . except mock Variable ,gomonkey It can also be direct mock The export function / Method 、mock The non exported function of the package where the code is located
Go monkey Permission Denied Solution :https://github.com/eisenxp/macos-golink-wrapper
Download the file , And then again cp
gomonkey The following are provided mock Method :
- ApplyGlobalVar(target, double interface{}): Use reflect package , take target Is changed to double
- ApplyFuncVar(target, double interface{}): Check target Is it a pointer type , And double Whether the function declaration is the same , Last call ApplyGlobalVar
- ApplyFunc(target, double interface{}): modify target The machine instructions for , Jump to double perform
- ApplyMethod(target reflect.Type, methodName string, double interface{}): modify method The machine instructions for , Jump to double perform
- ApplyFuncSeq(target interface{}, outputs []OutputCell): modify target The machine instructions for , Jump to gomonkey A generated function executes , Each call will start from outputs Take out a value and return
- ApplyMethodSeq(target reflect.Type, methodName string, outputs []OutputCell): modify target The machine instructions for , Jump to gomonkey A generated method executes , Each call will start from outputs Take out a value and return
- ApplyFuncVarSeq(target interface{}, outputs []OutputCell):gomonkey Generate a function to return in sequence outputs The value in , call ApplyGlobalVar
gomonkey Possible causes of pile driving failure
- gomonkey It's not concurrent security . If there are multiple concurrent piling on the same target , You need to exit the previous cooperation process gracefully .
- The piling target is an inline function or member method . You can use the command line arguments -gcflags=-l (go1.10 Before the release ) or -gcflags=all=-l(go1.10 Version and after ) Turn off inline optimization .
- gomonkey Piling failed for private member method .go1.6 Version of the reflection mechanism supports querying private member methods , and go1.7 And later versions do not support , So when users use go1.7 And later versions ,gomonkey Piling on private member methods triggers an exception .
goconvey
Stake a global variable
package unittest
import (
"testing"
"github.com/agiledragon/gomonkey"
"github.com/smartystreets/goconvey/convey"
)
var num = 10 // Global variables
func TestApplyGlobalVar(t *testing.T) {
convey.Convey("TestApplyGlobalVar", t, func() {
convey.Convey("change", func() {
patches := gomonkey.ApplyGlobalVar(
&num, 150)
defer patches.Reset()
convey.So(num, convey.ShouldEqual, 150)
})
convey.Convey("recover", func() {
convey.So(num, convey.ShouldEqual, 10)
})
})
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
Execution results :
For a function
func networkCompute(a, b int) (int, error) {
// do something in remote computer
c := a + b
return c, nil
}
func Compute(a, b int) (int, error) {
sum, err := networkCompute(a, b)
return sum, err
}
func TestFunc(t *testing.T) {
// mock 了 networkCompute(), The calculation result is returned 2
patches := gomonkey.ApplyFunc(networkCompute, func(a, b int) (int, error) {
return 2, nil
})
defer patches.Reset()
sum, err := Compute(1, 2)
println("expected %v, got %v", 2, sum)
if sum != 2 || err != nil {
t.Errorf("expected %v, got %v", 2, sum)
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
result :
You can see the results above , Failed to execute ,mock No success .
Sometimes I meet mock Failure situation , This problem is usually caused by inlining .
What is inline ?
In order to reduce the stack overhead during function calls , For short functions , At compile time , Code that directly embeds the call .
We disable inlining , And then execute ,go test -v -gcflags=-l mock_func_test.go
Execution results :
about go 1.10 The following versions , You can use -gcflags=-l Disable inline , about go 1.10 And above , have access to -gcflags=all=-l. But now it is used , Fine . About gcflags Usage of , have access to go tool compile --help see gcflags Meaning of each parameter
Welcome to the official account : The path of programmer wealth and freedom

official account : The path of programmer wealth and freedom
Pay attention to our , Learn more about
Reference material
- https://books.studygolang.com/The-Golang-Standard-Library-by-Example/chapter09/09.1.html
- https://github.com/agiledragon/gomonkey
- http://yangxikun.github.io/golang/2021/06/19/golang-mock.html
- https://www.sofineday.com/golang-unit-test.html
- https://www.sofineday.com/golang-unit-test.html#%E8%A1%A1%E9%87%8F%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95%E4%BB%A3%E7%A0%81%E7%9A%84%E6%88%90%E6%9C%AC
- https://www.sofineday.com/golang-unit-test.html#%E8%A1%A1%E9%87%8F%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95%E4%BB%A3%E7%A0%81%E7%9A%84%E6%88%90%E6%9C%AC
边栏推荐
猜你喜欢

web--信息泄漏
Redis learning notes - redis and Lua
![[plugin:vite:import-analysis]Failed to resolve import “@/“ from ““.Does the file exist](/img/1f/dde52dc63de58d67f51161e318a9fb.png)
[plugin:vite:import-analysis]Failed to resolve import “@/“ from ““.Does the file exist

必须知道的RPC内核细节(值得收藏)!!!
![[网鼎杯 2020 青龙组]AreUSerialz](/img/38/b67f7a42abec1cdaad02f2b7df6546.png)
[网鼎杯 2020 青龙组]AreUSerialz
Redis learning notes - data type: hash
![[GXYCTF2019]BabyUpload](/img/82/7941edd523d86f7634f5532ab97717.png)
[GXYCTF2019]BabyUpload

给RepVGG填坑?其实是RepVGG2的RepOptimizer开源
![[plugin:vite:import-analysis]Failed to resolve import “@/“ from ““.Does the file exist](/img/1f/dde52dc63de58d67f51161e318a9fb.png)
[plugin:vite:import-analysis]Failed to resolve import “@/“ from ““.Does the file exist
![[GYCTF2020]Blacklist](/img/a8/0f7231e5c498e6c89ff2e3bcb122f2.png)
[GYCTF2020]Blacklist
随机推荐
[GXYCTF2019]BabyUpload
xml相关面试题
给RepVGG填坑?其实是RepVGG2的RepOptimizer开源
Fill the pit for repvgg? In fact, it is the repoptimizer open source of repvgg2
Qiming Xingchen Huadian big data quantum security innovation laboratory was unveiled and two black technology products were released
Leetcode topic analysis contains duplicate III
[MRCTF2020]Ez_ bypass
Precautions for map interface
Difference between global shutter and roller shutter
Three methods to find the limit of univariate function -- lobida's rule and Taylor's formula
J. Med. Chem. | RELATION: 一种基于靶标结构的深度学习全新药物设计模型
Bit binding
AI system frontier dynamics issue 38: Google has abandoned tensorflow?; Four GPU parallel strategies for training large models; Father of llvm: modular design determines AI future
全局快门和卷帘快门的区别
分布式锁的三种实现方式
2022 Gdevops全球敏捷运维峰会-广州站精华回放(附ppt下载)
[GXYCTF2019]BabyUpload
J. Med. Chem. | Release: a new drug design model for deep learning based on target structure
[plugin:vite:import-analysis]Failed to resolve import “@/“ from ““.Does the file exist
16. system startup process