gpt4 book ai didi

.net - 用于单元测试 api Controller 的示例代码

转载 作者:行者123 更新时间:2023-12-03 13:35:23 24 4
gpt4 key购买 nike

是否有显示单元测试从 api Controller 继承的 Controller 的示例代码?
我正在尝试对 POST 进行单元测试,但它失败了。我相信我需要设置 HttpControllerContext 进行测试,但不知道如何
谢谢

最佳答案

此代码应演示后测试的基础知识。假设您有一个存储库注入(inject)到 Controller 中。如果您使用的是 Beta,我在这里使用的是 MVC 4 RC 而不是 Beta,Request.CreateResponse(... 有点不同,所以请给我留言...

给定 Controller 代码有点像这样:

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)
        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");

关于.net - 用于单元测试 api Controller 的示例代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com