gpt4 book ai didi

xamarin - 如何在 Xamarin.UITest 项目中使用 WireMock.Net?

转载 作者:行者123 更新时间:2023-12-03 17:23:38 25 4
gpt4 key购买 nike

我的 UITest 项目与原始 Web 服务器配合良好,但我想使用 WireMock.net 将其替换为模拟服务器.我已经在非 UITest 项目中成功使用了它。这是我在 UI 测试项目中的代码:

    [SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}

[OneTimeSetUp]
public void InitializerOnce()
{
_mockServer = WireMockServer.Start(new WireMockServerSettings()
{
Urls = new[] { "http://localhost:12345/"},
ReadStaticMappings = true
});

_mockServer.Given(
Request.Create().WithPath("*").UsingAnyMethod())
.RespondWith(Response.Create()
.WithStatusCode(HttpStatusCode.OK).WithBody("Sample response!"));
}

[OneTimeTearDown]
public void DisposeOnce()
{
_mockServer?.Stop();
}

[Test]
public async Task Test()
{
app.Tap(c => c.Marked("MyButton"));

await Task.Delay(5000);

//Assert
Assert.IsTrue(true);
}

private WireMockServer _mockServer;
我的主要 Android 项目有以下代码:
    <Button AutomationId="MyButton" Text="Action" Clicked="Action_OnClicked"/>

private async void Action_OnClicked(object sender, EventArgs e)
{
try
{
var client = new HttpClient();

var response = await client.GetAsync("http://10.0.2.2:12345/test");// is it a correct url???
var result = await response.Content.ReadAsStringAsync();

await UserDialogs.Instance.AlertAsync($"Status:{response.StatusCode}, result:{result}");
}
catch (Exception exception)
{
await UserDialogs.Instance.AlertAsync(exception.ToString());
}
}
这是点击按钮的结果:
enter image description here

最佳答案

在单元测试中,在随机端口而不是固定端口上运行 WireMock.Net。否则,在构建服务器上运行这些单元测试时可能会遇到问题,不能 100% 保证此端口在操作系统上可用。
我的建议是在没有固定端口的情况下启动 WireMock.Net。就像:

var server = WireMockServer.Start();

// Getting the random port on which the WireMock.Net server is running, can be done like:
var port = server.Ports[0];

// Or you can also get the full URL where the WireMock.Net server is running with:
var url = server.Urls[0];
所以在你的情况下使用:
var url = _mockServer.Urls[0];
var response = await client.GetAsync(url + "/test");

关于xamarin - 如何在 Xamarin.UITest 项目中使用 WireMock.Net?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63592687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com