packagemongodbimport("context""github.com/testcontainers/testcontainers-go""github.com/testcontainers/testcontainers-go/wait")// mongodbContainer represents the mongodb container type used in the moduletypemongodbContainerstruct{testcontainers.Container}// setupMongoDB creates an instance of the mongodb container typefuncsetupMongoDB(ctxcontext.Context)(*mongodbContainer,error){req:=testcontainers.ContainerRequest{Image:"mongo:6",ExposedPorts:[]string{"27017/tcp"},WaitingFor:wait.ForAll(wait.ForLog("Waiting for connections"),wait.ForListeningPort("27017/tcp"),),}container,err:=testcontainers.GenericContainer(ctx,testcontainers.GenericContainerRequest{ContainerRequest:req,Started:true,})iferr!=nil{returnnil,err}return&mongodbContainer{Container:container},nil}
packagemongodbimport("context""fmt""testing""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")funcTestMongoDB(t*testing.T){ctx:=context.Background()container,err:=setupMongoDB(ctx)iferr!=nil{t.Fatal(err)}// Clean up the container after the test is completet.Cleanup(func(){iferr:=container.Terminate(ctx);err!=nil{t.Fatalf("failed to terminate container: %s",err)}})// perform assertionsendpoint,err:=container.Endpoint(ctx,"mongodb")iferr!=nil{t.Error(fmt.Errorf("failed to get endpoint: %w",err))}mongoClient,err:=mongo.NewClient(options.Client().ApplyURI(endpoint))iferr!=nil{t.Fatal(fmt.Errorf("error creating mongo client: %w",err))}err=mongoClient.Connect(ctx)iferr!=nil{t.Fatal(fmt.Errorf("error connecting to mongo: %w",err))}err=mongoClient.Ping(ctx,nil)iferr!=nil{t.Fatal(fmt.Errorf("error pinging mongo: %w",err))}}