D3v*_*D3v 1 c# json unit-testing moq asp.net-web-api
我正在尝试基本上做标题所说的为了对我的api控制器进行单元测试,但我找不到合适的方法并且无法承担花费太多时间.这是我的代码.
[TestMethod]
public void Should_return_a_valid_json_result()
{
// Arrange
Search search = new Search();
search.Area = "test";
string json = JsonConvert.SerializeObject(search);
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
request.Setup(r => r.HttpMethod).Returns("POST");
request.Setup(r => r.InputStream.ToString()).Returns(json);
context.Setup(c => c.Request).Returns(request.Object);
var controller = new UserController();
controller.ControllerContext = new HttpControllerContext() { RequestContext = context };
//more code
}
Run Code Online (Sandbox Code Playgroud)
最后一行返回错误CS0029无法将类型'Moq.Mock System.Web.HttpContextBase'隐式转换为'System.Web.Http.Controllers.HttpRequestContext'.
我也不确定我应该使用的Moq语法,其他问题,示例和Moq文档对我没什么帮助.
如果只是为了传递请求,则无需在此处进行模拟.
[TestMethod]
public void Should_return_a_valid_json_result() {
// Arrange
var search = new Search();
search.Area = "test";
var json = JsonConvert.SerializeObject(search);
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.Content = new StringContent(json);
var controller = new UserController();
controller.Request = request;
//more code
}
Run Code Online (Sandbox Code Playgroud)
我正在使用这种方法
var json = JsonConvert.SerializeObject(request);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var httpContext = new DefaultHttpContext()
{
Request = { Body = stream, ContentLength = stream.Length }
};
var controllerContext = new ControllerContext { HttpContext = httpContext };
var controller = new Your_Controller(logic, logger) { ControllerContext = controllerContext };
Run Code Online (Sandbox Code Playgroud)