Search code examples
c#xunit

How to stop XUnit Theory on the first fail?


I use Theory with MemberData like this:

[Theory]
[MemberData(nameof(TestParams))]
public void FijewoShortcutTest(MapMode mapMode)
{
  ...        

and when it works, it is all fine, but when it fails XUnit iterates over all data I pass as parameters. In my case it is fruitless attempt, I would like to stop short -- i.e. when the first set of parameters make the test to fail, stop the rest (because they will fail as well -- again, it is my case, not general rule).

So how to tell XUnit to stop Theory on the first fail?


Solution

  • The point of a Theory is to have multiple independent tests running the same code of different data. If you only actually want one test, just use a Fact and iterate over the data you want to test within the method:

    [Fact]
    public void FijewoShortcutTest()
    {
        foreach (MapMode mapMode in TestParams)
        {
            // Test code here
        }
    }
    

    That will mean you can't easily run just the test for just one MapMode though. Unless it takes a really long time to execute the tests for some reason, I'd just live with "if something is badly messed up, I get a lot of broken tests".