如何编写表驱动开发的测试?

huangapple go评论86阅读模式
英文:

How to write Table Driven Development test?

问题

我正在尝试为以下代码编写TDD(测试驱动开发)。但是,我无法在我的测试代码中达到100%的覆盖率。有人可以给我正确的代码来覆盖我的测试吗?

以下代码用于连接我的数据库:

func Dbconn() (*sql.DB, error) {

    db, err := sql.Open("postgres", "postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true")
    if err != nil {
        return nil, err
    }
    return db, nil
}

以下是我的测试用例:

package models

import (
    "database/sql"
    "reflect"
    "testing"

    _ "github.com/lib/pq"
)

func TestDbconn(t *testing.T) {
    db, _ := sql.Open("postgres", "postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true")
    tests := []struct {
        name    string
        want    *sql.DB
        wantErr bool
    }{
        {
            name:    "Success connection",
            want:    db,
            wantErr: false,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := Dbconn()
            if (err != nil) != tt.wantErr {
                t.Errorf("Dbconn() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("Dbconn() = %v, want %v", got, tt.want)
            }
        })
    }
}

如果我运行我的测试,它只会覆盖75%。
而且还给我报错,像这样:

go test -v --cover
=== RUN   TestDbconn
=== RUN   TestDbconn/Success_connection
db_test.go:32: Dbconn() = &{{{} {} 0} {postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true 0x8d4730} {{} {} 0} {0 0} [] map[] 0 0 0xc0000824e0 false map[] map[] 0 0 0 0 <nil> 0 0 0 0 0x50f1a0}, want &{{{} {} 0} {postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true 0x8d4730} {{} {} 0} {0 0} [] map[] 0 0 0xc000082420 false map[] map[] 0 0 0 0 <nil> 0 0 0 0 0x50f1a0}
--- FAIL: TestDbconn (0.00s)
    --- FAIL: TestDbconn/Success_connection (0.00s)
        coverage: 75.0% of statements exit status 1
英文:

I am trying to write TDD for the following code. But, I cant able to cover 100% coverage in my test code. Can anyone give me the correct code to cover my test?

The following codes are used to connect my Database

func Dbconn() (*sql.DB, error) {

	db, err := sql.Open(&quot;postgres&quot;, &quot;postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true&quot;)
	if err != nil {
		return nil, err
	}
	return db, nil
}

The following codes are my test case
package models

import (
	&quot;database/sql&quot;
	&quot;reflect&quot;
	&quot;testing&quot;

	_ &quot;github.com/lib/pq&quot;
)

func TestDbconn(t *testing.T) {
	db, _ := sql.Open(&quot;postgres&quot;, &quot;postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true&quot;)
	tests := []struct {
		name    string
		want    *sql.DB
		wantErr bool
	}{
		{
			name:    &quot;Success connection&quot;,
			want:    db,
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := Dbconn()
			if (err != nil) != tt.wantErr {
				t.Errorf(&quot;Dbconn() error = %v, wantErr %v&quot;, err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf(&quot;Dbconn() = %v, want %v&quot;, got, tt.want)
			}
		})
	}
}

If I run my test, it will cover only 75%.
And also giving me error like this

     go test -v --cover
      === RUN   TestDbconn
      === RUN   TestDbconn/Success_connection
      db_test.go:32: Dbconn() = &amp;{{{} {} 0} {postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true 0x8d4730} {{} {} 0} {0 0} [] map[] 0 0 0xc0000824e0 false map[] map[] 0 0 0 0 &lt;nil&gt; 0 0 0 0 0x50f1a0}, want &amp;{{{} {} 0} {postgres:root@tcp(localhost:5432)/customer_complaints?multistatements=true 0x8d4730} {{} {} 0} {0 0} [] map[] 0 0 0xc000082420 false map[] map[] 0 0 0 0 &lt;nil&gt; 0 0 0 0 0x50f1a0}
--- FAIL: TestDbconn (0.00s)
    --- FAIL: TestDbconn/Success_connection (0.00s)
        coverage: 75.0% of statements exit status 1

答案1

得分: 1

似乎你的测试代码存在问题,问题在于你在测试中创建了一个新的数据库连接,然后将其与Dbconn()函数返回的连接进行比较。尽管这两个数据库连接可能具有相同的连接参数,但它们不会相等。

为了正确测试Dbconn()函数,你不应该在测试中创建新的数据库连接。相反,你可以测试函数是否返回一个非空的数据库连接,并检查连接过程中是否存在任何潜在的错误。

package models

import (
    "database/sql"
    "testing"
)

func TestDbconn(t *testing.T) {
    db, err := Dbconn()
    if err != nil {
        t.Fatalf("Dbconn()返回了一个错误:%v", err)
    }
    defer db.Close()

    // 执行一个简单的查询来检查连接是否正常工作
    if err := db.Ping(); err != nil {
        t.Fatalf("Dbconn()连接失败:%v", err)
    }
}

以上是翻译好的内容,请确认是否正确。

英文:

It seems that the issue with your test code is that you are creating a new database connection inside your test and then comparing it with the one returned by the Dbconn() function. These two instances of database connections will not be equal, even though they may have the same connection parameters.

To properly test the Dbconn() function, you should not create a new database connection inside the test. Instead, you can test if the function returns a non-nil database connection and check for any potential errors during the connection process.

package models

import (
    &quot;database/sql&quot;
    &quot;testing&quot;
)

func TestDbconn(t *testing.T) {
    db, err := Dbconn()
    if err != nil {
        t.Fatalf(&quot;Dbconn() returned an error: %v&quot;, err)
    }
    defer db.Close()

    // Perform a simple query to check if the connection is working
    if err := db.Ping(); err != nil {
        t.Fatalf(&quot;Dbconn() connection failed: %v&quot;, err)
    }
}

huangapple
  • 本文由 发表于 2023年7月24日 13:56:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76751747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定