Search code examples
c#asp.net-mvcunit-testingmoqhttppostedfilebase

How to return mock object as a null


as the topic says I don't know how to return a mocked object as null in my MVC Testing project. I'm new on making unit tests.

I have an action:

[HttpPost]
public ActionResult Edit(ClubToAddVM  clubToAddVm, HttpPostedFileBase imageFile)
{
    if (ModelState.IsValid)
    {
        if (imageFile!=null)
        {
            clubToAddVm.ImageMimeType = imageFile.ContentType;
            clubToAddVm.ImageData = new byte[imageFile.ContentLength];
            imageFile.InputStream.Read(clubToAddVm.ImageData, 0, imageFile.ContentLength);
        }
    }
    ...
}

And I want in my test to pass the imageFile object as a null. Unfortunately I can't create instance of HttpPostedFileBase abstract class and I wanna try with something like this:

var mockImageFile = new Mock<HttpPostedFileBase>();

But then I don't know how to make it as null, because mockImageFile.Object is readonly. Any ideas?


Solution

  • You don't have to create an instance if you want to make it null, just do:

    HttpPostedFileBase imageFile = null;
    

    That it is an abstract class does indeed mean that you cannot create an instance of it, but it is perfectly fine to declare a variable of that type and set it to null.