-2

I have a WPF application used to execute logic that tests hardware (i.e. reads sensors, amps, voltages, etc.)

Each individual test runs when a "Test Device" method is called. I need to be able to exit the method when one of the tests fails so that no further tests are run.

However, using an if statement results in a bunch of ugly, hard to read and hard to debug code. It's also not re-usable at all. I have a bunch of apps that do this for different hardware devices. It would be nice to have a library so testing and development were much faster. I've been reading about tasks, delegates, actions, and state management - but I'm not quite sure what to use and how to put it all together.

Edit - here is pseudo-code for what happens when a user clicks "start":

    public void ExecuteTests()
    {
        // Code that sets / resets test object state here
        ...
    RunTestOne();
    if(TestOne.Pass)
    {
        RunTestTwo();
        if(TestTwo.Pass)
        {
            RunTestThree();
            ...
        }
    }
    foreach(Test toCheck in _tests)
    {
        if(!toCheck.PassFailBool.HasValue)
        {
            toCheck.Fail;
        }
    }
}

2 Answers2

1

You're looking for "early exit" or "return early."

Example (for demonstration purposes only; won't win any beauty contests):

int Tests()
{
   if (!TestOne())
       return 1;

if (!TestTwo()) return 2;

// as many times as you need.

return 0;

}

You can also put all of your tests as delegates into a Dictionary, run a loop over the dictionary, and break when one of your tests fails.

bool RunAllTests()
{    
    var tests = new Dictionary<string, Action<bool>()
    {
       {"Test1", () => Test1() };
       {"Test2", () => Test2() };
    }
foreach(var test in tests)
{
    if (!test.Value())
       return false;
}
return true;

}

Robert Harvey
  • 200,592
1

If your test methods return a Boolean, you can just chain them with &&, which will stop evaluating with the first one that returns false.

var pass = TestOne() && TestTwo() && TestThree() && TestFour();
John Wu
  • 26,955