【问题标题】:TestHost generating Invalid URI: The format of the URI could not be determinedTestHost 生成无效的 URI:无法确定 URI 的格式
【发布时间】:2019-08-26 11:47:32
【问题描述】:

我已经使用 Microsoft.AspNetCore.TestHost 编写了一些集成测试,但是当我尝试获取无效 URI 消息时。

我可以成功创建 TestServer 并且能够创建客户端。但是当我使用客户端调用 API 时,它会显示无效的 URI。 TestHost 创建的 URL 是 http://localhost/,该 URL 看起来没有任何问题。

我无法理解这个 URL 怎么可能是错误的。我的机器上也没有运行其他 localhost 网站。

当我运行我的 Web API 时,它会在这个 URL Http:\localhost:5000 上运行,并将其设置为我的测试项目中的基地址,但它仍然会引发相同的错误。

这是我构建测试服务器的代码

public MongoDbFixture()
        {
            var builder = new WebHostBuilder()
                   .UseContentRoot(GetContentRootPath())
                   .UseEnvironment("Test")
                   .UseConfiguration(new ConfigurationBuilder()
                   .SetBasePath(GetContentRootPath())
                   .AddJsonFile("appsettings.Test.json")
                   .Build())
                   .UseStartup<Startup>();  // Uses Start up class from your API Host project to configure the test server

            _testServer = new TestServer(builder);
            Client = _testServer.CreateClient();
            //Client.BaseAddress = new Uri("http://localhost:5000/");
            AuthClient = _testServer.CreateClient();
            //AuthenticateClient();
            //AddPromptQuestions();
            //SetupGoogleTranslationService();
        }

这是发出请求的代码。

 public async Task<string> GetToken()
        {
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    //var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", "kunal.ahmedabad@gmail.com"), new KeyValuePair<string, string>("password", "Password123!") });
                    var content = new StringContent("{email:'test@test.com',password:'Integration#85'}", Encoding.UTF8, "application/json");
                    var response = await Client.PostAsync(new Uri("api/Accounts/Login"), content).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();
                    //var token = await response.Content.ReadAsAsync<OkResult>();
                    var newToken = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var tokenResponse = JsonConvert.DeserializeAnonymousType(newToken, new { Token = "", IsPhoneNumberConfirmed = "" });
                    token = tokenResponse.Token;
                    //token = newToken.Split(":")[1].Replace("\"", "").Replace("}", "");//todo:add better logic to read token.    
                    return token;
                }
            }
            catch (Exception)
            {
            }
            return "";
        }

我不确定什么是有效的 URL,但此设置在早期就可以使用。

【问题讨论】:

    标签: asp.net-core integration-testing asp.net-core-testhost


    【解决方案1】:

    尝试改变:

    new Uri("api/Accounts/Login")
    

    收件人:

    new Uri("api/Accounts/Login", UriKind.Relative)
    

    【讨论】:

    • 哇...这工作。是不是因为它之前没有这个而在框架中发生了一些新变化。
    • 所以早些时候我们使用字符串而不是 Uri,我们将字符串替换为 URI,因为 FxCop 显示使用字符串类型的警告。我应该在那个时候进行测试,这会节省我的时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2013-12-15
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多