Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access method 'System.Web.Http.HttpConfiguration.DefaultFormatters()' failed

Tags:

I have problem with unit testing my WEB API controller, I'm using moq to mock up my repository, do the setup and response for it. Then initiate the controller with mocked repository. The problem is when I try to execute a call from the controller I get an exception:

Attempt by method 'System.Web.Http.HttpConfiguration..ctor(System.Web.Http.HttpRouteCollection)' to access method 'System.Web.Http.HttpConfiguration.DefaultFormatters()' failed.


at System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection routes) at System.Web.Http.HttpConfiguration..ctor() at EyeShield.Api.Tests.PersonsControllerTests.Get_Persons_ReturnsAllPersons()

To be honest do don't have an idea what could be the problem here. Do anyone has an idea what might be the issue here?

Controller:

using System; using System.Net; using System.Net.Http; using EyeShield.Api.DtoMappers; using EyeShield.Api.Models; using EyeShield.Service; using System.Web.Http;  namespace EyeShield.Api.Controllers {     public class PersonsController : ApiController     {         private readonly IPersonService _personService;          public PersonsController(IPersonService personService)         {             _personService = personService;         }          public HttpResponseMessage Get()         {             try             {                 var persons = PersonMapper.ToDto(_personService.GetPersons());                 var response = Request.CreateResponse(HttpStatusCode.OK, persons);                 return response;             }             catch (Exception e)             {                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);             }         }     } } 

Global.asax:

using EyeShield.Data.Infrastructure; using EyeShield.Data.Repositories; using EyeShield.Service; using Ninject; using Ninject.Web.Common; using System; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing;  namespace EyeShield.Api {     public class MvcApplication : NinjectHttpApplication     {         protected override void OnApplicationStarted()         {             base.OnApplicationStarted();             AreaRegistration.RegisterAllAreas();              WebApiConfig.Register(GlobalConfiguration.Configuration);             WebApiConfig.ConfigureCamelCaseResponse(GlobalConfiguration.Configuration);              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);             RouteConfig.RegisterRoutes(RouteTable.Routes);         }          protected override IKernel CreateKernel()         {             var kernel = new StandardKernel();             kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);             kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();              RegisterServices(kernel);              // Install our Ninject-based IDependencyResolver into the Web API config             GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);              return kernel;         }          private void RegisterServices(IKernel kernel)         {             // This is where we tell Ninject how to resolve service requests             kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>();             kernel.Bind<IPersonService>().To<PersonService>();             kernel.Bind<IPersonRepository>().To<PersonRepository>();         }     } } 

Unit Test:

using System.Collections.Generic; using EyeShield.Api.Controllers; using EyeShield.Api.DtoMappers; using EyeShield.Api.Models; using EyeShield.Service; using Moq; using NUnit.Framework; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Hosting;  namespace EyeShield.Api.Tests {     [TestFixture]     public class PersonsControllerTests     {         private Mock<IPersonService> _personService;          [SetUp]         public void SetUp()         {             _personService = new Mock<IPersonService>();         }          [Test]         public void Get_Persons_ReturnsAllPersons()         {             // Arrange             var fakePesons = GetPersonsContainers();              _personService.Setup(x => x.GetPersons()).Returns(PersonMapper.FromDto(fakePesons));              // here exception occurs             var controller = new PersonsController(_personService.Object)             {                 Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }             };              // Act             var response = controller.Get();             string str = response.Content.ReadAsStringAsync().Result;              // Assert             Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);         }          private static IEnumerable<PersonContainer> GetPersonsContainers()         {             IEnumerable<PersonContainer> fakePersons = new List<PersonContainer>                 {                     new PersonContainer {Id = 1, Name = "Loke", Surname = "Lamora", PersonalId = "QWE654789", Position = "Software Engineer"},                     new PersonContainer {Id = 2, Name = "Jean", Surname = "Tannen", PersonalId = "XYZ123456", Position = "Biology Lab Assistant"},                     new PersonContainer {Id = 3, Name = "Edward", Surname = "Crowley", PersonalId = "ABC654789", Position = "System Infrastructure"}                 };              return fakePersons;         }     } } 
like image 218
Avangar Avatar asked May 02 '14 17:05

Avangar


People also ask

What is httpconfiguration httproutecollection?

HttpConfiguration(HttpRouteCollection) Initializes a new instance of the HttpConfiguration class with an HTTP route collection. Properties Name

What does setcorspolicyproviderfactory do in httpconfiguration?

SetCorsPolicyProviderFactory(ICorsPolicyProviderFactory) Sets the ICorsPolicyProviderFactoryon the HttpConfiguration.(Defined by CorsHttpConfigurationExtensions.) SuppressHostPrincipal()

What are the inheritance methods in httpconfiguration?

(Inherited from Object.) GetHashCode() (Inherited from Object.) GetType() (Inherited from Object.) MemberwiseClone() (Inherited from Object.) ToString() (Inherited from Object.) Extension Methods Name Description BindParameter(Type, IModelBinder) (Defined by HttpConfigurationExtensions.) EnableCors() Overloaded.


2 Answers

Try ensuring that Microsoft.AspNet.WebApi.Client is installed.

My app wasn't working because I'd removed that for other reasons.

Open Package Manager Console and execute:

Install-Package Microsoft.AspNet.WebApi.Client

like image 194
Ev. Avatar answered Sep 17 '22 06:09

Ev.


Make sure that the following Nuget packaged libraries are at the same version:

Microsoft.AspNet.WebApi Microsoft.AspNet.WebApi.Client Microsoft.AspNet.WebApi.Core Microsoft.AspNet.WebApi.WebHost 
like image 29
GrahamJ Avatar answered Sep 18 '22 06:09

GrahamJ