Go Mongo-Driver 및 mtest를 사용하여 UpdateOne의 모의 UpdateResult

王林
풀어 주다: 2024-02-09 20:00:33
앞으로
611명이 탐색했습니다.

使用 Go Mongo-Driver 和 mtest 从 UpdateOne 模拟 UpdateResult

php 편집기 Baicao는 이 기사에서 Go Mongo-Driver 및 mtest를 사용하여 UpdateOne의 UpdateResult를 시뮬레이션하는 방법을 소개합니다. 이 방법을 통해 테스트 환경에서 UpdateResult 개체를 시뮬레이션하고 이에 대한 다양한 작업 및 검증을 수행할 수 있습니다. 이 기술은 개발자가 코드를 더 잘 테스트하고 디버그할 수 있도록 지원하여 프로덕션 환경에서 안정성과 신뢰성을 보장합니다. 이 글에서는 독자들이 빠르게 시작하고 실제 프로젝트에 적용할 수 있도록 Go Mongo-Driver와 mtest를 사용하는 단계와 샘플 코드를 자세히 소개합니다. 함께 탐험해 보세요!

질문 내용

mtest 包(https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo/integration/mtest)对我的 mongodb 调用执行一些模拟结果测试,但我似乎无法弄清楚如何正确模拟对集合进行 updateone(...) 调用时返回的 *mongo.updateresult값을 사용하려고 합니다.

다음은 문제를 보여주는 코드 조각입니다.

으아아아

collection.updateone(context.background(), filter, update) 调用工作得很好。没有返回任何错误。不幸的是,updateresult.modifiedcount 값은 항상 0입니다.

나는 mtest.createsuccessresponse(...) 和 和 bson.d 的多种组合,使用 nmodifiedn (如代码片段中所示)等名称,以及 modifiedcount matchedcountphp cnendcphpcn.cn을 시도했지만 아무것도 문제를 해결하지 못하는 것 같습니다. </p> <p>이 호출이 실제로 <code>modifiedcountmodifiedcount 값을 반환하도록 시뮬레이션하는 방법이 있나요?

솔루션

package test

import (
    "context"
    "errors"
    "testing"

    "github.com/stretchr/testify/assert"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/integration/mtest"
)

func UpdateOneCall(mongoClient *mongo.Client) error {
    filter := bson.D{{Key: "SomeIDField", Value: "SomeID"}}
    update := bson.D{{Key: "$set", Value: bson.D{{Key: "ANewField", Value: true}}}}
    collection := mongoClient.Database("SomeDatabase").Collection("SomeCollection")
    updateResult, err := collection.UpdateOne(context.Background(), filter, update)
    if err != nil {
        return err
    }
    if updateResult.ModifiedCount != 1 {
        return errors.New("no field was updated")
    }
    return nil
}

func TestUpdateOneCall(t *testing.T) {
    mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
    defer mt.Close()

    mt.Run("Successful Update", func(mt *mtest.T) {

        mt.AddMockResponses(mtest.CreateSuccessResponse(
            bson.E{Key: "NModified", Value: 1},
            bson.E{Key: "N", Value: 1},
        ))

        err := UpdateOneCall(mt.Client)

        assert.Nil(t, err, "Should have successfully triggered update")
    })
}
로그인 후 복사

수정 개수: 1

을 얻는 데 도움이 되었습니다.

위 내용은 Go Mongo-Driver 및 mtest를 사용하여 UpdateOne의 모의 UpdateResult의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:stackoverflow.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!