0

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"]; 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);
        }
    }
}
Gamer X.
  • 1
  • 2

1 Answers1

0

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);
        }
    }
Gamer X.
  • 1
  • 2