使用MockServer進行整合測試

進行整合測試的時候,有些專案會依賴外部服務,以前是將外部服務抽成介面並進行抽換,但是這方法並不是很好。之前剛好使用MockServer進行壓力測試及相關測試。所以想說在整合測試裡面使用Docker去啟動MockServer方式。
這邊使用 TestContainer 進行架設 MockServer 的 Docker。(下面其中的 MockServerClientNet 套件可以選擇不使用。只是去設定MockServer相關期望比較簡單而已。)

安裝方式

1
2
dotnet add package Testcontainers
dotnet add package MockServerClientNet

建立 MockServer 的 TestContainer

  • MockServerConfiguration.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public sealed class MockServerConfiguration : ContainerConfiguration
{
public MockServerConfiguration() { }

public MockServerConfiguration(IResourceConfiguration<CreateContainerParameters> resourceConfiguration)
: base(resourceConfiguration) { }

public MockServerConfiguration(IContainerConfiguration resourceConfiguration)
: base(resourceConfiguration) { }

public MockServerConfiguration(MockServerConfiguration resourceConfiguration)
: base(new MockServerConfiguration(),resourceConfiguration) { }

public MockServerConfiguration(MockServerConfiguration oldValue, MockServerConfiguration newValue)
: base(oldValue, newValue) { }
}
  • MockServerBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public sealed class MockServerBuilder : ContainerBuilder<MockServerBuilder, MockServerContainer, MockServerConfiguration>
{
public const string MockServerImage = "mockserver/mockserver:latest";

public const ushort MockServerPort = 1080;

public MockServerBuilder()
: this(new MockServerConfiguration())
{
DockerResourceConfiguration = Init().DockerResourceConfiguration;
}

private MockServerBuilder(MockServerConfiguration resourceConfiguration)
: base(resourceConfiguration)
{
DockerResourceConfiguration = resourceConfiguration;
}

protected override MockServerConfiguration DockerResourceConfiguration { get; }

public override MockServerContainer Build()
{
Validate();
return new MockServerContainer(DockerResourceConfiguration);
}

protected override MockServerBuilder Init()
{
return base.Init()
.WithImage(MockServerImage)
.WithPortBinding(MockServerPort, true);
}

protected override MockServerBuilder Clone(IResourceConfiguration<CreateContainerParameters> resourceConfiguration)
{
return Merge(DockerResourceConfiguration, new MockServerConfiguration(resourceConfiguration));
}

protected override MockServerBuilder Clone(IContainerConfiguration resourceConfiguration)
{
return Merge(DockerResourceConfiguration, new MockServerConfiguration(resourceConfiguration));
}

protected override MockServerBuilder Merge(MockServerConfiguration oldValue, MockServerConfiguration newValue)
{
return new MockServerBuilder(new MockServerConfiguration(oldValue, newValue));
}
}
  • MockServerContainer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public sealed class MockServerContainer : DockerContainer
{
private readonly MockServerConfiguration _configuration;

public MockServerContainer(MockServerConfiguration configuration)
: base(configuration)
{
_configuration = configuration;
}

/// <summary>
/// Retrieves the MockServer endpoint.
/// </summary>
/// <returns>The endpoint URL of the MockServer.</returns>
public string GetEndpoint()
{
return $"http://{Hostname}:{GetMappedPublicPort(MockServerBuilder.MockServerPort)}";
}
}

上面這三個類別的實作方式都可以在官方文件上找到。
這邊也提供 Testcontainers.ModuleName 相關範例。

整合測試相關設定與啟動

MockServerFixture.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

public static class MockServerFixture
{
public static MockServerContainer CreateContainer(MockServerSetting mockServerSetting, string environmentName)
{
var containerName = mockServerSetting.ContainerName;
var container = new MockServerBuilder()
.WithImage($"{mockServerSetting.Image}:{mockServerSetting.Tag}")
.WithEnvironment(mockServerSetting.EnvironmentSettings)
.WithName($"{environmentName}-{containerName}")
.WithPortBinding(mockServerSetting.HostPort, mockServerSetting.ContainerPort)
.WithAutoRemove(true)
.Build();
return container;
}
}

ProjectFixture.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class ProjectFixture : IAsyncLifetime
{

private static MockServerContainer _mockServerContainer;

public static string EnvironmentName { get; set; }

/// <summary>
/// Initializes a new instance of the <see cref="ProjectFixture"/> class
/// </summary>
public ProjectFixture()
{
// 確保路徑跨平台運行
var baseDirectory = AppContext.BaseDirectory;
var settingsFilePath = Path.Combine(baseDirectory, "TestSettings.json");

TestSettingProvider.FilePath = settingsFilePath;

EnvironmentName = TestSettingProvider.GetEnvironmentName(typeof(ProjectFixture));

// Create Mock Server
var mockServerSettings = TestSettingProvider.GetMockServerSettings();

_mockServerContainer = MockServerFixture.CreateContainer(mockServerSettings, EnvironmentName);

}

internal static Uri MockServerEndpoint => new Uri(_mockServerContainer.GetEndpoint());

/// <summary>
/// Initializes this instance
/// </summary>
public async Task InitializeAsync()
{
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));

await _mockServerContainer.StartAsync(cts.Token);
}

/// <summary>
/// Disposes this instance
/// </summary>
public async Task DisposeAsync()
{
await _mockServerContainer.StopAsync();
await _mockServerContainer.DisposeAsync();
}
}

整合測試測試Restful API,這邊使用了FlentAssertions.Web進行驗證。這邊就不贅述。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
[Collection(nameof(ProjectCollectionFixture))]
public class SampleControllerTests
{
protected TestWebApplicationFactory<Program> TestWebApplicationFactory { get; }

protected HttpClient HttpClient { get; }

public SampleControllerTests()
{
this.TestWebApplicationFactory = new TestWebApplicationFactory<Program>();
this.HttpClient = TestWebApplicationFactory.CreateDefaultClient();
}

[Fact(DisplayName = "GetAsync_應返回正確的資料")]
public async Task GetAsync_ShouldReturnCorrectData()
{
// arrange
var expectedResponse = new List<string> { "Item1", "Item2", "Item3" };

// 設置 MockServer 的模擬回應
var mockServerEndPoint = ProjectFixture.MockServerEndpoint;
var mockServerClient = new MockServerClient(mockServerEndPoint.Host, mockServerEndPoint.Port);

var mockServerRequest = new HttpRequest()
.WithPath("/details")
.WithMethod(HttpMethod.Get);

var mockServerResponse = new HttpResponse()
.WithStatusCode(HttpStatusCode.OK)
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(new []
{
"Item1", "Item2", "Item3"
}))
.WithDelay(TimeSpan.FromMilliseconds(100));

await mockServerClient.When(mockServerRequest)
.RespondAsync(mockServerResponse);

var url = "api/sample";

// act
var response = await HttpClient.GetAsync(url);

// assert
response.Should().Be200Ok().And.BeAs(expectedResponse);
}
}

關於上面的程式碼也提供在個人Github上面有完整的整合測試及 MockServer TestContainer