登录
首页 >  Golang >  Go问答

使用 pgx 驱动程序编写单元测试来测试在 Golang 中与 db 交互的函数的处理程序

来源:stackoverflow

时间:2024-02-06 10:27:34 435浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用 pgx 驱动程序编写单元测试来测试在 Golang 中与 db 交互的函数的处理程序》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我一直在尝试为我的 http 处理程序编写单元测试。代码段如下:

func (s *server) handlecreateticketoption(w http.responsewriter, r *http.request) {
    var t ticket.ticket
    body, err := ioutil.readall(r.body)
    if err != nil {
        http.error(w, er.errinternal.error(), http.statusinternalservererror)
        return
    }
    err = json.unmarshal(body, &t)
    if err != nil {
        http.error(w, er.errinvaliddata.error(), http.statusbadrequest)
        return
    }

    ticket, err := s.ticketservice.createticketoption(r.context(), t)
    if err != nil {
        http.error(w, er.errinternal.error(), http.statusinternalservererror)
        return
    }

    res, err := json.marshal(ticket)
    if err != nil {
        http.error(w, er.errinternal.error(), http.statusinternalservererror)
        return
    }

    log.printf("%v tickets allocated with name %v\n", t.allocation, t.name)
    s.sendresponse(w, res, http.statusok)
}

与数据库交互的实际逻辑。该代码段由处理程序调用,如上面的代码所示。 票证,err := s.ticketservice.createticketoption(r.context(), t)

func (t *ticketservice) createticketoption(ctx context.context, ticket ticket.ticket) (*ticket.ticket, error) {
    tx, err := t.db.dbpool.begin(ctx)
    if err != nil {
        return nil, er.errinternal
    }
    defer tx.rollback(ctx)

    var id int
    err = tx.queryrow(ctx, `insert into ticket (name, description, allocation) values ($1, $2, $3) returning id`, ticket.name, ticket.description, ticket.allocation).scan(&id)
    if err != nil {
        return nil, er.errinternal
    }

    ticket.id = id

    return &ticket, tx.commit(ctx)
}

这就是我对处理程序的单元测试。

func testcreateticketoptionhandler(t *testing.t) {
    

    caseexpected, _ := json.marshal(&ticket.ticket{id: 1, name: "baris", description: "test-desc", allocation: 10})
    srv := newserver()
    // expected := [][]byte{
    //  _, _ = json.marshal(&ticket.ticket{id: 1, name: "baris", description: "test-desc", allocation: 20}),
    //  // json.marshal(&ticket.ticket{id: 1, name: "baris", description: "test-desc", allocation: 20})
    // }

    tt := []struct {
        name  string
        entry *ticket.ticket
        want  []byte
        code  int
    }{
        {
            "valid",
            &ticket.ticket{name: "baris", description: "test-desc", allocation: 10},
            caseexpected,
            http.statusok,
        },
    }

    var buf bytes.buffer
    for _, tc := range tt {
        t.run(tc.name, func(t *testing.t) {
            json.newencoder(&buf).encode(tc.entry)
            req, err := http.newrequest(http.methodpost, "/ticket_options", &buf)
            log.println("1")
            if err != nil {
                log.println("2")
                t.fatalf("could not create request: %v", err)
            }
            log.println("3")
            rec := httptest.newrecorder()

            log.println("4")
            srv.handlecreateticketoption(rec, req)
            log.println("5")
            if rec.code != tc.code {
                t.fatalf("got status %d, want %v", rec.code, tc.code)
            }
            log.println("6")
            if reflect.deepequal(rec.body.bytes(), tc.want) {
                log.println("7")
                t.fatalf("name:%v,  got %v, want %v", tc.name, rec.body.bytes(), tc.want)
            }
        })
    }
}

我做了关于模拟 pgx 的研究,其中大多数都是不通过处理程序测试逻辑部分。我想分别为处理程序和逻辑本身编写单元测试。但是,我为处理程序恐慌编写的单元测试如下

github.com/bariis/gowit-case-study/psql.(*TicketService).CreateTicketOption(0xc000061348, {0x1485058, 0xc0000260c0}, {0x0, {0xc000026dd0, 0x5}, {0xc000026dd5, 0x9}, 0xa})
        /Users/barisertas/workspace/gowit-case-study/psql/ticket.go:24 +0x125
github.com/bariis/gowit-case-study/http.(*Server).handleCreateTicketOption(0xc000061340, {0x1484bf0, 0xc000153280}, 0xc00018e000)
        /Users/barisertas/workspace/gowit-case-study/http/ticket.go:77 +0x10b
github.com/bariis/gowit-case-study/http.TestCreateTicketOptionHandler.func2(0xc000119860)
        /Users/barisertas/workspace/gowit-case-study/http/ticket_test.go:80 +0x305

psql/ticket.go:24: tx, err := t.db.dbpool.begin(ctx)

http/ticket.go:77: ticket, err := s.ticketservice.createticketoption(r.context(), t)

http/ticket_test.go:80: srv.handlecreateticketoption(rec, req)

如何模拟这种类型的代码?


正确答案


  1. 创建一个具有所需数据库功能的接口
  2. 您的数据库处理程序实现此接口。您在实际执行中使用处理程序
  3. 使用 testify/mock 创建模拟处理程序,并在测试用例中使用它代替数据库处理程序

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>