gpt4 book ai didi

c# - 如何在单元测试中创建json post到mvc Controller

转载 作者:太空狗 更新时间:2023-10-30 01:15:06 26 4
gpt4 key购买 nike

Controller 的方法需要 json post,例如...

public class MyController : Controller
{
[HttpPost]
public ActionResult PostAction()
{
string json = new StreamReader(Request.InputStream).ReadToEnd();
//do something with json
}
}

当您尝试测试它时,您如何设置单元测试以将发布数据发送到 Controller ?

最佳答案

要传递数据,您可以使用模拟的 http 上下文设置 Controller 上下文,并传递请求主体的虚假流。

使用最小起订量来伪造请求。

[TestClass]
public class MyControllerTests {
[TestMethod]
public void PostAction_Should_Receive_Json_Data() {
//Arrange

//create a fake stream of data to represent request body
var json = "{ \"Key\": \"Value\"}";
var bytes = System.Text.Encoding.UTF8.GetBytes(json.ToCharArray());
var stream = new MemoryStream(bytes);

//create a fake http context to represent the request
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(m => m.Request.InputStream).Returns(stream);

var sut = new MyController();
//Set the controller context to simulate what the framework populates during a request
sut.ControllerContext = new ControllerContext {
Controller = sut,
HttpContext = mockHttpContext.Object
};

//Act
var result = sut.PostAction() as ViewResult;

//Assert
Assert.AreEqual(json, result.Model);
}

public class MyController : Controller {
[HttpPost]
public ActionResult PostAction() {
string json = new StreamReader(Request.InputStream).ReadToEnd();
//do something with json
//returning json as model just to prove it received the data
return View((object)json);
}
}
}

有了这个,现在有一些建议。

不要重新发明轮子。

MVC 框架已经提供了解释发送到 Controller 操作的数据的功能(横切关注点)。这样您就不必担心必须对模型进行水合才能使用。该框架将为您完成。它将使您的 Controller 操作更清晰,更易于管理和维护。

如果可能,您应该考虑向您的操作发送强类型数据。

public class MyController : Controller {
[HttpPost]
public ActionResult PostAction(MyModel model) {
//do something with model
}
}

框架基本上会完全按照您在操作中手动执行的操作执行,方法是使用其 ModelBinder 执行所谓的参数绑定(bind)。如果它们匹配,它将反序列化请求的主体并将传入数据的属性绑定(bind)到操作参数。

有了它,它还可以更轻松地对 Controller 进行单元测试

[TestClass]
public class MyControllerTests {
[TestMethod]
public void PostAction_Should_Receive_Json_Data() {
//Arrange

var model = new MyModel {
Key = "Value"
};

var sut = new MyController();

//Act
var result = sut.PostAction(model);

//Assert
//...assertions here.
}
}

关于c# - 如何在单元测试中创建json post到mvc Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907762/

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