篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Web API集成测试相关的知识,希望对你有一定的参考价值。
public class HelpApiIntegrationTests : ApiIntegrationTests, IUseFixture<ApiIntegrationFixture>
{
public void SetFixture(ApiIntegrationFixture data)
{
Fixture = data;
}
[Fact, IntegrationTest]
public void Example_Test()
{
var client = new HttpClient(Fixture.Server);
var command = new SomeCommand {CommandID = 1};
using (var request = CreateRequest("api/test/command", command, HttpMethod.Post))
using (var response = client.SendAsync(request, new CancellationTokenSource().Token).Result)
{
Assert.NotNull(response.Content);
Assert.Equal(response.StatusCode, HttpStatusCode.OK);
}
}
}
public abstract class ApiIntegrationTests
{
private const string _url = "http://www.domain.com";
protected static string Url
{
get { return _url; }
}
public ApiIntegrationFixture Fixture { get; set; }
public HttpRequestMessage CreateRequest<T>(string url, T content, HttpMethod method = null, string mthv = "application/json", MediaTypeFormatter formatter = null) where T : class
{
var request = CreateRequest(url, mthv, method);
request.Content = new ObjectContent<T>(content, formatter ?? new JsonMediaTypeFormatter());
return request;
}
protected HttpRequestMessage CreateRequest(string url, string mthv = "application/json", HttpMethod method = null)
{
var request = new HttpRequestMessage { RequestUri = new Uri(Url + url) };
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
request.Method = method ?? HttpMethod.Get;
return request;
}
protected static string SerializeObject<T>(T item)
{
return JsonConvert.SerializeObject(item, Formatting.None, new JsonSerializerSettings { ContractResolver = new SitecoreItemBaseContractResolver() });
}
}
public class ApiIntegrationFixture : IDisposable
{
public ApiIntegrationFixture()
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
//remember to add all filters
config.Filters.Add(new ValidationActionFilter());
//Configure IOC
Bootstrapper.Bootstrap();
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(Bootstrapper.Container);
Server = new HttpServer(config);
}
public HttpServer Server { get; set; }
public void Dispose()
{
if (Server != null)
{
Server.Dispose();
}
}
}