样品code单元测试API控制器样品、控制器、单元测试、code

2023-09-03 09:12:48 作者:乄愛!

是否有样本code,显示单元测试控制器,它继承了API控制器? 我试图单元测试后,但它是失败的。我相信,我需要建立HttpControllerContext进行测试,但不知道如何 谢谢

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 the HttpControllerContext for testing but don't know how Thanks

推荐答案

这code必须展示出一种事后检验的基础知识。假定您已经注入到控制器的存储库。我使用MVC 4 RC不是beta这里,如果你使用的是测试版的Request.CreateResponse(...是有点不同的,因此给我留言...

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...

由于控制器$ C C有点$像这样的:

Given controller code a little like this:

public class FooController : ApiController
{
    private IRepository<Foo> _fooRepository;

    public FooController(IRepository<Foo> fooRepository)
    {
        _fooRepository = fooRepository;
    }

    public HttpResponseMessage Post(Foo value)
    {
        HttpResponseMessage response;

        Foo returnValue = _fooRepository.Save(value);
        response = Request.CreateResponse<Foo>(HttpStatusCode.Created, returnValue, this.Configuration);
        response.Headers.Location = "http://server.com/foos/1";

        return response;
    }
}

单元测试看起来有点像这个(NUnit的和RhinoMock)

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

        Foo dto = new Foo() { 
            Id = -1,
            Name = "Hiya" 
        };

        IRepository<Foo> fooRepository = MockRepository.GenerateMock<IRepository<Foo>>();
        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<Foo>().Result;
        Assert.IsNotNull(resultFoo, "Response was empty!");
        Assert.AreEqual(1, resultFoo.Id, "Foo id should be set");