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

go unit test for CSV fails

王林
王林forward
2024-02-06 08:42:03729browse

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
    }

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)
            }
        })
    }

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

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
        }

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete