Golang unit testing is an important means to ensure code quality and functional correctness, but in practice, we often encounter some simple errors. In this article, PHP editor Zimo will introduce you to some common error problems and how to solve them. By learning the solutions to these problems, I believe that everyone can perform Golang unit testing more smoothly and improve the quality and reliability of the code.
Question content
I'm having trouble trying to test this function, but there's an error inside. Below is my responsejson function which does not return an error but sends the response 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 } }
The following is my unit test code, which creates a mock responsewriter that successfully tests the writer's response to json without errors. Since I am not returning the error type in responsejson() function, how can I test it in test_responsejson function like below?
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) } } }
Additionally, I created a function that generates the actual log output for the log.println() built-in function. I know that the log.println() function is a built-in function and it is unlikely to fail. However, I want to achieve 100% coverage in my unit tests. please help! Thanks:)
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 }
Solution
Simply put, we can write a test case for the responsejson
function as shown below.
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) } }
We cannot get the error from bs, err := json.marshal(jsonstatus)
. json.marshal
The function can return two types of errors.
-
unsupportedtypeerror
(for example: channels, composite values, and function values) -
unsupportedvalueerror
(for example: circular data structure)
We were unable to parse the value to generate one of the above errors. We are parsing a struct with supported values and supported types. Therefore, we cannot write tests with 100% coverage.
The above is the detailed content of Simple error problem in Golang unit testing. For more information, please follow other related articles on the PHP Chinese website!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
