Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

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

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;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...