• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.testng.asserts;
2 
3 import java.util.Map;
4 
5 import org.testng.collections.Maps;
6 
7 /**
8  * When an assertion fails, don't throw an exception but record the failure.
9  * Calling {@code assertAll()} will cause an exception to be thrown if at
10  * least one assertion failed.
11  */
12 public class SoftAssert extends Assertion {
13   // LinkedHashMap to preserve the order
14   private final Map<AssertionError, IAssert<?>> m_errors = Maps.newLinkedHashMap();
15 
16   @Override
doAssert(IAssert<?> a)17   protected void doAssert(IAssert<?> a) {
18     onBeforeAssert(a);
19     try {
20       a.doAssert();
21       onAssertSuccess(a);
22     } catch (AssertionError ex) {
23       onAssertFailure(a, ex);
24       m_errors.put(ex, a);
25     } finally {
26       onAfterAssert(a);
27     }
28   }
29 
assertAll()30   public void assertAll() {
31     if (!m_errors.isEmpty()) {
32       StringBuilder sb = new StringBuilder("The following asserts failed:");
33       boolean first = true;
34       for (Map.Entry<AssertionError, IAssert<?>> ae : m_errors.entrySet()) {
35         if (first) {
36           first = false;
37         } else {
38           sb.append(",");
39         }
40         sb.append("\n\t");
41         sb.append(ae.getKey().getMessage());
42       }
43       throw new AssertionError(sb.toString());
44     }
45   }
46 }
47