1

We are doing an upgrade from 8.2 to 10.2, and the code has a lot of unit tests. One element in a number of them involves the HttpRequestBegin pipeline, where there's an article about the code to use for Sitecore 9 here: https://www.andybutland.dev/2017/11/unit-testing-httprequestargs-with-sitecore-9.html. The relevant code that the blogger said worked was this:

public static HttpRequestArgs CreateHttpRequestArgs(string url)
{
    var httpRequest = new HttpRequest(string.Empty, url, string.Empty);
    var httpResponse = new HttpResponse(new StringWriter());
    var httpContext = new HttpContext(httpRequest, httpResponse);
 
    var requestArgs = new HttpRequestArgs(new HttpContextWrapper(httpContext), HttpRequestType.End);
     
    // Reflection used to set the protected Url property
    var property = requestArgs.GetType().GetProperty("Url", BindingFlags.Public | BindingFlags.Instance);
    property?.SetValue(requestArgs, new RequestUrl(httpRequest));
 
    return requestArgs;
}

We tried this out, but the second to last line property?.SetValue(requestArgs, new RequestUrl(httpRequest)); gives an error that it can't convert HttpRequest to HttpRequestBase. We tried casts but it wouldn't go for that.

Has anyone had to do a unit test in Sitecore 10 in a similar fashion that has a code sample that works, or can point in the right direction?

1 Answer 1

1

Starting from Sitecore 9 you can get rid of all those customizations at all. The article describes a hack how to set httpRequest via reflection. The new HttpRequestBase class is the long-awaited absraction that makes all those hacks unnecessary. You can just mock it. See how HttpRequestArgs can be created in new Sitecore:

[Fact]
public void CreateHttpRequestArgs1()
{
    var args = new HttpRequestArgs(Substitute.For<HttpContextBase>());
    Assert.NotNull(args.HttpContext);
}

In combination with AutoFixture it can be even more elegant:

[Theory, AutoNSubstituteData]
public void CreateHttpRequestArgs(HttpRequestArgs args)
{
    Assert.NotNull(args.HttpContext);
}

UPDATE

Just in case you still want the code above to work, did you try to use RequestWrapper?

...
property?.SetValue(requestArgs, new RequestUrl(new HttpRequestWrapper(httpRequest)));

Your Answer

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

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