搜尋
首頁資料庫mysql教程GIN、GORM、TESTIFY、MYSQL 的 GOLANG 整合測試

GOLANG INTEGRATION TEST WITH GIN, GORM, TESTIFY, MYSQL

Creating a comprehensive integration test for a Golang application using libraries like Gin, Gorm, Testify, and MySQL (using an in-memory solution) involves setting up a testing environment, defining routes and handlers, and testing them against an actual database (though using MySQL in-memory might require a workaround like using SQLite in in-memory mode for simplicity).

Here’s an example of an integration test setup:

1. Dependencies:

  • Gin: for creating the HTTP server.
  • Gorm: for ORM to interact with the database.
  • Testify: for assertions.
  • SQLite in-memory: acts as a substitute for MySQL during testing.

2. Setup:

  • Define a basic model and Gorm setup.
  • Create HTTP routes and handlers.
  • Write tests using Testify and SQLite as an in-memory database.

Here’s the full example:

// main.go
package main

import (
    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
    "net/http"
)

// User represents a simple user model.
type User struct {
    ID    uint   `gorm:"primaryKey"`
    Name  string `json:"name"`
    Email string `json:"email" gorm:"unique"`
}

// SetupRouter initializes the Gin engine with routes.
func SetupRouter(db *gorm.DB) *gin.Engine {
    r := gin.Default()

    // Inject the database into the handler
    r.POST("/users", func(c *gin.Context) {
        var user User
        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        if err := db.Create(&user).Error; err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        c.JSON(http.StatusCreated, user)
    })

    r.GET("/users/:id", func(c *gin.Context) {
        var user User
        id := c.Param("id")
        if err := db.First(&user, id).Error; err != nil {
            c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
            return
        }
        c.JSON(http.StatusOK, user)
    })

    return r
}

func main() {
    // For production, use MySQL
    dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&User{})

    r := SetupRouter(db)
    r.Run(":8080")
}

Integration Test

// main_test.go
package main

import (
    "bytes"
    "encoding/json"
    "github.com/stretchr/testify/assert"
    "net/http"
    "net/http/httptest"
    "testing"

    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

// SetupTestDB sets up an in-memory SQLite database for testing.
func SetupTestDB() *gorm.DB {
    db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
    if err != nil {
        panic("failed to connect to the test database")
    }
    db.AutoMigrate(&User{})
    return db
}

func TestCreateUser(t *testing.T) {
    db := SetupTestDB()
    r := SetupRouter(db)

    // Create a new user.
    user := User{Name: "John Doe", Email: "john@example.com"}
    jsonValue, _ := json.Marshal(user)
    req, _ := http.NewRequest("POST", "/users", bytes.NewBuffer(jsonValue))
    req.Header.Set("Content-Type", "application/json")
    w := httptest.NewRecorder()
    r.ServeHTTP(w, req)

    assert.Equal(t, http.StatusCreated, w.Code)

    var createdUser User
    json.Unmarshal(w.Body.Bytes(), &createdUser)
    assert.Equal(t, "John Doe", createdUser.Name)
    assert.Equal(t, "john@example.com", createdUser.Email)
}

func TestGetUser(t *testing.T) {
    db := SetupTestDB()
    r := SetupRouter(db)

    // Insert a user into the in-memory database.
    user := User{Name: "Jane Doe", Email: "jane@example.com"}
    db.Create(&user)

    // Make a GET request.
    req, _ := http.NewRequest("GET", "/users/1", nil)
    w := httptest.NewRecorder()
    r.ServeHTTP(w, req)

    assert.Equal(t, http.StatusOK, w.Code)

    var fetchedUser User
    json.Unmarshal(w.Body.Bytes(), &fetchedUser)
    assert.Equal(t, "Jane Doe", fetchedUser.Name)
    assert.Equal(t, "jane@example.com", fetchedUser.Email)
}

func TestGetUserNotFound(t *testing.T) {
    db := SetupTestDB()
    r := SetupRouter(db)

    // Make a GET request for a non-existent user.
    req, _ := http.NewRequest("GET", "/users/999", nil)
    w := httptest.NewRecorder()
    r.ServeHTTP(w, req)

    assert.Equal(t, http.StatusNotFound, w.Code)
}

Explanation

  1. main.go:

    • Defines a User struct and sets up basic CRUD operations using Gin.
    • Uses Gorm for database interactions and auto-migrates the User table.
    • SetupRouter configures HTTP endpoints.
  2. main_test.go:

    • SetupTestDB initializes an in-memory SQLite database for isolated testing.
    • TestCreateUser: Tests the creation of a user.
    • TestGetUser: Tests fetching an existing user.
    • TestGetUserNotFound: Tests fetching a non-existent user.
    • Uses httptest.NewRecorder and http.NewRequest for simulating HTTP requests and responses.
    • Uses Testify for assertions, like checking HTTP status codes and verifying JSON responses.

Running the Tests

To run the tests, use:

go test -v

Considerations

  • SQLite for In-memory Testing: This example uses SQLite for in-memory testing as MySQL doesn't natively support an in-memory mode with Gorm. For tests that rely on MySQL-specific features, consider using a Docker-based setup with a MySQL container.
  • Database Migrations: Always ensure the database schema is up-to-date using AutoMigrate in tests.
  • Isolation: Each test function initializes a fresh in-memory database, ensuring tests don't interfere with each other.

以上是GIN、GORM、TESTIFY、MYSQL 的 GOLANG 整合測試的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使用Alter Table語句在MySQL中更改表?如何使用Alter Table語句在MySQL中更改表?Mar 19, 2025 pm 03:51 PM

本文討論了使用MySQL的Alter Table語句修改表,包括添加/刪除列,重命名表/列以及更改列數據類型。

如何為MySQL連接配置SSL/TLS加密?如何為MySQL連接配置SSL/TLS加密?Mar 18, 2025 pm 12:01 PM

文章討論了為MySQL配置SSL/TLS加密,包括證書生成和驗證。主要問題是使用自簽名證書的安全含義。[角色計數:159]

您如何處理MySQL中的大型數據集?您如何處理MySQL中的大型數據集?Mar 21, 2025 pm 12:15 PM

文章討論了處理MySQL中大型數據集的策略,包括分區,碎片,索引和查詢優化。

哪些流行的MySQL GUI工具(例如MySQL Workbench,PhpMyAdmin)是什麼?哪些流行的MySQL GUI工具(例如MySQL Workbench,PhpMyAdmin)是什麼?Mar 21, 2025 pm 06:28 PM

文章討論了流行的MySQL GUI工具,例如MySQL Workbench和PhpMyAdmin,比較了它們對初學者和高級用戶的功能和適合性。[159個字符]

如何使用Drop Table語句將表放入MySQL中?如何使用Drop Table語句將表放入MySQL中?Mar 19, 2025 pm 03:52 PM

本文討論了使用Drop Table語句在MySQL中放下表,並強調了預防措施和風險。它強調,沒有備份,該動作是不可逆轉的,詳細介紹了恢復方法和潛在的生產環境危害。

如何在JSON列上創建索引?如何在JSON列上創建索引?Mar 21, 2025 pm 12:13 PM

本文討論了在PostgreSQL,MySQL和MongoDB等各個數據庫中的JSON列上創建索引,以增強查詢性能。它解釋了索引特定的JSON路徑的語法和好處,並列出了支持的數據庫系統。

您如何用外國鑰匙代表關係?您如何用外國鑰匙代表關係?Mar 19, 2025 pm 03:48 PM

文章討論了使用外國密鑰來代表數據庫中的關係,重點是最佳實踐,數據完整性和避免的常見陷阱。

如何保護MySQL免受常見漏洞(SQL注入,蠻力攻擊)?如何保護MySQL免受常見漏洞(SQL注入,蠻力攻擊)?Mar 18, 2025 pm 12:00 PM

文章討論了使用準備好的語句,輸入驗證和強密碼策略確保針對SQL注入和蠻力攻擊的MySQL。(159個字符)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具