Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fake HttpContext for unit tests?

I need to fake HttpContext.Current.Application table in order to access it from my unit tests.

I need to store my data somewhere. I thought that I can just pass instance of NameValueCollectionBase but as I discovered this base type has no indexer so it seems too complicated to use.

So what about faking this part of HttpContext? Is it possible? How can I make it? Will be NUnit.Mocks helpful?

Thank you in advance...

like image 572
Łukasz W. Avatar asked Aug 15 '10 16:08

Łukasz W.


People also ask

Can we mock HttpContext?

HttpContextMock is an implementation of AspNetCore. Http. HttpContext that stores a Mock<HttpContext> instance and works as a proxy for the real Mock. The HttpContextMock constructor initializes a Mock for Request, Response, Header and etc to work as a proxy as well.

How do you mock in unit testing?

Advanced: Mocking in Unit TestMocking is used in unit tests to replace the return value of a class method or function. This may seem counterintuitive since unit tests are supposed to test the class method or function, but we are replacing all those processing and setting a predefined output.

What is IHttpContextAccessor?

It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any. ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it.

Do you unit test properties?

Generally, no. A unit test should be used to test for the functionality of a unit. You should unit test methods on a class, not individual, automatic properties (unless you are overriding the getter or setter with custom behaviour).


1 Answers

Please go through below links it will help you.

http://www.java2s.com/Open-Source/CSharp/Web-Frameworks/MvcContrib/MvcContrib/TestHelper/Fakes/FakeHttpContext.cs.htm

Mocking and HttpContextBase.get_User()

Thanks Venkat

like image 114
Venkat Avatar answered Oct 12 '22 13:10

Venkat