Jeiesel
Jeiesel

Reputation: 309

How to identify when my code is testing in C#?

I am having troubles when testing a controller, because there are some lines at my Startup that are null when testing, I want to add a condition for run this lines only if it's not testing.

// Desired method that retrieves if testing
if (!this.isTesting())
{
  SwaggerConfig.ConfigureServices(services, this.AuthConfiguration, this.ApiMetadata.Version);
}

Upvotes: 0

Views: 305

Answers (2)

eocron
eocron

Reputation: 7536

It really depends on which framework you use for testing. It can be MSTest, NUnit or whatever.

Rule of thumb, is that your application should not know whether it is tested. It means everything should be configured before actual testing through injection of interfaces. Simple example of how tests should be done:

//this service in need of tests. You must test it's methods.
public class ProductionService: IProductionService
{
    private readonly IImSomeDependency _dep;
    public ImTested(IImSomeDependency dep){ _dep = dep; }
    public void PrintStr(string str)
    {
        Console.WriteLine(_dep.Format(str));
    }
}

//this is stub dependency. It contains anything you need for particular test. Be it some data, some request, or just return NULL.
public class TestDependency : IImSomeDependency
{
    public string Format(string str)
    {
        return "TEST:"+str;
    }
}

//this is production, here you send SMS, Nuclear missle and everything else which cost you money and resources.
public class ProductionDependency : IImSomeDependency
{    
    public string Format(string str)
    {
        return "PROD:"+str;
    }
}

When you run tests you configure system like so:

var service = new ProductionService(new TestDependency());
service.PrintStr("Hello world!");

When you run your production code you configure it like so:

var service = new ProductionService(new ProductionDependency());
service.PrintStr("Hello world!");

This way ProductionService is just doing his work, not knowing about what is inside it's dependencies and don't need "is it testing case №431" flag. Please, do not use test environment flags inside code if possible.

UPDATE:

See @Mario_The_Spoon explanation for better understanding of dependency management.

Upvotes: 3

Mario The Spoon
Mario The Spoon

Reputation: 4859

The correct answer (although of no help): It should not be able to tell so. The application should to everything it does unaware if it is in productino or test.

However to test the application in a simpler setting, you can use fake modules or mock-up modules that are loaded instead of the heavy-weight production modules.

But in order to use that, you have to refactor your solution and use injection for instance.

Some links I found:

Designing with interfaces

Mock Objects

Some more on Mock objects

Upvotes: 3

Related Questions