Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of go unit testing

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "what are the methods of go unit testing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1.gomock

Gomock simulates an object by letting the user declare an interface and then use the mockgen tool provided by gomock to generate mock object code. When you want to mock the dependent object of the code under test, you can use the mock object to simulate and record the various behaviors of the dependent object: such as the most commonly used return value, the number of calls, and so on. The text description is a little abstract and goes directly to the code:

The DickFunc in dick.go depends on the external object OutterObj, and this example shows how to use the gomock framework to control the dependent objects.

Func DickFunc (outterObj MockInterface,para int) (result int) {fmt.Println ("This init DickFunc") fmt.Println ("call outter.func:") return outterObj.OutterFunc (para)}

The mockgen tool commands are:

Mockgen-source {source_file} .go-destination {dest_file} .go

For example, this example is:

Mockgen-source src_mock.go-destination dst_mock.go

After execution, you can find the generated dst_mock.go file in the same directory, and you can see that the mockgen tool also implements the interface:

In this example, the return value is simply changed to attract more attention:

Func TestDickFunc (t * testing.T) {mockCtrl: = gomock.NewController (t) / / defer mockCtrl.Finish () mockObj: = dick.NewMockMockInterface (mockCtrl) mockObj.EXPECT (). OutterFunc (3) .return (10) result: = dick.DickFunc (mockObj,3) t.Log ("resutl:", result)}

Use the go test command to perform this single test

From the result: should have output 3, the final output is 10, similar to other languages mock framework, the production of Mock objects do not have to redefine so troublesome.

2.httpexcept

Due to the excellent encapsulation of go in network architecture, go is widely used in many network scenarios, and http protocol is an important part of it. In the face of http requests, http client can be tested, which is a special application scenario of mock.

You can easily understand it by looking at a simple example:

Func TestHttp (t * testing.T) {handler: = FruitServer () server: = httptest.NewServer (handler) defer server.Close () e: = httpexpect.New (t, server.URL) e.GET ("/ fruits"). Expect (). Status (http.StatusOK). JSON (). Array (). Empty ()}

It also supports customization of the construction of different methods (including Header,Post, etc.) and the return value Json. Check out its official website for more details.

3.testify

There is also a testify that can be said to be compatible with gocheck and gomock in "one", but the use of mock is a bit cumbersome, using inherited tetify.Mock (anonymous combination) to re-implement interfaces that require Mock, in which the user uses Called (reflection implementation) to be Mock.

"the Art of Unit testing" believes that the biggest difference between stub and mock depends on whether the object interacts with the object being tested, and the result is that the pile object will not make the test fail, it only provides dependent objects for the tested object, and does not change the test results, while mock will change the test results according to different interactive test requirements. There are so many theories, but in fact, neither of the two methods is fragmented, so the gomock framework not only simulates objects like its name, but also provides the stub of pile objects. In terms of its implementation, it is more like the injection of a pile object. But because it is compatible with a number of useful features, it is the most popular in the community.

For specific usage, please refer to its github home page.

4.go-sqlmock

Another common scenario is the interaction with the database. Go-sqlmock is a sql simulation (Mock) driver, which is mainly used to test database interaction. Go-sqlmock provides a complete transaction execution testing framework, and the latest version (16.11.02) also supports prepare parameterized commit and execution of the Mock scheme.

For example, there is a function under test:

Func recordStats (db * sql.DB, userID, productID int64) (err error) {tx, err: = db.Begin () if err! = nil {return} defer func () {switch err {case nil: err = tx.Commit () default: tx.Rollback ()} () if _ Err = tx.Exec ("UPDATE products SET views = views + 1") Err! = nil {return} if _, err = tx.Exec ("INSERT INTO product_viewers (user_id, product_id) VALUES", userID, productID) Err! = nil {return} return} func main () {db, err: = sql.Open ("mysql", "root@/root") if err! = nil {panic (err)} defer db.Close () if err = recordStats (db, 1,5); err! = nil {panic (err)}}

Single time measurement:

Func TestShouldUpdateStats (t * testing.T) {db, mock, err: = sqlmock.New () if err! = nil {t.Fatalf ("mock error:'% s'", err)} defer db.Close () mock.ExpectBegin () mock.ExpectExec ("UPDATE products") .WillReturnResult (sqlmock.NewResult (1,1) mock.ExpectExec ("INSERT INTO product_viewers") .WithArgs (2) 3) .WillReturnResult (sqlmock.NewResult (1,1)) mock.ExpectCommit () if err = recordStats (db, 2,3) Err! = nil {t.Errorf ("exe error:% s", err)} if err: = mock.ExpectationsWereMet () Err! = nil {t.Errorf ("not implements:% s", err)} / / Test rollback func TestShouldRollbackStatUpdatesOnFailure (t * testing.T) {db, mock, err: = sqlmock.New () if err! = nil {t.Fatalf ("mock error:'% s", err)} defer db.Close () mock.ExpectBegin () mock.ExpectExec ("UPDATE products") .WillReturnResult (sqlmock.NewResult (1) 1) mock.ExpectExec ("INSERT INTO product_viewers") .WithArgs (2,3) .WillReturnError (fmt.Errorf ("some error")) mock.ExpectRollback () / / execute the method under test, if err = recordStats (db, 2,3) Err = = nil {t.Errorf ("not error")} / / execute the method under test, mock object if err: = mock.ExpectationsWereMet (); err! = nil {t.Errorf ("not implements:% s", err)}} "what are the methods of go unit testing". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report