feanz
4/2/2014 - 2:47 PM

AutoMoq Web Api Controllers

AutoMoq Web Api Controllers

public class AutoMoqWebApiDataAttribute : AutoDataAttribute
	{
		public AutoMoqWebApiDataAttribute()
			: base(new Fixture().Customize(new AutoMoqWebApiCustomization()))
		{
		}
	}

	public class AutoMoqWebApiCustomization : CompositeCustomization
	{
		public AutoMoqWebApiCustomization()
			: base(new HttpRequestMessageCustomization(),
			new ApiControllerCustomization(),
			new AutoMoqCustomization())
		{
		}

		private class ApiControllerCustomization : ICustomization
		{
			public void Customize(IFixture fixture)
			{
				fixture.Customizations.Add(
					new FilteringSpecimenBuilder(
						new Postprocessor(new MethodInvoker(new ModestConstructorQuery()),new ApiControllerFiller()),new ApiControllerSpecification()));
			}

			private class ApiControllerFiller : ISpecimenCommand
			{
				public void Execute(object specimen, ISpecimenContext context)
				{
					if (specimen == null)
						throw new ArgumentNullException("specimen");
					if (context == null)
						throw new ArgumentNullException("context");

					var target = specimen as ApiController;
					if (target == null)
						throw new ArgumentException(
							"The specimen must be an instance of ApiController.",
							"specimen");

					target.Request =
						(HttpRequestMessage)context.Resolve(
							typeof(HttpRequestMessage));
				}
			}

			private class ApiControllerSpecification : IRequestSpecification
			{
				public bool IsSatisfiedBy(object request)
				{
					var requestType = request as Type;
					return requestType != null && typeof(ApiController).IsAssignableFrom(requestType);
				}
			}
		}
		
		private class HttpRequestMessageCustomization : ICustomization
		{
			public void Customize(IFixture fixture)
			{
				fixture.Customize<HttpRequestMessage>(c => c
					.Without(x => x.Content)
					.Do(x => x.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration()));
			}
		}
	}