Skip to content

Consider adding new DefaultHttpContext() to Mock<DefaultHttpContext> alternatives #17321

@antmdvs

Description

@antmdvs

https://docs.microsoft.com/en-us/dotnet/core/compatibility/2.2-3.0#http-defaulthttpcontext-extensibility-removed

If your unit tests use Mock<DefaultHttpContext>, use Mock<HttpContext> instead.

After some research, it seems new DefaultHttpContext() is a valid way way to mock HttpContext in unit tests. Should this be added to the above-quoted line? Otherwise, it could be questioned whether newing a DefaultHttpContext() is a Microsoft-accepted practice or Mock<HttpContext> is the only recommended approach.

Supporting comments:

@JamesNK (dotnet/aspnetcore#6504 (comment)):

The difference is HttpContext requires you to mock out all the behavior that you need, while DefaultHttpContext lets you take the defaults and override only what you care about.

@davidfowl (dotnet/aspnetcore#6504 (comment)):

Most of the tests I see, new up the DefaultHttpContext (it was actually intentional to make it POCO like and newable).

@anurse (https://stackoverflow.com/questions/45959605/inspect-defaulthttpcontext-body-in-unit-test-situation#comment78887946_45960766)


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions