sonstiq
sonstiq

Reputation: 73

Check if application running or test running

I want to port the code below to core. But is there anyway to check code is running (ex: on kestrel) or running on test (ex : on NUnit)

        if (HostingEnvironment.IsHosted)
        {
            //hosted
            return HostingEnvironment.MapPath(path);
        }

        //not hosted. For example, run in unit tests
        var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
        return Path.Combine(baseDirectory, path);

I tried to do this _hostingEnvirontment is IHostingEnvironment

        if (I MUST CHECK IS HOSTED OR NOT)
        {
            //hosted
            return _hostingEnvironment.ContentRootPath + path;
        }

        //not hosted. For example, run in unit tests
        var baseDirectory = AppContext.BaseDirectory;
        path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
        return Path.Combine(baseDirectory, path);

Upvotes: 1

Views: 1191

Answers (1)

Charlie
Charlie

Reputation: 13736

Rather than have the code you are testing "know" whether it is running live or under a test framework, it's better to inject those things that need to be changed in the test environment. This makes your application generally more testable and avoids a lot of the risks inherent in having the sut know about the test framework.

Consider creating a TestHostingEnvironment that implements IHostingEnvironment and providing it to the SUT when running tests.

Upvotes: 1

Related Questions