• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2007 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito.internal.junit;
6 
7 import junit.framework.ComparisonFailure;
8 import org.mockito.exceptions.verification.ArgumentsAreDifferent;
9 
10 public class ExceptionFactory {
11 
12     private final static boolean hasJUnit = canLoadJunitClass();
13 
ExceptionFactory()14     private ExceptionFactory() {
15     }
16 
17     /**
18      * If JUnit is used, an AssertionError is returned that extends from JUnit {@link ComparisonFailure} and hence provide a better IDE support as the comparison result is comparable
19      */
createArgumentsAreDifferentException(String message, String wanted, String actual)20     public static AssertionError createArgumentsAreDifferentException(String message, String wanted, String actual) {
21         if (hasJUnit) {
22             return createJUnitArgumentsAreDifferent(message, wanted, actual);
23         }
24         return new ArgumentsAreDifferent(message);
25     }
26 
createJUnitArgumentsAreDifferent(String message, String wanted, String actual)27     private static AssertionError createJUnitArgumentsAreDifferent(String message, String wanted, String actual) {
28         return JUnitArgsAreDifferent.create(message, wanted, actual);
29     }
30 
canLoadJunitClass()31     private static boolean canLoadJunitClass() {
32         try {
33             JUnitArgsAreDifferent.create("message", "wanted", "actual");
34         } catch (NoClassDefFoundError onlyIfJUnitIsNotAvailable) {
35             return false;
36         }
37         return true;
38     }
39 
40     /**
41      * Don't inline this class! It allows create the JUnit-ArgumentsAreDifferent exception without the need to use reflection.
42      * <p>
43      * If JUnit is not available a call to {@link #create(String, String, String)} will throw a {@link NoClassDefFoundError}.
44      * The {@link NoClassDefFoundError} will be thrown by the class loader cause the JUnit class {@link ComparisonFailure}
45      * can't be loaded which is a upper class of ArgumentsAreDifferent.
46      */
47     private static class JUnitArgsAreDifferent {
create(String message, String wanted, String actual)48         static AssertionError create(String message, String wanted, String actual) {
49             return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual);
50         }
51     }
52 }
53