0

I am new to Nunit and Moq framework and am totally stuck in testing for one of my controller as it fetches some of the values from Request.Form["Something"]. I am able to test for the other part of the controller method using nunit but the code is breaking wherever Request.form values are fetched in the same controller.

Below is the test controller code using nunit and Moq:

      [Test]
    public void SaveRequest()
    {
        TestController test = new TestController();

        TestModel model = new TestModel();
        model = PopulateRequestModel();
        Mail = model.Mail;
        HttpContext.Current = new HttpContext(new HttpRequest("", "https://localhost", ""), new HttpResponse(new System.IO.StringWriter()));
        System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, new HttpSessionStateContainer("", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true, HttpCookieMode.UseCookies, SessionStateMode.InProc, false));

        System.Web.HttpContext.Current.Session["__RequestVerificationTokenError"] = false;

        var httpContext1 = (new Mock<HttpContextBase>());
        var routeData = new RouteData();
        httpContext1.Setup(c => c.Request.RequestContext.RouteData).Returns(routeData);

        httpContext1.Setup(c => c.Request.Form).Returns(delegate()
        {
            var nv = new NameValueCollection();
            nv.Add("Firstname", "Dave");
            nv.Add("LastName", "Smith");
            nv.Add("Email", "[email protected]");
            nv.Add("Comments", "Comments are here...");
            nv.Add("ReceiveUpdates", "true");
            return nv;
        });


        if (LoggedInEnterpriseId != null)
        {
            ViewResult result = test.SaveRequest(model, mail) as ViewResult;
            Assert.IsNotNull(result);
        }
    }

PopulateRequestModel :

        private RequestModel PopulateRequestModel ()
    {
        RequestModel model = new RequestModel ();

        model.Firstname = "Dave";
        model.LastName = "Smith";
        model.Email = "[email protected]";
        model.Comments = "Comments are here...";
        model.ReceiveUpdates = true;


        return model;

    }

Below is the actual controller method to be tested :

     [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult SaveRequest(TestModel model, HttpPostedFileBase Mail)
    {

        string Name = Request.Form["Firstname"].ToString();
        model.Mail = Mail;

        //Start Adding Request to DB
        Logger.Write("Start: Adding new request..");
        try
        {
            using (db = new DatabaseContext())
            {
                NewRequest newRequest = new NewRequest();

                if (RequestNumber != 0)
                {
                    newRequest.Name = Convert.ToInt16(Request.Form["Firstname"]);
                    newRequest.LastName = Request.Form["LastName"];
                    newRequest.Email = Request.Form["Email"];
                    newRequest.Comments = Request.Form["Comments"];                       
                    newRequest.ReceiveUpdates = Convert.ToBoolean(Request.Form["ReceiveUpdates"]);               
                }
                else
                {

                    newRequest.Name = model.Firstname;
                    newRequest.LastName = model.LastName;
                    newRequest.Email = model.Email;
                    newRequest.Comments = model.Comments;                       
                    newRequest.ReceiveUpdates = model.ReceiveUpdates;     

                }
                db.NewRequests.Add(newRequest);
                int save = db.SaveChanges();

    }   

The code is getting blocked wherever request.form is used.

16
  • 1
    what does "getting blocked" mean, and why are you using Request.Form at all in your controller? You've got your TestModel object which should contain the values you need (and if it doesn't, you need to change your model). By using Request.Form you're entirely missing the benefits of the Model binder in MVC, which is one of the best bits about it. Commented May 24, 2018 at 8:01
  • Getting blocked means the code coverage is being blocked. We are using the testmodel object but some of the values are fetched at runtime through request.form. So we are able to handle the "else" part but having issue in the "if" part. How do I give those request.form values through my test method. Commented May 24, 2018 at 8:17
  • 1
    The answer is still the same, don't use Request and then you don't have to try and mock it. Or better yet move all your logic into a logic layer and test that. IMO testing controllers is mostly a waste of time. Testing should test logic, logic shouldn't be in your controller. Commented May 24, 2018 at 9:52
  • 1
    Thanks all but the problem is we are not allowed to change the existing code. All we can do is create test methods but no changes are allowed to make in the controller. Hence,no other option but to find a solution for this. The error I am getting is - An exception of type 'System.TypeInitializationException' occurred in Moq.dll but was not handled in user code Additional information: The type initializer for 'Moq.DefaultValueProvider' threw an exception. which is in the line : var httpContext1 = (new Mock<HttpContextBase>()); Commented May 24, 2018 at 10:12
  • 1
    we are not allowed to change the existing code unit testing shouldn't be like this. You can't unit test in isolation to the code base. Often the code is untestable (static methods being a prime example) and/or incorrect. The point of unit testing is to make better code, just adding tests to bad code isn't going to make anything better. Tl;Dr if you have the option feedback to whoever did write this code that they've done it wrong and it's making testing very difficult Commented May 24, 2018 at 10:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.