| jeffhao | 5d1ac92 | 2011-09-29 17:41:15 -0700 | [diff] [blame] | 1 | package junit.framework; |
| 2 | |
| 3 | /** |
| 4 | * Thrown when an assert equals for Strings failed. |
| 5 | * |
| 6 | * Inspired by a patch from Alex Chaffee mailto:alex@purpletech.com |
| 7 | */ |
| 8 | public class ComparisonFailure extends AssertionFailedError { |
| 9 | private String fExpected; |
| 10 | private String fActual; |
| 11 | |
| 12 | /** |
| 13 | * Constructs a comparison failure. |
| 14 | * @param message the identifying message or null |
| 15 | * @param expected the expected string value |
| 16 | * @param actual the actual string value |
| 17 | */ |
| 18 | public ComparisonFailure (String message, String expected, String actual) { |
| 19 | super (message); |
| 20 | fExpected= expected; |
| 21 | fActual= actual; |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Returns "..." in place of common prefix and "..." in |
| 26 | * place of common suffix between expected and actual. |
| 27 | * |
| 28 | * @see java.lang.Throwable#getMessage() |
| 29 | */ |
| 30 | public String getMessage() { |
| 31 | if (fExpected == null || fActual == null) |
| 32 | return Assert.format(super.getMessage(), fExpected, fActual); |
| 33 | |
| 34 | int end= Math.min(fExpected.length(), fActual.length()); |
| 35 | |
| 36 | int i= 0; |
| Elliott Hughes | b25c3f6 | 2012-03-26 16:35:06 -0700 | [diff] [blame^] | 37 | for (; i < end; i++) { |
| jeffhao | 5d1ac92 | 2011-09-29 17:41:15 -0700 | [diff] [blame] | 38 | if (fExpected.charAt(i) != fActual.charAt(i)) |
| 39 | break; |
| 40 | } |
| 41 | int j= fExpected.length()-1; |
| 42 | int k= fActual.length()-1; |
| 43 | for (; k >= i && j >= i; k--,j--) { |
| 44 | if (fExpected.charAt(j) != fActual.charAt(k)) |
| 45 | break; |
| 46 | } |
| 47 | String actual, expected; |
| 48 | |
| 49 | // equal strings |
| 50 | if (j < i && k < i) { |
| 51 | expected= fExpected; |
| 52 | actual= fActual; |
| 53 | } else { |
| 54 | expected= fExpected.substring(i, j+1); |
| 55 | actual= fActual.substring(i, k+1); |
| 56 | if (i <= end && i > 0) { |
| 57 | expected= "..."+expected; |
| 58 | actual= "..."+actual; |
| 59 | } |
| 60 | |
| 61 | if (j < fExpected.length()-1) |
| 62 | expected= expected+"..."; |
| 63 | if (k < fActual.length()-1) |
| 64 | actual= actual+"..."; |
| 65 | } |
| 66 | return Assert.format(super.getMessage(), expected, actual); |
| 67 | } |
| 68 | } |