csharp Web API集成测试

Posted

tags:

篇首语:本文由小常识网(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();
			}
		}
	}

以上是关于csharp Web API集成测试的主要内容,如果未能解决你的问题,请参考以下文章

csharp MVC和Web Api Unity集成

在 Visual Studio 2013 中使用 HttpClient 进行单元测试/集成测试 Web API

如何使用 WebApplicationFactory 对 .NET 6 Web Api 项目进行集成测试?

ASP.NET Core 6 Web API 的集成测试引发 System.InvalidOperationException

Web API - owin 中的 HttpContext.Current 问题,用于使用 moq 进行集成测试

csharp Web API