我正在尝试测试从 Request.InputStream 读取 JSON 并输出动态的控制器操作。我不明白 Mock Request.InputStream 类型应该是什么。我已经尝试将它作为 MemoryStream 并传递给它一个字节数组,但它无法读取它。
到目前为止,我的模拟看起来像这样:
var str = "{ MediaItem: null, ParentId: 2897, Post: null, PostContent: hello }";
byte[] bytes = new byte[str.Length * sizeof(char)];
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
var stream = new MemoryStream(bytes);
var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.InputStream).Returns(stream);
request.Setup(x => x.InputStream).Returns(stream);
request.Setup(x => x.Url).Returns(new Uri("http://localhost:35199/api/comment/create"));
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
CommentController controller = new CommentController(pr, ur, er, apr, ar);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
ActionResult expected = null;
ActionResult actual = controller.Create();
JSON 阅读器这样做:
public static dynamic SqueezeJson(HttpRequestBase Request)
{
var bodyText = "";
using (var stream = Request.InputStream)
{
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream))
bodyText = reader.ReadToEnd();
}
if (string.IsNullOrEmpty(bodyText)) return null;
return JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter());
}
这会引发此错误:
解析属性名称后出现无效字符。预期的':'但得到:a。路径 '',第 1 行,位置 6。
编辑:我应该提到我没有重构控制器代码的自由。