TDD of go language test

1. TDD understanding

TDD definition

TDD is test-driven development (Test-Driven Development) of the title, is a core agile development practices and technologies, but also a design methodology. The principle of TDD is to write unit test case code before developing functional code, and the test code determines what product code needs to be written. Although TDD is the core practice of agile methods, it is not only applicable to XP (Extreme Programming), but also applicable to other development methods and processes.
The basic idea of ​​TDD is to promote the entire development through testing, but test-driven development is not just a simple test work, but a process of quantifying requirements analysis, design, and quality control. The basic flow chart is as follows:
Insert picture description here


Complete the "Iteration" chapter of the tutorial based on the TDD cycle

1. Writing the test
In the test, we test the Repeat function, and hope to return a string through the Repeat function, which contains 5 incoming character parameters.
Write the test code in the iteration/repeat_test.go file as follows:

package iteration

import "testing"

func TestRepeat(t *testing.T) {
    
    
    repeated := Repeat("a")
    expected := "aaaaa"

    if repeated != expected {
    
    
        t.Errorf("expected '%q' but got '%q'", expected, repeated)
    }
}

2. Run the test and get the result of failure.
Since the Repeat function is not defined, an error will be reported when the test is run. The results of the run test are as follows:
Insert picture description here
3. Write a compilable implementation and
strictly follow the steps and principles of the TDD method. Now just make the code compilable. So you can check whether the test case can pass.
Write the code in the iteration/repeat.go file as follows:

package iteration

func Repeat(character string) string {
    
    
    return ""
}

4. Run the test to get the failed result
. The Repeat function has been defined here, and then the specific content in the test code can be further executed, but the result of the running test will also be wrong. This is because of the problem of the Repeat function definition. The running test results are as follows:
Insert picture description here
5. Writing the realization that can pass the test.
According to the running test results of the previous step and the requirements of the test code, rewrite the Repeat function that meets the test requirements. Since the specific content of the test code is already known, the requirements can be passed in this step. Write out the Repeat function.
Rewrite the code in the iteration/repeat.go file as follows:

package iteration

func Repeat(character string) string {
    
    
	var repeated string
	for i := 0; i < 5; i++ {
    
    
		repeated = repeated + character
	}
	return repeated
}

6. Run the test to get a successful result
The rewriting of the Repeat function meets the needs of the test code, so running the test will get a successful result. The running test results are as follows:
Insert picture description here
7. Refactoring
Although the code in the code repeat.go file has passed the test, there are still many problems with the standardization and conciseness of the code, so we need to refactor the code and refactor the code requirements Simplify the code as much as possible without changing the logic and function of the code. The purpose of simplification is to enhance the readability of the code, speed up the execution of the code, and so on. A common simplification method is to reuse code (define frequently used variables, constants, and functions separately, so that you can call these variables, constants, and functions in various places). Refactor repeat.go here as follows:

package iteration

const repeatCount = 5

func Repeat(character string) string {
    
    
	var repeated string
	for i := 0; i < repeatCount; i++ {
    
    
		repeated += character
	}
	return repeated
}

Benchmarks (benchmarks)

After completing the examples in the "Iteration" chapter based on the TDD cycle, you can also write benchmark tests on this basis. Writing benchmarks in Go is another first-level feature of the language, which is very similar to writing tests in TDD.
Add the following benchmark code on the basis of iteration/reoeat_test.go:

func BenchmarkRepeat(b *testing.B) {
    
    
    for i := 0; i < b.N; i++ {
    
    
        Repeat("a")
    }
}

testing.B gives you access to cryptically named bN. When the benchmark is running, the code runs bN times and measures how long it takes. The number of code runs will not affect you, the testing framework will choose the best value it thinks so that you can get more reasonable results.


Use go test -bench=. to run the benchmark test. (If you use go test -bench="." in the Windows Powershell environment). The test results are as follows:
Insert picture description here

2. Complete the exercises in the "Iteration" chapter of this tutorial

Modify the test code so that the caller can specify the number of character repetitions, and then fix the code

Here requires the Repeat function to specify the number of character repetitions by passing in a parameter. We modify the test code as follows:

package iteration

import "testing"

func TestRepeat(t *testing.T) {
    
    
	repeated := Repeat("a", 6)
	expected := "aaaaaa"

	if repeated != expected {
    
    
		t.Errorf("expected %q but got %q", expected, repeated)
	}
}

Because the parameters of the Repeat function have changed, running the test will get a failed result. The test results are as follows:
Insert picture description here
Modify the main code to make the test pass, the code is modified as follows:

package iteration

//Repeat a string with 
func Repeat(character string, Readcount int) string {
    
    
	var repeated string
	for i := 0; i < Readcount; i++ {
    
    
		repeated += character
	}
	return repeated
}

Running the test at this time will get a successful result. Run the test as follows:

Insert picture description here

Write an ExampleRepeat to improve your function documentation

In order to improve the function documentation, we also need to write a sample test. Add an example test function ExampleRepeat to the repeat_test.go file. The function code is as follows:

func ExampleRepeat() {
    
    
	str := Repeat("b", 10)
	fmt.Println(str)
	//Output: bbbbbbbbbb
}

The results of the running test are as follows:
Insert picture description here
This shows that the test function and the sample test function are executed successfully. Check the function documentation at this time and find that the function documentation already contains a sample test part.
Insert picture description here


Take a look at the strings package. Find functions you think might be useful and write some tests for them

Check the strings package documentation, some functions are as follows:

Insert picture description here


Write and test the Compare and ToLower functions. The test code can be simply written as follows:

package main

import (
	"fmt"
	"strings"
)

func main() {
    
    

	fmt.Println("compare:", strings.Compare("a", "b")) //Output: -1

	fmt.Println("tolower:", strings.ToLower("ABC")) // Output: abc
}

The results of running the test code are as follows:
Insert picture description here

Three, TDD application: Go language to achieve bubble sorting algorithm

Bubble sorting algorithm based on TDD cycle completion

1. Write the test
Write the test code in the BubbleSort/BubbleSort_test.go file as follows:

package BubbleSort

import (
	"testing"
)

func TestBubbleSort(t *testing.T) {
    
    
	arr := [10]int{
    
    7, 6, 3, 9, 5, 0, 1, 4, 2, 8}
	sorted := BubbleSort(arr)
	expected := [10]int{
    
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

	for i := 0; i < 10; i++ {
    
    
		if sorted[i] != expected[i] {
    
    
			t.Errorf("expected %v but got %v", expected, sorted)
		}
	}
}

2. Run the test and get the failed result.
Because the BubbleSortt function is not defined, an error will be reported when the test is run at this time. The run test results are as follows:
Insert picture description here

3. Write a compilable implementation.
Strictly follow the steps and principles of the TDD method. Now you only need to make the code compilable, so you can check whether the test case can pass.
Write the code in the BubbleSort/BubbleSort.go file as follows:

package BubbleSort

func BubbleSort(arr [10]int) [10]int {
    
    
	return arr
}

4. Run the test and get the failed result
. The BubbleSort function has been defined here, and then the specific content in the test code can be further executed, but the result of the running test will be wrong. This is because of the BubbleSort function definition problem. The test results are as follows:
Insert picture description here

5. Write the realization that can pass the test.
According to the running test results of the previous step and the requirements of the test code, rewrite the BubbleSort function that meets the test requirements. Since you already know the specific content of the test code, you can write the BubbleSort function according to the requirements in this step.
Rewrite the code in the BubbleSort/BubbleSort.go file as follows:

package BubbleSort

//BubbleSort sort a array
func BubbleSort(arr [10]int) [10]int {
    
    
	for i := 0; i < 9; i++ {
    
    
		for j := 0; j < 9-i; j++ {
    
    
			if arr[j] > arr[j+1] {
    
    
				temp := arr[j]
				arr[j] = arr[j+1]
				arr[j+1] = temp
			}
		}
	}
	return arr
}

6. Run the test to get a successful result
. Rewriting the BubbleSort function meets the needs of the test code, so running the test will get a successful result. The results of the running test are as follows:
Insert picture description here
7. Refactoring
According to the method mentioned above , refactoring BubbleSort.go is as follows:

package BubbleSort

const count = 10

//BubbleSort sort a array
func BubbleSort(arr [10]int) [10]int {
    
    
	for i := 0; i < count-1; i++ {
    
    
		for j := 0; j < count-1-i; j++ {
    
    
			if arr[j] > arr[j+1] {
    
    
				temp := arr[j]
				arr[j] = arr[j+1]
				arr[j+1] = temp
			}
		}
	}
	return arr
}

Benchmarks (benchmarks)

Add the following benchmark code on the basis of BubbleSort/BubbleSort.go:

func BenchmarkBubbleSort(b *testing.B) {
    
    
	for i := 0; i < b.N; i++ {
    
    
		arr := [10]int{
    
    7, 6, 3, 9, 5, 0, 1, 4, 2, 8}
		BubbleSort(arr)
	}
}

Use go test -bench=. to run the benchmark test. (If you use go test -bench="." in the Windows Powershell environment). The test results are as follows:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45960131/article/details/108721261
TDD