猿问

如何正确地对 mongoDB CRUD 结果进行单元测试

mongo-go-drive我的应用程序主要由使用包与 MongoDB 之间的 CRUD 组成。该函数是 gRPC 服务器服务之一,它所做的只是调用数据库方法action.GetProducts(ctx)并返回*mongo.cursor. 然后对结果进行解码。对于每个文档,我将文档内容放入单个产品结构中,然后将其附加到产品切片中(该GetProductsResponse结构是使用 gRPC 原型repeated GetProductResponse类型制作的)。将所有产品附加到 后GetProductsResponse,我将响应返回给 gRPC 客户端。


我也是一般测试的新手,我应该如何分解功能并进行模拟(如何模拟光标?)以进行单元测试?是否有必要首先对函数进行单元测试,即使它所做的只是附加结果,还是应该直接进行集成测试并跳过单元测试,因为它涉及数据库 I/O?


func (s *Server) GetProducts(ctx context.Context, in *pb.EmptyRequest) (*pb.GetProductsResponse, error) {

    cursor, err := action.GetProducts(ctx)

    if err != nil {

        return nil, err

    }


    products := pb.GetProductsResponse{}


    res := model.Product{}


    for cursor.Next(ctx) {

        // Convert document to above struct

        err := cursor.Decode(&res)

        if err != nil {

            return nil, fmt.Errorf("failed to decode document: %v", err)

        }


        product := &pb.GetProductResponse{ProductId: res.Product_id.Hex(), Name: res.Name, Price: res.Price, Qty: int32(res.Qty)}


        products.Products = append(products.Products, product)

    }


    return &products, nil

}


MYYA
浏览 81回答 1
1回答

慕田峪7331174

如果您与数据库交互不再是单元测试,因为您正在与另一个外部系统集成。无论如何,我用这种方式定义我的“存储库”层函数:package repovar FetchUserById = func(id string) (*model.User, error){    // here the real logic    return user, err}然后,当我必须测试我的“服务”层逻辑时,我会以这种方式模拟整个“存储库”层:repo.FetchUserById = func(id string) (*model.User, err) {   return myMockedUser, nil}
随时随地看视频慕课网APP

相关分类

Go
我要回答