其他分享
首页 > 其他分享> > Go语言:TTD(测试驱动开发)

Go语言:TTD(测试驱动开发)

作者:互联网

学习参考网站:

学习Go迭代

https://studygolang.gitbook.io/learn-go-with-tests/go-ji-chu/iteration

for i:=0; i < length; i++ { // 注意不能使用++i

   // code 

}

 

学习Go数组与切片

https://studygolang.gitbook.io/learn-go-with-tests/go-ji-chu/arrays-and-slices

数组允许你以特定的顺序在变量中储存相同类型的多个元素

数组是值类型,而且申请的时候要明确数组的长度

var newArray = [intNum] int {初始化变量}

 

切片可以允许你申请不定长度的数组,而且它们是引用类型

var newArray = [] int {初始化变量}

 

课程要求

参考:《Learn Go with tests》
作业2:完成该教程“迭代”章节的练习,理解TDD、重构、测试、基准测试等概念。自己选择一个算法如“快排”,模仿教程内容结构,写一个Go语言某算法实现TDD实践报告

 

教程迭代的练习:

package iteration

func Repeat(character string, num int) string {
    var repeated string
    for i := 0; i < num; i++ {
        repeated = repeated + character
    }
    return repeated
}
package iteration

import "testing"

func TestRepeat(t *testing.T) {
	repeated := Repeat("a", 5)
	expected := "aaaaa"
	
	if repeated != expected {
		t.Errorf("expected '%q' but got '%q'", expected, repeated)
	}

}

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

 自己设计的符合TDD模式,快排算法

参考:

https://www.runoob.com/w3cnote/quick-sort.html

package quickSort

func adjustArr(arr [] int, findex, lindex int) (int) { // return mid
    
    mid := (int)((findex + lindex) / 2)
    temp1 := arr[findex]
    arr[findex] = arr[mid]
    arr[mid] = temp1
    
    index := findex + 1
    for i:=findex + 1; i <= lindex; i++{
        if (arr[i] < arr[findex]) {
            temp2 := arr[i]
            arr[i] = arr[index]
            arr[index] = temp2
            index++ 
        }
    }
    
    index = index - 1
    
    temp1 = arr[findex]
    arr[findex] = arr[index]
    arr[index] = temp1 
    
    return index
}

func QuickSort(arr [] int, findex, lindex int) () {
    if findex >= lindex {
        return 
    }
    
    mid := adjustArr(arr, findex, lindex)
    QuickSort(arr, findex, mid - 1)
    QuickSort(arr, mid + 1, lindex)
    return 
}

 

package quickSort

import "testing"
import "fmt"

func TestQuickSort(t *testing.T) {
	var arr1 = [] int {3, 2, 1, 6, 7}
	detail_test(arr1, len(arr1), t)
	
	var arr2 = [] int {4,2,1,10,39,234,3,2,1,6,7}
	detail_test(arr2, len(arr2), t)
	
	var arr3 = [] int {4,2,1,10,39,234,3,2,1,6,7,0,52,123,2415,1234,656,253,245,12,3,4,12,51,52,13,1235,1234,656,13}
	detail_test(arr3, len(arr3), t)
}

func detail_test(arr [] int, length int, t *testing.T)() {
	QuickSort(arr, 0, length - 1)
	for i := 0; i < length - 1; i++ {
		fmt.Printf("%d ", arr[i])
		if arr[i] > arr[i + 1] {
			t.Errorf("%d ", arr[i])
		} 	
	}
	
	fmt.Printf("%d \n", arr[length - 1]);
}

 

标签:arr,int,testing,mid,repeated,findex,测试,Go,TTD
来源: https://www.cnblogs.com/woodx/p/13725888.html