Go語言測試包概述
在這篇Go語言文章中,我們將學習使用兩個測試函式以及迭代方法來概述測試包。
測試分為兩種型別:手動測試和自動化測試。手動測試是根據預定義的測試用例手動進行的,而自動化測試則是建立程式程式碼來測試軟體。在這裡,我們將使用兩個測試函式以及迭代方法來展示測試包的重要性。
演算法
步驟1 - 在程式中匯入所需的包
步驟2 - 建立一個測試函式,其中將呼叫要測試的函式
步驟3 - 使用測試用例檢查和分析函式,使用`go test`命令瞭解錯誤,如果未獲得錯誤,它將返回“透過”
示例1
在這個示例中,建立了兩個測試函式來了解被檢查函式中的錯誤。函式的結果將記錄在簡短的變數中,然後與正確的輸出進行匹配。
package mypackage
import "testing"
func Test_function(t *testing.T) {
result := first_function()
if result != "Hello, alexa!" {
t.Errorf("Expected 'Hello, alexa!' but got '%s'", result)
}
}
func Test_another_function(t *testing.T) {
result := Another_function()
if result != 64 {
t.Errorf("Expected 64 but got %d", result)
}
}
輸出
Pass
示例2
在這個示例中,將建立一個測試函式,其中將建立一些測試用例。然後,將迭代測試用例並在被呼叫函式上進行測試。
package mypackage
import (
"math"
"testing"
)
func Test_calculate_squareRoot(t *testing.T) {
test_cases := []struct {
input float64
expected float64
}{
{4, 2},
{9, 3},
{16, 4},
{25, 5},
{36, 6},
}
for _, testCase := range test_cases {
result := CalculateSquareRoot(testCase.input)
if math.Abs(result-testCase.expected) > 0.001 {
t.Errorf("Expected %f but got %f", testCase.expected, result)
}
}
}
輸出
Pass
結論
我們執行並總結了測試包的實現過程。在第一個示例中,我們建立了兩個測試函式,在每個測試函式中,我們將函式的輸出與精確的輸出進行了檢查。在第二個示例中,我們建立了一個測試用例結構體並對其進行了迭代以檢查錯誤。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP