I am currently trying to mock a media request and the media item I am requesting using FakeDb but for some reason my request is returning an empty MediaPath rather than the MediaPath I am expecting.

Here is the method:

public class RequestMediaEXT
    public bool getImage(HttpContext context)
        MediaRequest request = MediaManager.ParseMediaRequest(context.Request);
        string mediaPath = request?.MediaUri.MediaPath;
        if (mediaPath == null | MediaPath == string.empty)
            return false;

        return true;

Unit test for the method:

[CustomAutoData("http://image.here/", "~/media/myimage.ashx")]
public void getImage_imageFound_ReturnsTrue(string url, string media)

    string myImageUrl = url + media;
    Sitecore.Data.ID mediaItemId = Sitecore.Data.ID.NewID;

    HttpRequest httpRequest = new HttpRequest(string.Empty, myImageUrl, string.Empty);
    HttpResponse httpResponse = new HttpResponse(new StringWriter());
    HttpContext httpContext = new HttpContext(httpRequest, httpResponse);
    var processor = new RequestMediaEXT()

    // create some media item. Location, fields and template are not important
    using (Db db = new Db())
        var mediaFakeItem = new DbItem("myimage")
            ParentID = Sitecore.ItemIDs.MediaLibraryRoot
        mediaFakeItem.FullPath = myImageUrl;

        // create media provider mock and configure behaviour
        MediaProvider mediaProvider =

            .GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaItemId))

        // substitute the original provider with the mocked one
        using (new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider))


How do I mock the HttpContext such that the MediaPath doesn't become an empty string but the actual MediaPath?

I am using Sitecore 8.1 and therefore have to use the now obsolete MediaProviderSwitcher.


What you are doing here is not Unit Testing, I would consider it more of an integration test, I am a broken record on this subject but it is my opinion that you should reserve unit testing for testing functionality you own and take advantage of focused and mockable interfaces, see Interface segregation principle.

Mocking the HttpContext almost always ends in tears byways of a test maintenance nightmare, however, there is some relief to this from ASP.NET 3.5 and up; look at using HttpContextBase and HttpContextWrapper.

public bool getImage(HttpContextBase context)

HttpContextBase is abstract and you will have an easier time mocking it. When you need to adapt the HttpContext you can with the HttpContextWrapper class.

var abstractContext = new HttpContextWrapper(context);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.