Quickstart

MockServer

qianmoQqianmoQ· 更新于 2026-10-14· 阅读 26 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

MockServer

Since v0.28.0

Introduction

The Testcontainers module for MockServer. MockServer can be used to mock HTTP services by matching requests against user-defined expectations.

Adding this module to your project dependencies

Please run the following command to add the MockServer module to your Go dependencies:

go get github.com/testcontainers/testcontainers-go/modules/mockserver

Usage example

Creating a MockServer container

ctx := context.Background()

mockserverContainer, err := mockserver.Run(ctx, "mockserver/mockserver:5.15.0")
defer func() {
    if err := testcontainers.TerminateContainer(mockserverContainer); err != nil {
        log.Printf("failed to terminate container: %s", err)
    }
}()
if err != nil {
    log.Printf("failed to start container: %s", err)
    return
}

Module Reference

Run function

Info

The RunContainer(ctx, opts...) function is deprecated and will be removed in the next major release of Testcontainers for Go.

The MockServer module exposes one entrypoint function to create the MockServer container, and this function receives three parameters:

func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*MockServerContainer, error)
  • context.Context, the Go context.
  • string, the Docker image to use.
  • testcontainers.ContainerCustomizer, a variadic argument for passing options.

Image

Use the second argument in the Run function to set a valid Docker image. In example: Run(context.Background(), "mockserver/mockserver:5.15.0").

Container Options

When starting the MockServer container, you can pass options in a variadic way to configure it.

The following options are exposed by the testcontainers package.

Basic Options

Lifecycle Options

Files & Mounts Options

Build Options

Logging Options

Image Options

Networking Options

Advanced Options

Experimental Options

Container Methods

The MockServer container exposes the following methods:

URL

The URL method returns the url string to connect to the MockServer container. It returns a string with the format http://<host>:<port>.

It can be used to configure a MockServer client (github.com/BraspagDevelopers/mock-server-client), e.g.:

Using URL with the MockServer client

ctx := context.Background()

mockserverContainer, err := mockserver.Run(ctx, "mockserver/mockserver:5.15.0")
defer func() {
    if err := testcontainers.TerminateContainer(mockserverContainer); err != nil {
        log.Printf("failed to terminate container: %s", err)
    }
}()
if err != nil {
    log.Printf("failed to start container: %s", err)
    return
}

url, err := mockserverContainer.URL(ctx)
if err != nil {
    log.Printf("failed to get container URL: %s", err)
    return
}
ms := client.NewClientURL(url)

评论

登录后参与评论

正在加载评论…