1

I have a Controller for creating template. This controller accept template model as Parameter.The controller contains the code for file upload. I don't understand how to unit test this code...

This is my model:

public class Template
{
   public string TemplateName {get; set;}
   public string Description {get; set;}
   public string FileName {get; set;}
} 

This is my controller

public ActionResult Create(Template template)
{
   if (ModelState.IsValid)
            {
                var file = Request.Files["FileName"];
                template.FileName = template.TemplateName;

                long TemplateId = _templateService.Create(template);
                string path = Server.MapPath("~/Templates/Archieve/" + TemplateId);
                Directory.CreateDirectory(path);
                string archievePath = Server.MapPath("~/Templates/Archieve/" + TemplateId + "/" + "Template" + TemplateId + ".zip");

                file.SaveAs(archievePath);
                using (ZipFile zip = ZipFile.Read(archievePath))
                {
                    zip.ExtractAll(Server.MapPath("~/Templates/" + TemplateId), ExtractExistingFileAction.DoNotOverwrite);

                }

                return RedirectToAction("Index");
}

This is my unit test:

public void Create_Template()
{
     //Arrange
     var template = new Template()
                {
                    Description = "Description",
                    FileName = null,
                    TemplateName = "name"
                };

                //Act
                var result = controller.Create(template) as RedirectToRouteResult;

                //Assert
                Assert.AreEqual("index", result.RouteValues["action"]);
}

How to unit test Request.Files[FileName] and Server.MapPath

tereško
  • 56,151
  • 24
  • 92
  • 147
Ruchi
  • 145
  • 1
  • 2
  • 12
  • If there is problem in Request.Files["FileName"], your code will through exception, and your Assert will be fail. – Ishtiaq Nov 13 '14 at 14:10
  • Yes, There is Exception while running test. When I debug the test, as it reaches the code Request.Files["FileName"]", it throws Exception-"Object reference not set to an instance of object". And this is my problem, how to solve this exception @Ish – Ruchi Nov 14 '14 at 04:46

1 Answers1

0

You have to use Mock object for HttpContext.
Go through the LINK for further details.

Community
  • 1
  • 1
Ishtiaq
  • 890
  • 2
  • 6
  • 21