Clodoaldo Neto
Clodoaldo Neto

Reputation: 125454

Testing a difficult to reach code path

Whenever I want to exercise a certain path of code that would otherwise only be reached under a difficult to reproduce condition like:

if (condition) { code to be tested }

I or it with a true value:

if (true || condition) { code to be tested }

Is there a more elegant approach?

Upvotes: 7

Views: 994

Answers (5)

Kaf
Kaf

Reputation: 33839

I think more elegant way is using the logical negation operator (!) as;

if (!condition) { code to be tested }

But more safe way for debugging or testing purposes you can use a preprocessor directive (as per my commet). When you finish testing simply remove or change #define UnreachableTest

#define UnreachableTest //should be on the top of the class/page

#if (UnreachableTest) 
    condition = !condition; //or
    condition = true;
#endif

if (condition) { code to be tested }

Upvotes: 13

mosca125
mosca125

Reputation: 131

Put the code to be tested in a separate method. Then you can call the method and bypass the conditional. Now you won't have to worry about adding "true" or more importantly forgetting to remove it.

You can also add unit tests for the method so that you can modify the parameters passed into it and test all the scenarios you want.

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

More elegant solution is using mocks. Make decisions based on dependencies or parameters:

var mock = new Mock<IFoo>();
mock.Setup(foo => foo.IsBar).Returns(true);
var sut = new Sut(mock.Object);
sut.DoSomething();

And in your system under test:

public void DoSomething()
{
    if (_foo.IsBar)
        // code path to test
}

Upvotes: 13

Daniel Goldfarb
Daniel Goldfarb

Reputation: 7724

Your approach, with "true or", and the approach of if (!condition) are the simplest. Here is an approach that I like for large programs

Create a function, let's call it testme(const string). And instead of inserting true in if test, you insert testme, with some string that identifies that piece of code.

    if ( testme("Location 123") || condition ) { code to be tested }

Then, using some kind of config file, or arguments to your program (i prefer config), you can totally control when testme("Location 123") will return true. AND you can use the same function in many locations. Just change the config file to test each one.

Upvotes: 3

Hans Passant
Hans Passant

Reputation: 942197

I'll assume this is not a unit test scenario since it wasn't mentioned in the question. By far the simplest way to do on-the-fly testing of code like this is by using the debugger's Set Next Statement command.

Set a breakpoint on the if() statement, if necessary, or step the code until it reaches that statement. Then right-click the next line, inside the if() statement body, and select "Set Next Statement". Code will resume executing at that line, completely skipping the if().

Upvotes: 2

Related Questions