Solucionado (ver solução)
Solucionado
(ver solução)
5
respostas

Erro na Requisição de Teste

Olá pessoal,

Estou obtendo erro na requisição de teste, mesmo quando a mesma requisição pelo Insomnia está OK.

Meu código:

package main

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
    "github.com/xdouglas90/go_studies/gin-rest-api/controllers"
)

func RoutesTestSetup() *gin.Engine {
    r := gin.Default()
    return r
}

func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
    req, _ := http.NewRequest(method, path, nil)
    w := httptest.NewRecorder()
    r.ServeHTTP(w, req)
    return w
}

func TestVerifySCGetStudents(t *testing.T) {
    r := RoutesTestSetup()
    r.GET("/students", controllers.GetStudents)
    w := performRequest(r, "GET", "/students")

    if w.Code != http.StatusOK {
        t.Errorf("Expected status code %d, got %d", http.StatusOK, w.Code)
    }
}

Erro em teste:

2022/10/23 14:56:16 [Recovery] 2022/10/23 - 14:56:16 panic recovered:
GET /students HTTP/1.1


runtime error: invalid memory address or nil pointer dereference
/usr/local/go/src/runtime/panic.go:260 (0x450895)
        panicmem: panic(memoryError)
/usr/local/go/src/runtime/signal_unix.go:835 (0x450865)
        sigpanic: panicmem()
/home/odouglas-dev/go/pkg/mod/gorm.io/gorm@v1.24.1-0.20221019064659-5dd2bb482755/gorm.go:372 (0x63e078)
        (*DB).getInstance: if db.clone > 0 {
/home/odouglas-dev/go/pkg/mod/gorm.io/gorm@v1.24.1-0.20221019064659-5dd2bb482755/finisher_api.go:163 (0x6382c4)
        (*DB).Find: tx = db.getInstance()
/home/odouglas-dev/go/src/studies/alura/gin-rest-api/controllers/controller.go:11 (0xab3f37)
        GetStudents: database.DBConn.Find(&students)
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0xaab5a1)
        (*Context).Next: c.handlers[c.index](c)
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/recovery.go:101 (0xaab58c)
        CustomRecoveryWithWriter.func1: c.Next()
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0xaaa6a6)
        (*Context).Next: c.handlers[c.index](c)
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/logger.go:240 (0xaaa689)
        LoggerWithConfig.func1: c.Next()
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/context.go:173 (0xaa9770)
        (*Context).Next: c.handlers[c.index](c)
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:616 (0xaa93d8)
        (*Engine).handleHTTPRequest: c.Next()
/home/odouglas-dev/go/pkg/mod/github.com/gin-gonic/gin@v1.8.1/gin.go:572 (0xaa8f1c)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/home/odouglas-dev/go/src/studies/alura/gin-rest-api/main_test.go:27 (0xab583e)
        performRequest: r.ServeHTTP(w, req)
/home/odouglas-dev/go/src/studies/alura/gin-rest-api/main_test.go:34 (0xab5939)
        TestVerifySCGetStudents: w := performRequest(r, "GET", "/students")
/usr/local/go/src/testing/testing.go:1446 (0x5217aa)
        tRunner: fn(t)
/usr/local/go/src/runtime/asm_amd64.s:1594 (0x46e460)
        goexit: BYTE    $0x90   // NOP

[GIN] 2022/10/23 - 14:56:16 | 500 |     689.721µs |                 | GET      "/students"
--- FAIL: TestVerifySCGetStudents (0.00s)
    main_test.go:37: Expected status code 200, got 500
FAIL
exit status 1
FAIL    github.com/xdouglas90/go_studies/gin-rest-api   0.008s

Mesma requisição pelo Insomnia:

< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Sun, 23 Oct 2022 18:02:14 GMT
< Content-Length: 357

Desde já, obrigado pela ajuda.

5 respostas

Olá Douglas, tudo bem?

Poderia subir o seu projeto Go no github e postar o link aqui para eu dar uma olhada?

Olá Otávio,

Claro, está hospedado neste link .

solução!

O problema é que dentro do seu método de teste você não está chamando o database.Connect()

Quando eu mudei para o código abaixo resolveu o problema:

func TestVerifySCGetStudents(t *testing.T) {
    database.Connect()
    r := RoutesTestSetup()
    r.GET("/students", controllers.GetStudents)
    w := performRequest(r, "GET", "/students")

    if w.Code != http.StatusOK {
        t.Errorf("Expected status code %d, got %d", http.StatusOK, w.Code)
    }
}

Muito obrigado Otávio.

Opa, por nada Douglas, qualquer dúvida só abrir outro tópico :)