我正在尝试使用 MSTest 和 Moq 为将 json 从表单发布到数据库的实时系统设置单元测试。系统本身工作得很好,但我的任务是尝试为它构建一些测试。我正在使用的视图中的 ajax 调用遵循控制器之一的 HttpPost 方法:
[HttpPost]
public ActionResult Add(Request model)
{
return ProcessRequest(model, UserAction.Create);
}
这导致 WebAPI 控制器:
public int Post([FromBody]Request value)
{
try
{
var id = myRepository.AddRequest(value);
foreach (var day in value.Days)
{
day.RequestId = id;
myRepository.AddRequestDay(day);
}
return id;
}
catch
{
return -1;
}
}
通过我的测试,我认为使用 TransactionScope 是一个好主意,所以我实际上并没有在数据库中保存任何数据。如果有更好的方法,请赐教:
[TestMethod]
public void API_Request_Post()
{
using (TransactionScope ts = new TransactionScope())
{
var jsonObject = //some json scraped from a test post
var request = new Mock<HttpRequestBase>();
//This is where I'm stuck. I can't find anything in Setup that lets me prep the Post body for when the controller gets to it.
//request.Setup(x => x.InputStream).Returns(jsonObject);
RequestController controller = new RequestController();
//This is another point that I don't understand. I make the call for post happy with a reference to the model instead of the actual json?
var result = controller.Post(new Models.Request() );
Assert.IsTrue(result > -1);
}
}
任何试图确定我需要将 json 提供给 HttpRequest 的哪一部分的帮助将不胜感激(并且帮助我理解 Post 只是锦上添花)。