当前位置: 首页 > article >正文

四十一、完成内容添加功能(使用go测试方法)

目录

一、添加model

二、完成相关dao

三、使用测试类进行测试

1、把光标防止要测试的方法上,右击并选择

2、自动会生成一个以dao文件加_test命名的文件

3、在其中完善方法并完成测试

四、完成content_create_handle


一、添加model

按数据库字段以及字段格式完成model

type ContentDetails struct {
	ID             int64     `gorm:"column:id;primary_key"`
	ContentID      string    `gorm:"column:content_id"`
	Title          string    `gorm:"column:title"`
	Description    string    `gorm:"column:description"`
	Author         string    `gorm:"column:author"`
	VideoUrl       string    `gorm:"column:video_url"`
	Thumbnail      string    `gorm:"column:thumbnail"`
	Category       string    `gorm:"column:category"`
	Duration       int64     `gorm:"column:duration"`
	Resolution     string    `gorm:"column:resolution"`
	FileSize       int64     `gorm:"column:fileSize"`
	Format         string    `gorm:"column:format"`
	Quality        int64     `gorm:"column:quality"`
	ApprovalStatus int64     `gorm:"column:approval_status"`
	Ct             time.Time `gorm:"column:created_at"`
	Ut             time.Time `gorm:"column:updated_at"`
}

func (ContentDetails) TableName() string {
	table := "cms_account.content_details"
	return table
}

二、完成相关dao

type ContentDetailsDao struct {
	db *gorm.DB
}

func NewContentDetailsDao(db *gorm.DB) *ContentDetailsDao {
	return &ContentDetailsDao{db: db}
}

func (c *ContentDetailsDao) Create(content model.ContentDetails) error {
	if err := c.db.Create(&content).Error; err != nil {
		fmt.Printf("create contentDetails failed, err:%v\n", err)
		return err
	}
	return nil
}

三、使用测试类进行测试

1、把光标防止要测试的方法上,右击并选择

2、自动会生成一个以dao文件加_test命名的文件
3、在其中完善方法并完成测试
// 添加连接数据库函数
func connDB() *gorm.DB {
	mysqlDB, err := gorm.Open(mysql.Open("root:rootroot@tcp(localhost:3306)/?charset=utf8mb4&parseTime=True&loc=Local"))
	if err != nil {
		panic(err)
	}
	db, err := mysqlDB.DB()
	if err != nil {
		panic(err)
	}
	//最大连接数
	db.SetMaxOpenConns(4)
	//最大空闲连接,一般为最大连接数/2
	db.SetMaxIdleConns(2)
	mysqlDB = mysqlDB.Debug()
	return mysqlDB
}

func TestContentDetailsDao_Create(t *testing.T) {
	type fields struct {
		db *gorm.DB
	}
	type args struct {
		content model.ContentDetails
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		wantErr bool
	}{
		{ //自定义名称
			name: "内容插入",
			//选择db为上面的connDB函数
			fields: fields{
				db: connDB(),
			},
			args: args{
				//选择入参
				content: model.ContentDetails{

					Title: "test",
					Ct:    time.Now(),
					Ut:    time.Now(),
				},
			},
			wantErr: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := &ContentDetailsDao{
				db: tt.fields.db,
			}
			if err := c.Create(tt.args.content); (err != nil) != tt.wantErr {
				t.Errorf("Create() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

四、完成content_create_handle

package services

import (
	"ContentSystem/internal/dao"
	"ContentSystem/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// 入参
type ContentCreateReq struct {
	Title          string    `json:"title" binding:"required"`
	Description    string    `json:"description" binding:"required"`
	Author         string    `json:"author" binding:"required"`
	VideoUrl       string    `json:"video_url"`
	Thumbnail      string    `json:"thumbnail"`
	Category       string    `json:"category"`
	Duration       int64     `json:"duration"`
	Resolution     string    `json:"resolution"`
	FileSize       int64     `json:"fileSize"`
	Format         string    `json:"format"`
	Quality        int64     `json:"quality"`
	ApprovalStatus int64     `json:"approval_status"`
	UpdatedAt      time.Time `json:"updated_at"`
	CreatedAt      time.Time `json:"created_at"`
}

// 回包
type ContentCreateRsp struct {
	Message string `json:"message"`
}

func (c *CmsApp) ContentCreate(ctx *gin.Context) {
	var req ContentCreateReq
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	contentDetailsDao := dao.NewContentDetailsDao(c.db)
	err := contentDetailsDao.Create(model.ContentDetails{
		Title:          req.Title,
		Description:    req.Description,
		Author:         req.Author,
		VideoUrl:       req.VideoUrl,
		Thumbnail:      req.Thumbnail,
		Category:       req.Category,
		Duration:       req.Duration,
		Resolution:     req.Resolution,
		FileSize:       req.FileSize,
		Format:         req.Format,
		Quality:        req.Quality,
		ApprovalStatus: req.ApprovalStatus,
		Ct:             time.Now(),
		Ut:             time.Now(),
	})
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "ok",
		"data": &ContentCreateRsp{
			Message: "ok",
		},
	})
}


http://www.kler.cn/news/315769.html

相关文章:

  • 全栈项目小组【算法赛】题目及解题
  • How do you send files to the OpenAI API?
  • 1.量化第一步,搭建属于自己的金融数据库!
  • 鸿蒙设置,修改APP图标和名称
  • Android Choreographer 监控应用 FPS
  • 如何在Chrome最新浏览器中调用ActiveX控件?
  • 什么时候用synchronized,什么时候用Reentrantlock
  • 高等数学——微分学
  • 5.《DevOps》系列K8S部署CICD流水线之K8S通过Yaml部署GitLab
  • C++从入门到起飞之——多态 全方位剖析!
  • 通信工程学习:什么是NFVI网络功能虚拟化基础设施层
  • Apache HttpComponents HttpClient
  • Blender软件三大渲染器Eevee、Cycles、Workbench对比解析
  • mysql学习教程,从入门到精通,SQL 删除数据(DELETE 语句)(18)
  • Tron/ETH/MATIC/TRX链上智能合约项目开发
  • 【系统架构设计师】软件架构的风格(经典习题)
  • SpringBoot启动横幅输出到控制台。
  • fiddler抓包07_抓IOS手机请求
  • 预付费计量系统实体模型
  • 在Docker中运行Tomcat:打造高效可移植的Java Web服务器
  • 01_RabbitMQ安装及工作模式
  • 阿里HPN-用于大型语言模型训练的数据中心网络
  • Kafka 下载安装及使用总结
  • JavaWeb初阶 day1
  • 从零开始学习Linux(14)---线程池
  • 『功能项目』QFrameWorkBug关联Slot(插槽)【67】
  • C++:使用tinyxml2获取节点下元素
  • android kotlin Extension扩展函数
  • HashMap源码
  • 【bug】通过lora方式微调sdxl inpainting踩坑