Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

continue on assert

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);
}
like image 548
Mayo Avatar asked Jan 01 '14 20:01

Mayo


People also ask

How do you continue test if assert fails?

They don't throw an exception when an assert fails. The execution will continue with the next step after the assert statement. If you need/want to throw an exception (if such occurs) then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.

How do you continue execution when Assertion failed in Junit?

You can do this using an ErrorCollector rule. To use it, first add the rule as a field in your test class: public class MyTest { @Rule public ErrorCollector collector = new ErrorCollector(); //... tests... }


2 Answers

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...

like image 50
Jon Skeet Avatar answered Sep 18 '22 23:09

Jon Skeet


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]

like image 29
Sergey Berezovskiy Avatar answered Sep 19 '22 23:09

Sergey Berezovskiy