I have written some integration tests using Microsoft.AspNetCore.TestHost, But when I try to get a message as Invalid URI.
I can create TestServer successfully and able to create a client. But when I call an API using the client it says invalid URI. The URL created by TestHost is http://localhost/ and there is nothing look wrong in that URL.
I am not able to understand how could this URL be wrong. There is no other localhost website running in my machine also.
When I run my web API it's run on this URL Http:\localhost:5000 and set that as base address in my test project but it still throws the same error.
This my code to build Test Server
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();
}
This is a code to make a request.
public async Task<string> GetToken()
{
try
{
if (string.IsNullOrEmpty(token))
{
//var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", "[email protected]"), new KeyValuePair<string, string>("password", "Password123!") });
var content = new StringContent("{email:'[email protected]',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 "";
}
I am not sure what is a valid URL, but this setup was working earlier.
Try changing:
To: