2014-10-08 125 views
0

我想使用Moq測試給定的方法。我如何讓我的控制器使用moq對象?控制器方法內部正在創建新的對象。其中一個類是datacontext,另一個類也是一個具體類。在爲這些課程創建模擬方面面臨麻煩。使用MOQ的MVC控制器測試

//My Controller class action method 
    public ActionResult GetRelatedCourses(int stuId) 
       { 
        if (Request.Cookies["RememberUsername"] != null) 
        { 
         if (System.Web.HttpContext.Current.Cache.Get(userName) == null) 
         { 
          CacheUtil.UpdateCache(userName); 
         } 
         Dictionary<string, int> sectionsCourses = (Dictionary<string, int>)System.Web.HttpContext.Current.Cache.Get(userName); 
         if (sectionsForums.ContainsValue(stuId)) 
         { 
          var contextWrapper = new DataContextWrapper(dataContext); 
          var courseRepository = new CourseRepository(contextWrapper); 
          bool Student_Exists = StudentExists(stuId); 
          if (Student_Exists) 
          { 
           IEnumerable<Course> course = courseRepository.GetRelatedCourses(stuId); 
           var UserProfiles = contextWrapper.dataContext.usp_GetUserProfilesByStudentID(stuId).ToList(); 
           ViewBag.UserProfiles = UserProfiles; 
           if (course.Count() == 0) 
           { 
            ViewBag.ErrorMessage = "No courses available."; 
           } 
           return View(courses); 
          } 
          return View("NoStudentExists"); 
         } 
        } 
        return View("NoAccess"); 
       } 
+0

@Patrick Quirk:有什麼建議嗎? – user3527975 2014-10-13 23:53:33

回答

1

您需要使用依賴注入和像Ninject這樣的良好IoC。如果你想要單元測試,在你的方法中實例化數據對象是不行的。

+0

問題在於代碼已經存在了。我必須寫測試。除了去改變代碼之外別無他法嗎? – user3527975 2014-10-14 01:55:12