C# 在MVC中模拟Web API调用
我有一个mvc应用程序,它使用restsharp调用WEB API。我正在为MVC应用程序编写测试用例。测试用例在调试模式下执行失败,当它碰到下面的Web API是MVC代码时C# 在MVC中模拟Web API调用,c#,asp.net-mvc,unit-testing,asp.net-web-api,moq,C#,Asp.net Mvc,Unit Testing,Asp.net Web Api,Moq,我有一个mvc应用程序,它使用restsharp调用WEB API。我正在为MVC应用程序编写测试用例。测试用例在调试模式下执行失败,当它碰到下面的Web API是MVC代码时 public JsonResult GetCustomerInforGrid(string ddlItem, string Searchtext) { CustomerInfoModel customerinfor = new CustomerInfoModel(); List<CustomerIn
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);
}
可能一个HttpMessageHandler在调试模式控制器中拦截请求并从web API返回您所期望的内容,它会点击line rest客户端,但无法获取配置设置。。。你能帮我解决这个问题吗?我不懂你的测试方法代码;您的断言比较两种不同的类型:
CustomerInfoModel
和CustomerInfoController
…(assert.Equals(CIM,CI);
)。顺便说一句,在哪里初始化服务器?我给我们介绍的测试方法是如何尝试断言。等于(CIM,controller);。。。。但问题是,当我运行mvc的测试用例时,我将如何启动web api。。。。是否需要进行初始化,以便MS test可以读取API的web配置路径,从DB@oldFox获取值。例如,您应该搜索SelfHostServer
;可能一个HttpMessageHandler在调试模式控制器中拦截请求并从web API返回您所期望的内容,它会点击line rest客户端,但无法获取配置设置。。。你能帮我解决这个问题吗?我不懂你的测试方法代码;您的断言比较两种不同的类型:CustomerInfoModel
和CustomerInfoController
…(assert.Equals(CIM,CI);
)。顺便说一句,在哪里初始化服务器?我给我们介绍的测试方法是如何尝试断言。等于(CIM,controller);。。。。但问题是,当我运行mvc的测试用例时,我将如何启动web api。。。。是否需要进行初始化,以便MS test可以读取API的web配置路径,从DB@oldFox获取值。例如,您应该搜索SelfHostServer
;
[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);
}