微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在Xamarin.UITest项目中使用WireMock.Net?

我的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");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。