jeudi 10 décembre 2015

Mocking Web API call in MVC

i have mvc application which call the WEB API using the restsharp . i am writing the test cases for the MVC application. test case execution fails in the debug mode when it hit to the Web API below is the MVC code

  public JsonResult GetCustomerInforGrid(string ddlItem, string Searchtext)
        {

            CustomerInfoModel customerinfor = new CustomerInfoModel();
            List<CustomerInfoModel> listcustomerinfor = new List<CustomerInfoModel>();
            var restClient = new RestClient(ConfigurationManager.AppSettings["SWBWebApiBaseUri"]);
            var request = new RestRequest("api/CustomerInfo/GetCustomerInfo/{ddlItem}/{Searchtext}", Method.GET);
            request.AddParameter("ddlItem", ddlItem, ParameterType.UrlSegment);
            request.AddParameter("Searchtext", Searchtext, ParameterType.UrlSegment);
            var varexceptionlist = restClient.Execute<List<CustomerInfoModel>>(request);

            foreach (var item in varexceptionlist.Data)
            {

                listcustomerinfor.Add(item);
            }


            return Json(listcustomerinfor, JsonRequestBehavior.AllowGet);

        }

below is the code written in the MS test i am trying to mock it but not sure how to do. kindly provide the help/suggestion how to test the MVC controller

 [TestMethod]
        public void SearchCustomer()
        {
            String GCIN = "GC007637306A";
            CustomerInfoModel CIM = new CustomerInfoModel();

            CustomerInfoController controller = new CustomerInfoController();
            //HomeController controller = new HomeController();
            //Mock Request.Url.AbsoluteUri 
            HttpRequest httpRequest = new HttpRequest("", "http://mySomething", "");
            StringWriter stringWriter = new StringWriter();
            HttpResponse httpResponse = new HttpResponse(stringWriter);
            HttpContext httpContextMock = new HttpContext(httpRequest, httpResponse);
            controller.ControllerContext = new ControllerContext(new HttpContextWrapper(httpContextMock), new RouteData(), controller);


            CIM.CustomerName = "XXX XXXXX 549224361A";

            CustomerInfoController CI = new CustomerInfoController();
            controller.GetCustomerInforGrid("GCIN", GCIN);

            Assert.Equals(CIM, CI);

        }

Aucun commentaire:

Enregistrer un commentaire