Sample code for unit testing api controllers

后端 未结 4 870
遥遥无期
遥遥无期 2021-02-04 03:44

Is there an sample code that shows unit testing a controller that inherits from the api controller? I am trying to unit test a POST but it is failing. I believe I need to set up

4条回答
  •  孤独总比滥情好
    2021-02-04 04:29

    this code should demonstrate the basics of a post test. Assumes you have a repository injected into the controller. I am using MVC 4 RC not Beta here if you are using Beta the Request.CreateResponse(... is a little different so give me a shout...

    Given controller code a little like this:

    public class FooController : ApiController
    {
        private IRepository _fooRepository;
    
        public FooController(IRepository fooRepository)
        {
            _fooRepository = fooRepository;
        }
    
        public HttpResponseMessage Post(Foo value)
        {
            HttpResponseMessage response;
    
            Foo returnValue = _fooRepository.Save(value);
            response = Request.CreateResponse(HttpStatusCode.Created, returnValue, this.Configuration);
            response.Headers.Location = "http://server.com/foos/1";
    
            return response;
        }
    }
    

    The unit test would look a little like this (NUnit and RhinoMock)

            Foo dto = new Foo() { 
                Id = -1,
                Name = "Hiya" 
            };
    
            IRepository fooRepository = MockRepository.GenerateMock>();
            fooRepository.Stub(x => x.Save(dto)).Return(new Foo() { Id = 1, Name = "Hiya" });
    
            FooController controller = new FooController(fooRepository);
    
            controller.Request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/foos");
            //The line below was needed in WebApi RC as null config caused an issue after upgrade from Beta
            controller.Configuration = new System.Web.Http.HttpConfiguration(new System.Web.Http.HttpRouteCollection());
    
            var result = controller.Post(dto);
    
            Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Expecting a 201 Message");
    
            var resultFoo = result.Content.ReadAsAsync().Result;
            Assert.IsNotNull(resultFoo, "Response was empty!");
            Assert.AreEqual(1, resultFoo.Id, "Foo id should be set");
    

提交回复
热议问题