001package junit.framework;
002
003import java.util.ArrayList;
004import java.util.Arrays;
005import java.util.HashMap;
006import java.util.List;
007
008import org.junit.runner.Description;
009import org.junit.runner.notification.Failure;
010import org.junit.runner.notification.RunListener;
011import org.junit.runner.notification.RunNotifier;
012
013public class JUnit4TestAdapterCache extends HashMap<Description, Test> {
014    private static final long serialVersionUID = 1L;
015    private static final JUnit4TestAdapterCache fInstance = new JUnit4TestAdapterCache();
016
017    public static JUnit4TestAdapterCache getDefault() {
018        return fInstance;
019    }
020
021    public Test asTest(Description description) {
022        if (description.isSuite()) {
023            return createTest(description);
024        } else {
025            if (!containsKey(description)) {
026                put(description, createTest(description));
027            }
028            return get(description);
029        }
030    }
031
032    Test createTest(Description description) {
033        if (description.isTest()) {
034            return new JUnit4TestCaseFacade(description);
035        } else {
036            TestSuite suite = new TestSuite(description.getDisplayName());
037            for (Description child : description.getChildren()) {
038                suite.addTest(asTest(child));
039            }
040            return suite;
041        }
042    }
043
044    public RunNotifier getNotifier(final TestResult result, final JUnit4TestAdapter adapter) {
045        RunNotifier notifier = new RunNotifier();
046        notifier.addListener(new RunListener() {
047            @Override
048            public void testFailure(Failure failure) throws Exception {
049                result.addError(asTest(failure.getDescription()), failure.getException());
050            }
051
052            @Override
053            public void testFinished(Description description) throws Exception {
054                result.endTest(asTest(description));
055            }
056
057            @Override
058            public void testStarted(Description description) throws Exception {
059                result.startTest(asTest(description));
060            }
061        });
062        return notifier;
063    }
064
065    public List<Test> asTestList(Description description) {
066        if (description.isTest()) {
067            return Arrays.asList(asTest(description));
068        } else {
069            List<Test> returnThis = new ArrayList<Test>();
070            for (Description child : description.getChildren()) {
071                returnThis.add(asTest(child));
072            }
073            return returnThis;
074        }
075    }
076
077}