Hard to Test Code

Whenever I want to implement a specific code path that would otherwise be achieved only if the condition complexly reproduced, for example:

 if (condition) { code to be tested } 

I or with true :

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

Is there a more elegant approach?

+7
source share
5 answers

I think more elegant way uses the logical negation operator (!) Like:

 if (!condition) { code to be tested } 

But a safer way to debug or test you can use the preprocessor directive (as in my comet). When you are done testing, just delete or modify the #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 } 
+13
source

A more elegant solution uses 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 the system under test:

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

Your approach, with "true or," and the if (! Condition) approach are the simplest. This is the approach that I like for large programs

Create a function, let it call testme (const string). And instead of embedding true in if test, you embed testme with some string that identifies this piece of code.

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

Then, using some kind of configuration file or your program arguments (I prefer config), you can fully control when testme ("Location 123") returns true. And you can use the same function in many places. Just change the configuration file to check each.

+3
source

I assume this is not a unit test script as it was not mentioned in the question. Of course, the easiest way to test such code on the fly is to use the Set aside Defer Debugger command.

Set a breakpoint in the if () statement, if necessary, or place the code until it reaches this statement. Then right-click the next line inside the body of the if () statement and select Set Next Expression. The code will resume execution of this line, completely skipping if ().

+2
source

Put the code to be tested by a separate method. Then you can call the method and bypass the conditional. Now you don’t have to worry about adding β€œtruth” or, more importantly, forget to remove it.

You can also add unit tests for the method so that you can change the parameters passed to it and test all the scripts you want.

+2
source

All Articles