[Go] Unit testing Go code

  • Vanilla Go includes Testing
  • A test is a file with suffix_test.go
  • You define functions with prefix Test and with an special signature receiving a *testing.T arguement
  • The function inside calls methods of T
  • You can create subtests as goroutines
  • You use the CLI with go test
  • TableDrivenTest Design Pattern
  • Fuzzing since 1.19

Fuzzing: Automated testing that manipulates inputs to find bugs. Go fuzzing uses coverage guidance to find failures and is valuable in detecting security exploits and vunlnerabilities.

 

Code:

查看代码
package api

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"project/data"
)

const apiUrl = "https://cex.io/api/ticker/%s/USD"

// add * to struct in return type is a pattern
// because if you want to return nil from the function
// without *, it doesn't compile
func GetRate(currency string) (*data.Rate, error) {

	if len(currency) < 3 {
		return nil, fmt.Errorf("3 characteres minimu; %d received", len(currency))
	}

	upCurrency := strings.ToUpper(currency)
	res, err := http.Get(fmt.Sprintf(apiUrl, upCurrency))
	if err != nil {
		return nil, err
	}

	var cexResp CEXResponse
	if res.StatusCode == http.StatusOK {
		// Wait all stream have been readed
		bodyBytes, err := io.ReadAll(res.Body)
		if err != nil {
			return nil, err
		}


		errJson := json.Unmarshal(bodyBytes, &cexResp)
		if errJson != nil {
			return nil, errJson
		}
	} else {
		return nil, fmt.Errorf("status code received: %v", res.StatusCode)
	}

	rate := data.Rate{Currency: upCurrency, Price: float32(cexResp.Ask)}
	return &rate, nil
}

 

Test:

package api_test

import (
	"testing"

	"project/api"
)

func TestApiCallWithEmptyCurrency(t *testing.T) {
	_, err := api.GetRate("")
	if err == nil {
		t.Error("error was not found")
	}
}

 

posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-02-06 [Typescript] Global Scope
2023-02-06 [Typescript] Indexing an Object with Branded Types
2019-02-06 [TypeScript] Type Definitions and Modules
2019-02-06 [Tools] Add a Dynamic Tweet Button to a Webpage
2019-02-06 [Algorithm] Find Nth smallest value from Array
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components
点击右上角即可分享
微信分享提示