【发布时间】: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