作为单元测试的一部分,我尝试创建一个包含HTTP表单数据的模拟IOwinRequest
作为其主体。有问题的代码适用于生产(我可以通过Web浏览器发送的请求成功读取表单数据),但我无法理解我在单元测试中遇到的错误:
[TestMethod]
public async Task TestPostData()
{
String rawFormData = "test=testValue&test2=testValue2";
MemoryStream stream = new MemoryStream();
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8, 4 * 1024, true))
await writer.WriteAsync(rawFormData);
stream.Seek(0, SeekOrigin.Begin);
Mock<IOwinRequest> requestMock = new Mock<IOwinRequest>();
requestMock.SetupGet(r => r.Method).Returns("POST");
requestMock.SetupGet(r => r.Body).Returns(stream);
requestMock.SetupGet(r => r.ContentType).Returns("application/x-www-form-urlencoded");
Assert.IsNotNull(await requestMock.Object.ReadFormAsync());
}
ReadFormAsync
方法返回的表单对象为null
。我错过了什么?这是在.Net4.5和Microsoft.Owin 3.0.1
答案 0 :(得分:0)
您没有设置该方法,因此在调用时显然会返回null。
[TestMethod]
public async Task _TestPostData() {
var dictionary = new Dictionary<string, string[]>() {
{ "test", new[]{"testValue"}},
{ "test2", new[]{"testValue2"}},
};
String rawFormData = "test=testValue&test2=testValue2";
var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, Encoding.UTF8, 4 * 1024, true))
await writer.WriteAsync(rawFormData);
stream.Seek(0, SeekOrigin.Begin);
var formMock = new Mock<IFormCollection>();
formMock.Setup(_ => _.GetEnumerator()).Returns(() => dictionary.GetEnumerator());
var readableString = formMock.As<IReadableStringCollection>();
//..setup as desired
var requestMock = new Mock<IOwinRequest>();
requestMock.Setup(_ => _.Method).Returns("POST");
requestMock.Setup(_ => _.Body).Returns(stream);
requestMock.Setup(_ => _.ContentType).Returns("application/x-www-form-urlencoded");
requestMock.Setup(_ => _.ReadFormAsync()).ReturnsAsync(formMock.Object);
Assert.IsNotNull(await requestMock.Object.ReadFormAsync());
}
但鉴于此问题似乎是XY problem。在这个答案中,我可以提供的设置并不多。