php小編魚仔今天為大家介紹一下Go語言的單元測(cè)試。在軟件開發(fā)中,單元測(cè)試是非常重要的一環(huán)。通過編寫測(cè)試用例,我們可以驗(yàn)證代碼的正確性,提高代碼質(zhì)量和可維護(hù)性。Go語言提供了豐富的測(cè)試框架和工具,使得編寫和運(yùn)行單元測(cè)試變得更加簡(jiǎn)單和高效。本文將帶領(lǐng)大家了解Go語言的單元測(cè)試,包括測(cè)試用例的編寫、運(yùn)行和覆蓋率的統(tǒng)計(jì)。讓我們一起來深入了解Go語言的單元測(cè)試吧!
問題內(nèi)容
運(yùn)行單元測(cè)試時(shí)出現(xiàn)主鍵違規(guī) user_id 錯(cuò)誤
我的togglefavourite功能如下
func ToggleTrackToFavourite(c *gin.Context) { userID := GetCurrentUserID(c) trackID, err := strconv.Atoi(c.Param("id")) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Track ID"}) return } if err := favourites.CreateTable(db.DB); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create table" + err.Error()}) return } if isInFavorites(userID, trackID) { err = favourites.RemoveFavorite(db.DB, userID, trackID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to remove track from favorites"}) return } c.JSON(http.StatusOK, gin.H{"message": "Track removed from favorites"}) } else { err = favourites.InsertFavorite(db.DB, userID, trackID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to add track to favorites : " + err.Error()}) return } c.JSON(http.StatusOK, gin.H{"message": "Track added to favorites"}) } }
登錄后復(fù)制
func GetCurrentUserID(c *gin.Context) int { userID, exists := c.Get("userID") if !exists { return 0 } if userIDInt, ok := userID.(int); ok { return userIDInt } return 0 }
登錄后復(fù)制
上述代碼的單元測(cè)試函數(shù)如下
func TestToggleTrackToFavourite(t *testing.T) { db.InitTestDB() if err := users.CreateTable(db.DB); err != nil { t.Fatalf("Failed to create users table: %v", err) } if err := tracks.CreateTable(db.DB); err != nil { t.Fatalf("Failed to create tracks table: %v", err) } if err := favourites.CreateTable(db.DB); err != nil { t.Fatalf("Failed to create favorites table: %v", err) } user := users.User{ Username: "Test", Email: "[email protected]", Password: "123456", } if err := users.CreateUser(db.DB, &user); err != nil { t.Fatalf("Failed to create user: %v", err) } sampleTrack := tracks.Track{ Name: "Test track", Index: 10, Track: "chere.mp4", Image: "image.jpg", Album_ID: 4, Is_Published: true, } if err := tracks.CreateTrack(db.DB, &sampleTrack); err != nil { t.Fatalf("Failed to insert the example track: %v", err) } r := gin.Default() r.PUT("/user/favorite/toggle/:id", ToggleTrackToFavourite) reqAddToFavorites := httptest.NewRequest("PUT", "/user/favorite/toggle/1", nil) wAddToFavorites := httptest.NewRecorder() r.ServeHTTP(wAddToFavorites, reqAddToFavorites) assert.Equal(t, http.StatusOK, wAddToFavorites.Code) assert.Equal(t, `{"message":"Track added to favorites"}`, wAddToFavorites.Body.String()) // reqRemoveFromFavorites := httptest.NewRequest("PUT", "/user/favorite/toggle/1", nil) // reqAddToFavorites.Params = append(reqAddToFavorites.Params, httptest.Param{"id", "1"}) // wRemoveFromFavorites := httptest.NewRecorder() // r.ServeHTTP(wRemoveFromFavorites, reqRemoveFromFavorites) // assert.Equal(t, http.StatusOK, wRemoveFromFavorites.Code) // assert.Equal(t, `{"message":"Track removed from favorites"}`, wRemoveFromFavorites.Body.String()) if _, err := db.DB.Exec("DROP TABLE IF EXISTS favorite"); err != nil { t.Fatalf("Failed to drop the table: %v", err) } if _, err := db.DB.Exec("DROP TABLE IF EXISTS tracks"); err != nil { t.Fatalf("Failed to drop the table: %v", err) } if _, err := db.DB.Exec("DROP TABLE IF EXISTS users"); err != nil { t.Fatalf("Failed to drop the table: %v", err) } }
登錄后復(fù)制
不知道如何在單元測(cè)試中將 GETCURRENTUSER 函數(shù)的默認(rèn)值傳遞為 1
只想從收藏夾中添加/刪除曲目
解決方法
代碼中的用戶 ID 似乎存儲(chǔ)在處理程序之前的某些身份驗(yàn)證中間件的上下文局部變量中名為“userId”的局部變量中,因此設(shè)置它足以進(jìn)行測(cè)試,您可以更改這些行:
r := gin.Default() c.Set("userID", "1") r.PUT("/user/favorite/toggle/:id", ToggleTrackToFavourite)
登錄后復(fù)制