• Go for Add a Test for 20230921 Day2


    Testing your code during development can expose bugs that find their way in as you make changes. In this topic, you add a test for the Hello function.

    Go's built-in support for unit testing makes it easier to test as you go. Specifically, using naming conventions, Go's testing package, and the go test command, you can quickly write and execute tests.

    1.In the greetings directory, create a file called greetings_test.go.

    Ending a file's name with _test.go tells the go test command that this file contains test functions.

    2.In greetings_test.go, paste the following code and save the file.

    1. package greetings
    2. import (
    3. "regexp"
    4. "testing"
    5. )
    6. // TestHelloName calls greetings.Hello with a name, checking for a valid return value.
    7. func TestHelloName(t *testing.T) {
    8. name := "Gladys"
    9. want := regexp.MustCompile(`\b` + name + `\b`)
    10. msg, err := Hello("Gladys")
    11. if !want.MatchString(msg) || err != nil {
    12. t.Fatalf(`Hello("Gladys")= %q, %v, want match for %#q, nil`, msg, err, want)
    13. }
    14. }
    15. // TestHelloEmpty calls greetings.Hello with an empty string, checking for an error
    16. func TestHelloEmpty(t *testing.T) {
    17. msg, err := Hello("")
    18. if msg != "" || err == nil {
    19. t.Fatalf(`Hello("") = %q, %v, want "", error`, msg, err)
    20. }
    21. }
    • Implement test functions in the same package as the code you're testing.
    • Create two test functions to test the greetings.Hello function. Test function names have the form TestName, where Name says something about the specific test. Also, test functions take a pointer to the testing package's testing.T type as a parameter. You use this parameter's methods for reporting and logging from your test.
    • Implement two tests:
      • TestHelloName calls the Hello function, passing a name value with which the function should be able to return a valid response message. If the call returns an error or an unexpected response message (one that doesn't include the name you passed in), you use the t parameter's  Fatalf method to print a message to the console and end execution.
      • TestHelloEmpty calls the Hello function with an empty string. This test is designed to confirm that your error handling works. If the call returns a non-empty string or no error, you use the t parameter's Fatalf method to print a message to the console and end execution.

    3.At the command line in the greetings directory, run the go test command to execute the test.

    The go test command executes test functions (whose names begin with Test) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.

    4.greetings.go

    1. package greetings
    2. import (
    3. "errors"
    4. "fmt"
    5. "math/rand"
    6. )
    7. // Hello returns a greeting for the named person.
    8. func Hello(name string) (string, error) {
    9. // If no name was given, return an error with a message
    10. if name == "" {
    11. return name, errors.New("empty name")
    12. }
    13. // Create a message using a random format.
    14. message := fmt.Sprintf(randomFormat(), name)
    15. //message := fmt.Sprint(randomFormat())
    16. return message, nil
    17. }
    18. // Hellos returns a map that associates each of the named people with a greeting message.
    19. func Hellos(names []string) (map[string]string, error) {
    20. // A map to associate names with messages.
    21. messages := make(map[string]string)
    22. // Loop through the received slice of names, calling the Hello function to get a message for each name.
    23. for _, name := range names {
    24. message, err := Hello(name)
    25. if err != nil {
    26. return nil, err
    27. }
    28. // In the map, associate the retrieved message with the name.
    29. messages[name] = message
    30. }
    31. return messages, nil
    32. }
    33. // randomFormat returns one of a set of greeting messages. The returned message is selected at random.
    34. func randomFormat() string {
    35. // A slice of message formats.
    36. formats := []string{
    37. "Hi, %v. Welcome!",
    38. "Great to see you, %v!",
    39. "Hail, %v! Well met!",
    40. }
    41. // Return one of the message formats selected at random.
    42. return formats[rand.Intn(len(formats))]
    43. }

    5.Hello.go

    1. package main
    2. import (
    3. "fmt"
    4. "log"
    5. "example.com/greetings"
    6. )
    7. func main() {
    8. // Set properties of the predefined Logger, including
    9. // the log entry prefix and a flag to disable printing
    10. // the time, source file, and line number.
    11. log.SetPrefix("greetings: ")
    12. log.SetFlags(0)
    13. // A slice of names.
    14. names := []string{"Gladys", "Samantha", "Darrin"}
    15. // Request greeting messages for the names.
    16. messages, err := greetings.Hellos(names)
    17. if err != nil {
    18. log.Fatal(err)
    19. }
    20. // If no error was returned, print the returned map of
    21. // messages to the console.
    22. fmt.Println(messages)
    23. }

    The tests should pass.

    6.Break the greetings.Hello function to view a failing test.

    The TestHelloName test function checks the return value for the name you specified as a Hello function parameter. To view a failing test result, change the greetings.Hello function so that it no longer includes the name.

    In greetings/greetings.go, paste the following code in place of the Hello function. Note that the highlighted lines change the value that the function returns, as if the name argument had been accidentally removed.

    1. // Hello returns a greeting for the named person.
    2. func Hello(name string) (string, error) {
    3. // If no name was given, return an error with a message
    4. if name == "" {
    5. return name, errors.New("empty name")
    6. }
    7. // Create a message using a random format.
    8. //message := fmt.Sprintf(randomFormat(), name)
    9. message := fmt.Sprint(randomFormat())
    10. return message, nil
    11. }

    7.At the command line in the greetings directory, run go test to execute the test.

    This time, run go test without the -v flag. The output will include results for only the tests that failed, which can be useful when you have a lot of tests. The TestHelloName test should fail -- TestHelloEmpty still passes.

  • 相关阅读:
    跨平台编译GSL(Windows、Linux、MacOS环境下编译与安装)
    力合精密装备科技:操纵盒按键说明
    东南亚电商指南,卖家如何布局东南亚市场?
    LeetCode 349 两个数组的交集 - Java 实现
    HTTP响应状态码
    h264编码流程分析
    【Linux】项目部署CPU彪高如何定位
    第一次实操Python+robotframework接口自动化测试
    [Android] 隧道音画同步模式
    VI常用操作
  • 原文地址:https://blog.csdn.net/u011868279/article/details/133122333