user3527975
user3527975

Reputation: 1773

MVC Controller test using MOq

I want to test the given method using Moq. How do I make my controller use moq objects? New objects are being created inside the controller method. One of the class is datacontext and other one is also a concrete class. Facing trouble in creating a mock for these classes alslo.

//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");
                }

Upvotes: 0

Views: 149

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11340

You need to use Dependency Injection and a good IoC like Ninject. Instantiating data objects inside your methods is a no go if you want unit tests.

Upvotes: 1

Related Questions