continue on assert

10,227

Solution 1

No, you can't - Assert will throw an exception if it fails, and you can't just keep going after the exception. You could catch the exceptions, and then add them into a collection... but it's not terribly nice.

If you're trying to basically test several different cases, most modern unit test frameworks have ways of parameterizing tests so that each case ends up as a separate test, with separately-reported pass/failure criteria. We don't know which framework you're using or what the different cases are here, but if you could give more context, we could try to help more...

Solution 2

Assert.AreEqual throws assertion exception. So, you can't simply move to next assertion. You should catch them, but that's not how assertions supposed to be used. Failed assertion should stop test execution.

So, you should have single assertion which will return all required data for you. If you want verify that all items are equal to some value, then you should write it in test. If test fails you can dump all collection to error message or just items which are not expected (I used Json.NET for that):

Assert.IsTrue(data.All(ex => ex == ex1), 
              JsonConvert.SerializeObject(data.Where(ex => ex != ex1)));

In case of fail this assertion will serialize all items to JSON and show them in test runner message. E.g. if you have collection of integers:

var data = new List<int> { 1, 1, 5, 1, 2 };
int expected = 1;
Assert.IsTrue(data.All(i => i == expected), "Unexpected items: " +
              JsonConvert.SerializeObject(data.Where(i => i != expected)));  

Test will fail with message:

Assert.IsTrue failed. Unexpected items: [5,2]

Solution 3

You could catch the exception, add it to a list, then continue. At the end, you could assert that the list is empty.

Solution 4

That article explains how to 'Verify' your value. Adding verify to MsTest

Share:
10,227
Mayo
Author by

Mayo

Updated on June 04, 2022

Comments

  • Mayo
    Mayo almost 2 years

    Is there any way to continue test after Assert? .. I need to see all cases which the assert causes.

    foreach (var ex in data)
    {
         Assert.AreEqual(ex1, ex, msg);
    }
    
  • Adarsh Shah
    Adarsh Shah over 10 years
    But its not a good practice to do this. You should either create a separate test for each scenario you are testing or use parameterized tests.
  • DevSolar
    DevSolar over 2 years
    That link is dead. This is eactly why link only answers are frowned upon -- now the reader is left with the information that you had a solution, but it's lost now.