[英]how can I assign real/fake object to binding context for Xunit test (Model Binding)?
this is the method i want to test这是我要测试的方法
public class DataRequestQueryBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var jsonString = bindingContext.ActionContext.HttpContext.Request.Query["request"];
if (string.IsNullOrWhiteSpace(jsonString))
{
throw new ArgumentNullException("request");
}
var result = JsonConvert.DeserializeObject<DataRequestQuery>(jsonString);
bindingContext.Result = ModelBindingResult.Success(result);
return Task.CompletedTask;
}
}
i am new in unit testing below is my attempt for Xunit test but i want to give it the real object manually by code, or just prepare bindingContext.ActionContext.HttpContext.Request.Query["request"];
我是单元测试的新手,下面是我对 Xunit 测试的尝试,但我想通过代码手动给它真正的 object,或者只是准备
bindingContext.ActionContext.HttpContext.Request.Query["request"];
if required.如果需要。
public class DataRequestQueryBinderTest
{
[Fact]
public async Task BindingModleAsyncTest()
{
DataRequestQueryBinder dta = new DataRequestQueryBinder();
ModelBindingContext bindingContext = Substitute.For<ModelBindingContext>();
//await dta.BindModelAsync(bindingContext);
//bindingContext.ActionContext.HttpContext
var value1 = dta.BindModelAsync(bindingContext);
//var value = Task.Run(async () => await dta.BindModelAsync(bindingContext));
Assert.True(dta.BindModelAsync(bindingContext).IsCompleted);
Assert.NotNull(value1);
}
}
}
late but i found the solution by myself, it may help other person, just look at the solution i did.晚了,但我自己找到了解决方案,它可能会帮助其他人,看看我做的解决方案。
public class DataRequestQueryBinderTest
{
[Fact]
public async Task BindModelAsyncTest()
{
//--- assemble
var requestFake = new HttpRequestFeature();
requestFake.QueryString = "request={// your own request}";
var features = new FeatureCollection();
features.Set<IHttpRequestFeature>(requestFake);
var fakeHttpContext = new DefaultHttpContext(features);
var bindingContext = new DefaultModelBindingContext
{
ModelName = "CustomQueryExpr",
ActionContext = new ActionContext()
{
HttpContext = fakeHttpContext,
},
};
var binder = new DataRequestQueryBinder();
//--- act
await binder.BindModelAsync(bindingContext);
//--- assert
Assert.True(bindingContext.Result.IsModelSet);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.