Home > Backend Development > Golang > go unit test for CSV fails

go unit test for CSV fails

王林
Release: 2024-02-06 08:42:03
forward
728 people have browsed it

CSV 的 go 单元测试失败

Question content

I want to use the csv package for a large project, and I'm starting with some basic testing. I can't figure out why this unit test fails when the output looks to match the expected output.

document:

package csv

import (
    "bytes"
    "encoding/csv"
)

func generatecsv(records [][]string) (string, error) {
    buf := bytes.buffer{}

    w := csv.newwriter(&buf)

    for _, record := range records {
        if err := w.write(record); err != nil {
            // handle the err
            }
    }
        w.flush()

        if err := w.error(); err != nil {
            // handle the error
        }

        return buf.string(), nil
    }
Copy after login

Test file:

package csv

import "testing"

func testgeneratecsv(t *testing.t) {

    records := [][]string{
        {"first_name","last_name","user_name"},
    }
    type args struct {
        records [][]string
    }
    tests := []struct {
        name    string
        args    args
        want    string
        wanterr bool
    }{
        // todo: add test cases.
        {"t1", args{records: records,}, "first_name,last_name,user_name", false},
    }
    for _, tt := range tests {
        t.run(tt.name, func(t *testing.t) {
            got, err := generatecsv(tt.args.records)
            if (err != nil) != tt.wanterr {
                t.errorf("generatecsv() error = %v, wanterr %v", err, tt.wanterr)
                return
            }
            if got != tt.want {
                t.errorf("generatecsv() = %v, want %v", got, tt.want)
            }
        })
    }
Copy after login

When the test runs, I get the following output:

FAIL: TestGenerateCSV
GenerateCSV() = first_name,last_name,user_name
        , want first_name,last_name,user_name
Copy after login

Looks like the test output is exactly what I asked for? Can anyone help me figure out what I'm doing wrong?


Correct Answer


To catch errors, add this check in your test code.

if len(got) != len(tt.want) {
            t.Errorf("GenerateCSV() string len = %v, want length %v", len(got), len(tt.want))
            return
        }
Copy after login

Cause: When you use w.flush to write a record, it adds a new row.

The above is the detailed content of go unit test for CSV fails. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template