使用Moq模拟OData客户端的容器

gee*_*ran 10 c# asp.net-mvc unit-testing moq odata

我正在使用OData V4客户端在我的asp.net mvc 5中创建代理.我想使用Moq对控制器进行单元测试.有没有办法可以通过容器模拟OData服务响应.下面是OData容器实例化器:

    public static class ControlEntityContextHelper
    {
         /// <summary>
         /// Returns OData service context
         /// </summary>
         /// <returns></returns>
         public static Container GetEntityContext()
         {
             // create the container
             var container = new Container(new Uri("http://localhost/services/odata/"));
             container.Timeout = 1800;
             return container;
          }
     } 
Run Code Online (Sandbox Code Playgroud)

下面是MVC控制器:

    public JsonResult GetEmployees(string employeeId)
    {
        var odataContext = ControlEntityContextHelper.GetEntityContext();
        var employee = odataContext.Employees.Where(emp => emp.EmployeeId == employeeId);
        return Json(employee, JsonRequestBehavior.AllowGet);
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

ska*_*kin 2

尝试添加这个:

public interface IEmployeeRepository
{
    Employee GetById(string id);
}

public class EmployeeRepository: IEmployeeRepository
{
    public Employee GetById() {//access to OData}
} 
Run Code Online (Sandbox Code Playgroud)

然后将你的控制器更改为

public JsonResult GetEmployees(string employeeId)
  {
        var employee = employeeRepository.GetById(employeeId);
        return Json(employee, JsonRequestBehavior.AllowGet);
  }
Run Code Online (Sandbox Code Playgroud)

然后您将能够轻松地访问您的数据访问层。