Explore some popular testing libraries in golang

PHPz
Release: 2023-04-05 14:08:44
Original
664 people have browsed it

Golang is a relatively young programming language, but it is already very popular among developers. Because it is particularly suitable for building high-performance web services, but also has reliability and simplicity. For an experienced developer, writing code is not difficult, but how to ensure program quality when writing code, especially how to test the code, is a key issue.

This article will explore how to test in Golang. We will introduce unit testing and integration testing. At the same time, we will also explore some popular testing libraries, including test and goconvey.

What is unit testing?

Unit testing refers to developers testing the smallest testable units in the software to ensure that they are functioning properly. In Golang, this usually refers to functions and methods.

Unit testing is automated, which means you need to write code to test your code. The code will then run and a detailed error report will be provided if the test fails. Since the tests are automated, you can run them without manual intervention.

Let's look at an example. Let's say we have a file called "adder.go" that contains a function called "Add()" that adds two numbers. The following is the content of "adder_test.go", which is used to test the "Add()" function in "adder.go":

package main

import (
    "testing"
)

func TestAdd(t *testing.T) {
    expected := 4
    actual := Add(2, 2)

    if actual != expected {
        t.Errorf("Add(): expected %d but got %d", expected, actual)
    }
}
Copy after login

The focus of unit testing is to test the behavior of the function and whether it behaves as expected consistent. In addition to testing whether the "Add()" function correctly calculates the sum of two numbers, we also test whether it matches the expected value. If the test fails, we will see an error message showing the result we are looking for so we can easily find the bug and fix it.

What is integration testing?

Integration testing refers to the type of software testing used to test multiple components to check the interaction between them. For web applications, this typically involves end-to-end testing of the server to ensure that the web service is fully integrated and ready to run in a real-world environment.

In Golang, integration testing usually involves testing HTTP handlers or RPC methods. The following is the code for a sample integration test, which tests whether the HTTP handler function can handle HTTP requests correctly:

package main

import (
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestHelloHandler(t *testing.T) {
    req, err := http.NewRequest("GET", "/", nil)
    if err != nil {
        t.Fatal(err)
    }

    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(HelloHandler)

    handler.ServeHTTP(rr, req)

    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }

    expected := "Hello, World!"
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}
Copy after login

For integration testing, we usually use the httptest package to handle such requests. It allows us to create a dummy HTTP request and pass it through the web service we want to test.

Testing library in Golang

testing

testing is the official testing framework of the Go language. The framework is built into the Go language’s standard library and therefore does not require any additional imports. It provides some simple functions and types for writing unit and integration tests.

The following is a sample code from the testing library, which tests a function called "Square()":

package main

import (
    "testing"
)

func TestSquare(t *testing.T) {
    cases := []struct {
        name         string
        input, want  int
    }{
        {
            "positive",
            3,
            9,
        },
        {
            "zero",
            0,
            0,
        },
        {
            "negative",
            -2,
            4,
        },
    }

    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            got := Square(tc.input)
            if got != tc.want {
                t.Errorf("For (%d), got (%d), expected (%d)",
                    tc.input, got, tc.want)
            }
        })
    }
}
Copy after login

Now, the testing library provides us with a convenience function that allows us to use Multiple test cases run the same test equation. This is the t.Run() function, which will create a child test and associate it with our parent test. Which version of Square() performed best across all test cases? We can find out by running separate tests for each test case with t.Run().

goconvey

Goconvey is a popular third-party testing framework that allows you to test how functions and methods work and quickly understand which tests pass and which tests fail.

Unlike testing libraries, goconvey lets you create the context of your test code by copying text, rather than creating a function. This means you don't have to write the same test case code every time. goconvey automatically generates tests and provides a summary of results, making it easier to use.

The following is sample code from the goconvey framework, which tests a function called "Greet()":

package main

import (
    . "github.com/smartystreets/goconvey/convey"
    "testing"
)

func TestGreet(t *testing.T) {
    Convey("Given a name and a greeting message", t, func() {
        name := "John"
        greeting := "Hello"

        Convey("When we pass the name and greeting to Greet()", func() {
            message, err := Greet(name, greeting)

            Convey("Then there is no error", func() {
                So(err, ShouldBeNil)

                Convey("And the message contains the name and greeting", func() {
                    So(message, ShouldEqual, "Hello, John")
                })
            })
        })
    })
}
Copy after login

Please note that we used "Convey" instead of "Run" or "Test" ” to describe the scenario we want to test. This is because goconvey uses a Behavior-driven development style. In our example, "Convey()" is a function that describes a unit test scenario. Each scenario describes a different situation that could occur and defines the results to be checked. Similar to the testing library, we can use functions such as So/ShouldBeNil to modify the results and ensure that our expectations are met.

Conclusion

Unit testing and integration testing are an integral part of the Golang development process. They help ensure that our code works as expected. testing and goconvey are two powerful libraries that provide some fast and easy-to-use functions and types for testing functions and methods. If you haven't used these libraries and are interested in learning more about testing in Go, give them a try.

The above is the detailed content of Explore some popular testing libraries in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!