简体   繁体   中英

How to “unhost” from HostingEnvironment

I am currently writing Unit tests fo ASP Net MVC application, and one of the things I have to mock is an HTTP Request. For this I use HttpSimulator library (Subtext.TestLibrary).

I call SimulateRequest() method, and one of things it does is it creates a HostingEnvironment object.

_httpSimulator = new HttpSimulator().SimulateRequest(new Uri());

Before simulating HTTP request, I have to use the value of HostingEnvironment.IsHosted property in my code (in condition statement).

All works fine for the first test, because I get the proper value for HostingEnvironment.IsHosted (which is FALSE).

However, when the SimulateRequest() creates a HostingEnvironment object, HostingEnvironment.IsHosted becomes TRUE, so when the second test runs I receive a TRUE value, which leads to wrong results (or exception).

HostingEnvironment environment = new HostingEnvironment();

Therefore I am trying to find a way to reset HostingEnvironment.IsHosted back to FALSE. This property, however, is read-only.

I also cannot see any method, which would reset this property (I expect either Terminate, Finalize or whatever else it could be).

It sounds like your tests are too tightly coupled with multiple tests using the same instance of HostingEnvironment().

Each test should typically be executed independently of one another so that the results of eg Test 1 do not have any effect on the results of eg Test 2.

Just use separate instances of HostingEnvironment() :

 [Test]
 public void InitializeContext()
 {
     using (HttpSimulator simulator = new HttpSimulator())
     {
        //Test #1...
     }
 }

[Test]
public void Simulator_Assigns_CurrentContext()
{
    using (HttpSimulator simulator = new HttpSimulator())
    {
        //Test #2...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM