laitimes

Introduction to gocheck, a Golang unit testing framework

author:Flash Gene
Introduction to gocheck, a Golang unit testing framework

What makes a good unit testing framework?

Unit tests should verify the correctness of the program in terms of functions and parameters; After unit testing, the machine state should remain the same; The running, passing, and failing of unit tests does not depend on other tests, and the data can be artificially constructed to maintain the independence of unit tests.

Introduction to Gocheck

GoCheck is a relatively sound and simple unit testing framework in Golang language, GoCheck is rich in many functions on top of Golang's official testing package, enriching the assert assertions commonly used in unit testing, judging verbs deep multi-type comparison, string comparison and regular matching. In terms of test case organization collection, test cases are organized by suite, and setup() and teardown() at the suite level are supported. Temporary files can be created and deleted.

Use of Assert assertions

Assert 根据预期 Checker 值检验接口返回值与预期值是否匹配,如果它们不匹配,则会记录错误,测试记录不通过,并且测试用例将停止。 func (c *C) Assert(obtained interface{}, checker Checker, args ... interface{}) 那么如上代码所示的hecker接口是怎么来实现验证的呢?hecker接口是必须与 Assert 和 Check 验证方法一起使用的检查器。

First, you need to define the Checker interface, which is as follows:

Introduction to gocheck, a Golang unit testing framework

The CheckerInfo is a struct that defines the parameter format of our benchmark check.

There are a lot of checkers in the checker, which can generally meet our various checking needs under normal circumstances, such as the ErrorMatches checker to verify that the error value is non-zero and matches the provided regular expression.

The inspector code could be written like this:

Introduction to gocheck, a Golang unit testing framework

Assert check code:

Introduction to gocheck, a Golang unit testing framework

The above is a simple verification process for an interface. At the same time, the Checker inspector provides a variety of checker methods, which are listed below:

DeepEquals congruent check, the type must be the same, the check is strict, and it is rarely used because the probability of the check result failure is relatively high;

Equals is equivalent to ==check, which is a bit more lenient than congruent checksum;

FitsTypeOf to check whether the types are consistent;

HasLen 校验长度是否一致;

IsNil 校验返回值是否为空;

func not(checker Checker) reverses the logic of the provided checker, and the resulting checker will succeed if the original checker fails, and vice versa.

Use of temporary files

The temporary file method is used to meet the needs of unit tests to read and write files.

In order to follow the principle of "after the unit test, the machine state remains the same", we need to automatically clean up the data stored in a large number of temporary files used and generated in the unit test run after the unit test is completed. GoCheck can create a temporary directory that automatically deletes it at the end of the test, eliminating the need for manual cleanup.

Sample code:

Introduction to gocheck, a Golang unit testing framework

Skip the use of tests

It is used to filter the test suite, and when some test suites need to be reflected in the report in a specific situation, this method can be used to facilitate the generation of test reports and the deliberate filtering during the test process.

Tests can be skipped using SetUpSuite, the skip method in SetUpTest, or the test method itself. This allows tests to be selectively ignored based on custom factors, such as the architecture being run, the flags provided to the test, or the availability of resources (network, etc.).

For example, the following test suites will skip all tests in the suite unless the -live option is provided for testing

Sample code:

Introduction to gocheck, a Golang unit testing framework

Mock server api related test usage

In the process of testing, we often encounter the need to call external APIs, so the success of the response of the external API directly affects the success of our current unit tests, which is contrary to the independence required by unit tests, so we finally use mock data to ensure the independence of unit tests.

Using gocheck's SetUpSuite() and TearDownSuite() methods, you can create a new http test server and close it when it's finished.

Introduction to gocheck, a Golang unit testing framework

Zhihu asks a code test example

We all know that Zhihu's question and answer function is an important function of the entire Zhihu community, after the Zhihu community has questions and raises questions, how to test this part of the functional code if you want to modify the detailed description of the questions you raise? Let's talk about how to unit test this relatively small point.

1. Needs analysis

The detailed content of the test question is updated this function function, the variable has detailed content specific information, update reason, update time, update user This four changing parameters, of which the update time and update user part can be obtained directly, and it is not the focus of our single test, then the focus is left with two specific information and update reason, the update reason is a given list to filter, so it is not the focus of attention, and the specific details of updating are the focus of this test. Start analyzing the constraints of this parameter, and ask questions with a word limit of 3000 words and are mandatory.

2. Test code writing

2.1 Analysis of the libraries used

Because 3,000 words are required in the requirements, in order to ensure the consistency of the server test, you need to use the temporary file function to temporarily store the 3,000-word document and destroy it when it is used up.

2.2 Writing specific unit test functions

2.2.1 Naming conventions

For example, if the name of the tested file is question.go, then the name of the test file is question_test.go

Introduction to gocheck, a Golang unit testing framework

2.2.2 Code Writing

Create temporary folders along with temporary file contents

Introduction to gocheck, a Golang unit testing framework

When the parameters are passed, the content of the temporary file will be used as the parameter of the problem details, so that after the test code is run, the parameters of the problem details will be destroyed, and no redundant files will be generated on the server.

Introduction to gocheck, a Golang unit testing framework

3. Analysis of results

Every time the underlying database changes, the storage changes, and the interface service changes, but the data structure and call results do not change, the unit test results can be used to quickly check the existing business logic.

At last

  • The Gocheck framework is easier and faster to unit test golang code than the native unit testing framework, and the library can basically meet most use cases.
  • The entire framework itself is open source on GitHub, and you can add your own libraries.
  • For more detailed instructions, please refer to GoCheck's API documentation.

Author: icy001

Source: https://zhuanlan.zhihu.com/p/45570168

Read on