Home > Back-end >  Cannot save file when unit testing a file upload
Cannot save file when unit testing a file upload

Time:05-31

I try to Unit test a mvc controller that receive a model that has a HttpPostedFile as parameter

    var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
    var obj = (HttpPostedFile)constructorInfo
        .Invoke(new object[] { @"D:\test.xlsx", "application/vnd.ms-excel", null });

    model.MembershipRegisterFile = new HttpPostedFileWrapper(obj);

When I run the test and the controller tries to save the file to disk I get an exception on this line..

file.SaveAs(completepath);

With error...

System.NullReferenceException: 'Object reference not set to an instance of an object.'

I assume this is beacuse the file isnt really uploaded and the content length of the file is null. So how should I approach this. Should I inside my controller have logic for the possibility of contentlength equals to null or can the HttpPostedFile set the content length?

UPDATE: I mocked the file like this and this worked....

var postedfile = new Mock<HttpPostedFileBase>();
postedfile.Setup(f => f.ContentLength).Returns(8192);
postedfile.Setup(f => f.FileName).Returns("myfile.txt");
postedfile.Setup(f => f.InputStream).Returns(new MemoryStream(8192));
myObject.HttpPostedFile = postedfile.Object;

CodePudding user response:

Unit Testing File I/O you can analyze the link. I think you should not put a file in your project. You should create a mock file. To create mock file Use System.IO.Abstractions

  • Related