My application is an ASP.NET Core 1.0 Web API.
I would like to test my controllers with the TestServer
object.
I have a controller class decorated with the Authorize
attribute.
How i get my testclient:
protected HttpClient GetTestClient(){
var builder =
new WebHostBuilder().UseContentRoot(this.path)
.UseStartup<Startup>()
.UseEnvironment("Development")
.ConfigureServices(services => services.AddTransient<IAnInterface, AMock>());
var server = new TestServer(builder);
var client = server.CreateClient();
return client;
}
a snipped of how I work with it:
[TestMethod]
public void ShouldReturnSuccessful()
{
var response = await this.client.PostAsync(Url, content);
response.EnsureSuccessStatusCode();
}
If I remove the Authorize
attribute from the controller class, alle my tests work fine but if the Authorize
attribute is set, I get System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
Which makes sense.
Now I know I could just request the Bearer Token
from the TestServer
and do the following:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "My OAauth token");
But I don't want to request a token
via the TestServer
because I dont want any userdata in my application. I think this is bad practice.
I would like to know if there is any way to test the controllers without having user data inside my code? Is there any workaround to make the tests pass with the Authorize
attribute set?
Or should it even be possible to pass Authorize
without any authentication with the server? Since the TestServer
sends real HTTP-Packages doesn't this mean if this would be testable without any authentication that attackers could get into my application too without authentication?
Any hint is highly appreciated since Iam having this problem for many days now.
Thank you