课程: Hands-On Introduction: Go

Writing simple tests, setup, and teardown - Go教程

课程: Hands-On Introduction: Go

Writing simple tests, setup, and teardown

- Go Standard Library comes with a built-in testing package that you can use to test your code. Writing tests with this testing package is as simple as creating a file whose name ends in underscore test dot go and that contains functions whose names begin with the capitalized test. This documentation example illustrates the simplicity quite well. Let's switch back to our project and write our own tests. We'll work with code in our main package to keep things simple. We've got a familiar bit of code here the generic sum function from the chapter on generics. Let's write a unit test for it. We'll switch over to the main underscore test dot go file and just to verify that it is in the same location as the main dot go, see these two are right next to each other under the same directory. Now we'll write our test function starting with the name test. Func test. We'll call it test sum and we'll accept a pointer to testing dot T. The function returns nothing. We'll now capture a variable for a sum operation, specify what we want and then do a comparison between what we got and what we want. If that comparison fails, we'll consider the test a failure and use the T variable to call an error F function with some output that helps us understand why the test failed. There are lots of ways to fail a test using a testing package that we won't cover here, but that you know how to learn more about. Let's run our test from the command line. We'll use Go test as part of the Go tool chain and specifying our test location. When you start that go here to ensure that all the go files in that directory are included. At first, it may not appear as though much has happened, but our tests ran. Let's make the output a bit more verbose. We'll add a dash V after go test and there we go. Moving forward, I'll be using the helpers that appear at the top of the functions inside of the editor, like so. When you need to run code before and after your test suite runs you can use a special function called Test Main to set these up. Scroll down here line 16 and add a function Test main. The function accepts a pointer to testing dot m and we must remember to call the run function on it. Otherwise, our tests won't run. We can then write code above and below this call to M dot run for your setup and test that one respectively. Let's run our test and you can see here's the output. The setup is run, our tests are run and the tear down is run. Our setup and test on are executed around our test suite. If you need per test set up in tear down you'll need to simply do those in your test directly and not through something like test dot main. Let's move on to a must know testing technique next.

内容