搜尋
首頁後端開發GolangGolang 單元測試的簡單錯誤問題

Golang 单元测试的简单错误问题

Golang單元測試是保證程式碼品質和功能正確性的重要手段,但在實務中,我們常常會遇到一些簡單的錯誤問題。在本文中,php小編子墨將為大家介紹一些常見的錯誤問題,以及如何解決它們。透過學習這些問題的解決方法,相信大家在進行Golang單元測試時能夠更順利地進行,並提升程式碼的品質和可靠性。

問題內容

我在嘗試測試此函數時遇到問題,但內部有錯誤。以下是我的 responsejson 函數,它不回傳錯誤,但發送回應 json。

func responsejson(w http.responsewriter, code int, message string) {
    jsonstatus := struct {
        code int `json:"code"`
        message string `json:"message"`
    }{
        message: message,
        code: code,
    }

    bs, err := json.marshal(jsonstatus);

    if err != nil {
        log.println("error in marshal json in responsejson: ", err)
        str := "internal server error. please contact the system administrator."
        io.writestring(w, str);
        return 
    } else {
        io.writestring(w, string(bs));
        return
    }
    
}

以下是我的單元測試程式碼,它創建了一個模擬 responsewriter,它能夠成功測試編寫器回應 json 的情況,沒有錯誤。由於我沒有在 responsejson() 函數中傳回錯誤類型,因此如何在 test_responsejson 函數中測試它,如下所示?

func test_responsejson(t *testing.t) {
    responsejsontests := []struct {
        testname string
        code int
        message string
        expectedjsonresponse string
    } {
        {"successful login", http.statusok, "successfully logged in!", `{"code":200,"message":"successfully logged in!"}`},
        {"existing username", http.statusbadrequest, "username already exists. please try again.", `{"code":400,"message":"username already exists. please try again."}`},
    }

    for _, e := range responsejsontests {
        // creating a mock responsewriter
        w := httptest.newrecorder()

        responsejson(w, e.code, e.message)

        // read the response body as a string
        body, _ := io.readall(w.result().body)
        actual := string(body)

        expected := e.expectedjsonresponse
        if actual != expected {
            t.errorf("%s: expected %s but got %s", e.testname, e.expectedjsonresponse, actual)
        }
    }
}

此外,我還建立了一個函數,它為 log.println() 內建函數產生實際的日誌輸出。我知道 log.println() 函數是內建函數,它不太可能失敗。但是,我希望在單元測試中實現 100% 的覆蓋率。請幫忙!謝謝:)

func GenerateLogOutput(message string, errorMessage string) string {
    // Create a new bytes.Buffer to capture the log output
    var buf bytes.Buffer

    // Redirect log output to a different destination set as a buffer
    // By default, log message are written to the standard error stream os.Stderr
    log.SetOutput(&buf)

    // Generate an error
    err := errors.New(errorMessage)

    w := httptest.NewRecorder()

    // Calling the function
    InternalServerError(w, message, err)
    actualOutput := buf.String()

    return actualOutput
}

解決方法

簡單地說,我們可以為 responsejson 函數編寫一個測試案例,如下所示。

func Test_ResponseJson(t *testing.T) {
    tests := []struct {
        Code        int
        Message     string
        ExpectedStr string
    }{
        {
            Code:        1,
            Message:     "sample message",
            ExpectedStr: "{\"code\":1,\"message\":\"sample message\"}",
        },
    }
    for _, test := range tests {
        w := httptest.NewRecorder()

        ResponseJson(w, test.Code, test.Message)

        res := w.Result()
        data, err := ioutil.ReadAll(res.Body)
        res.Body.Close()

        actualStr := string(data)

        assert.Nil(t, err, "Invalid test data")
        assert.Equal(t, actualStr, test.ExpectedStr)
    }
}

我們無法從 bs 取得錯誤,err := json.marshal(jsonstatus)json.marshal 函數可以傳回兩種類型的錯誤。

  1. unsupportedtypeerror(例如:通道、複合值和函數值)
  2. unsupportedvalueerror(例如:循環資料結構)

我們無法解析值來產生上述錯誤之一。我們正在解析具有支援的值和支援的類型的結構。因此,我們無法編寫 100% 覆蓋率的測試。

以上是Golang 單元測試的簡單錯誤問題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
去其他語言:比較分析去其他語言:比較分析Apr 28, 2025 am 12:17 AM

goisastrongchoiceforprojectsneedingsimplicity,績效和引發性,butitmaylackinadvancedfeatures and ecosystemmaturity.1)

比較以其他語言的靜態初始化器中的初始化功能比較以其他語言的靜態初始化器中的初始化功能Apr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

GO中初始功能的常見用例GO中初始功能的常見用例Apr 28, 2025 am 12:13 AM

thecommonusecasesfortheinitfunctionoare:1)加載configurationfilesbeforeThemainProgramStarts,2)初始化的globalvariables和3)runningpre-checkSorvalidationsbeforEtheprofforeTheProgrecce.TheInitFunctionIsautefunctionIsautomentycalomationalmatomatimationalycalmatemationalcalledbebeforethemainfuniinfuninfuntuntion

GO中的頻道:掌握際際交流GO中的頻道:掌握際際交流Apr 28, 2025 am 12:04 AM

ChannelsarecrucialingoforenablingsafeandefficityCommunicationBetnewengoroutines.theyfacilitateSynChronizationAndManageGoroutIneLifeCycle,EssentialforConcurrentProgramming.ChannelSallSallSallSallSallowSallowsAllowsEnderDendingAndReceivingValues,ActassignalsignalsforsynChronization,and actassignalsynChronization and andsupppor

包裝錯誤:將上下文添加到錯誤鏈中包裝錯誤:將上下文添加到錯誤鏈中Apr 28, 2025 am 12:02 AM

在Go中,可以通過errors.Wrap和errors.Unwrap方法來包裝錯誤並添加上下文。 1)使用errors包的新功能,可以在錯誤傳播過程中添加上下文信息。 2)通過fmt.Errorf和%w包裝錯誤,幫助定位問題。 3)自定義錯誤類型可以創建更具語義化的錯誤,增強錯誤處理的表達能力。

使用GO開發時的安全考慮使用GO開發時的安全考慮Apr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

了解GO的錯誤接口了解GO的錯誤接口Apr 27, 2025 am 12:16 AM

Go的錯誤接口定義為typeerrorinterface{Error()string},允許任何實現Error()方法的類型被視為錯誤。使用步驟如下:1.基本檢查和記錄錯誤,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。 2.創建自定義錯誤類型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。 3.使用錯誤包裝(自Go1.13起)來添加上下文而不丟失原始錯誤信息,

並發程序中的錯誤處理並發程序中的錯誤處理Apr 27, 2025 am 12:13 AM

對效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,enplionErrorWatchers,Instertimeout,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErtopassErrorsErtopassErrorsErrorsErrorsFromGoroutInestOthemainFunction.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能