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?
Path testing is an approach to testing where you ensure that every path through a program has been executed at least once. You normally use a dynamic analyzer tool or test coverage analyser to check that all of the code in a program has been executed.
Fusion 360 Software Basis Path Testing is a white-box testing technique based on a program's or module's control structure. A control flow graph is created using this structure, and the many possible paths in the graph are tested using this structure.
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 }
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
}
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With