Java 类junit.framework.TestResult 实例源码

项目:incubator-netbeans    文件:NbModuleLogHandler.java   
public static void checkFailures(TestCase test, TestResult res, String workDirPath) {
    StringBuffer t = text;
    if (t == null) {
        return;
    }
    synchronized (t) {
        if (t.length() > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("NbModuleSuite has been started with failOnMessage(");
            sb.append(msg);
            sb.append(") and failOnException(").append(exc);
            sb.append("). The following failures have been captured:\n");
            sb.append(normalize(text, workDirPath));
            res.addFailure(test, new AssertionFailedError(sb.toString()));
            t.setLength(0);
        }
    }
}
项目:incubator-netbeans    文件:NbTestCase.java   
/**
 * Runs the test case, while conditionally skip some according to result of
 * {@link #canRun} method.
 */
@Override
public void run(final TestResult result) {
    if (canRun()) {
        System.setProperty("netbeans.full.hack", "true"); // NOI18N
        System.setProperty("java.util.prefs.PreferencesFactory",
                MemoryPreferencesFactory.class.getName());//NOI18N
        try {
            Preferences.userRoot().sync();
        } catch(BackingStoreException bex) {}
        Level lev = logLevel();
        if (lev != null) {
            Log.configure(lev, logRoot(), NbTestCase.this);
        }
        super.run(result);
    }
}
项目:incubator-netbeans    文件:FlowControlTest.java   
public void testRuntimeExceptionsAlsoGenerateLog() throws Exception {
    if (throwIt != null) {
        Logger.getLogger("").info("Ahoj");
        throw throwIt;
    }

    FlowControlTest l = new FlowControlTest("testRuntimeExceptionsAlsoGenerateLog");
    l.throwIt = new NullPointerException();
    TestResult res = l.run();
    assertEquals("No failures", 0, res.failureCount());
    assertEquals("One error", 1, res.errorCount());

    Object o = res.errors().nextElement();
    TestFailure f = (TestFailure)o;

    if (f.exceptionMessage() == null || f.exceptionMessage().indexOf("Ahoj") == -1) {
        fail("Logged messages shall be in exception message: " + f.exceptionMessage());
    }
}
项目:incubator-netbeans    文件:NbModuleSuiteStampTest.java   
public void testTestReuseUsedir(){
    NbTestSuite instance = new NbTestSuite();
    instance.addTest(
        NbModuleSuite.emptyConfiguration().gui(false)
        .addTest(NbModuleSuiteTimestamps.class)
        .enableClasspathModules(false)
    .suite());
    instance.addTest(
        NbModuleSuite.emptyConfiguration().gui(false)
        .addTest(NbModuleSuiteTimestamps.class)
        .reuseUserDir(true)
        .enableClasspathModules(false)
    .suite());
    TestResult res = junit.textui.TestRunner.run(instance);
    assertEquals("Two tests started", 2, res.runCount());
    assertEquals("No failures", 0, res.failureCount());
    assertEquals("No errors", 0, res.errorCount());

    String value = System.getProperty("stamps");
    assertNotNull("Property provided", value);
}
项目:incubator-netbeans    文件:NbTestCaseTest.java   
public void testJustRunTestCase() {
    class Fail extends NbTestCase {
        public Fail() {
            super("testFail");
        }

        public void testFail() {
            throw new IllegalStateException();
        }
    }

    Fail f = new Fail();

    TestResult res = new TestResult();
    f.run(res);

    assertEquals("One error", 1, res.errorCount());


}
项目:incubator-netbeans    文件:TimeOutHasToPrintLogTest.java   
public void testThatTheTimeOutStillPrintsTheWarning() throws Exception {
    TimeOutHasToPrintLogTest t = new TimeOutHasToPrintLogTest("printAhojAndTimeOut");

    CharSequence seq = Log.enable(LOG.getName(), Level.FINE);

    TestResult res = t.run();

    assertEquals("One test has been run", 1, res.runCount());

    String s = seq.toString();

    if (s.indexOf("Ahoj") == -1) {
        fail("Ahoj has to be logged:\n" + s);
    }

    assertEquals("No error", 0, res.errorCount());
    assertEquals("One failure", 1, res.failureCount());

    TestFailure f = (TestFailure)res.failures().nextElement();
    s = f.exceptionMessage();
    if (s.indexOf("Ahoj") == -1) {
        fail("Ahoj has to be part of the message:\n" + s);
    }
}
项目:incubator-netbeans    文件:TimeOutHasToPrintLogTest.java   
public void testThreadDumpPrinted() throws Exception {
    TimeOutHasToPrintLogTest t = new TimeOutHasToPrintLogTest("justTimeOutInOneOfMyMethods");

    TestResult res = t.run();

    assertEquals("One test has been run", 1, res.runCount());
    TestFailure failure = (TestFailure)res.failures().nextElement();
    String s = failure.exceptionMessage();

    if (s.indexOf("justTimeOutInOneOfMyMethods") == -1) {
        fail("There should be thread dump reported in case of timeout:\n" + s);
    }

    assertEquals("No error", 0, res.errorCount());
    assertEquals("One failure", 1, res.failureCount());
}
项目:incubator-netbeans    文件:LogAndTimeOutTest.java   
public void testLoggingAndTimeOut() throws Exception {
    TestResult result = new TestResult();

    T t = new T("testLoadFromSubdirTheSFS");
    t.run(result);

    assertEquals("No error", 0, result.errorCount());
    assertEquals("One failure", 1, result.failureCount());

    Object o = result.failures().nextElement();

    String output = o.toString();
    if (output.indexOf("LogAndTimeOutTest$T") == -1) {
        fail("There should be a stacktrace:\n" + output);
    }
    if (output.indexOf("Adding 5") == -1) {
        fail("There should be a 'Adding 5' message:\n" + output);
    }
}
项目:incubator-netbeans    文件:LoggingTest.java   
public void testMyExceptionIsWrappedWithLogMsg() throws Exception {
    LoggingTest inner = new LoggingTest("throwMyThrowable");

    class MyEx extends Exception {
    }

    inner.toThrow = new MyEx();

    TestResult res = inner.run();
    assertEquals("One error", 1, res.errorCount());
    assertEquals("No failure", 0, res.failureCount());

    TestFailure f = (TestFailure)res.errors().nextElement();

    if (f.exceptionMessage() == null || f.exceptionMessage().indexOf("Going to throw") == -1) {
        fail("There should be output of the log:\n" + f.exceptionMessage());
    }
}
项目:incubator-netbeans    文件:LoggingTest.java   
public void testMyExceptionWithStackTrace() throws Exception {
    LoggingTest inner = new LoggingTest("throwMyThrowable");

    class MyEx extends Exception {
    }

    inner.toThrow = new MyEx();
    inner.toMsg = new MyEx();

    TestResult res = inner.run();
    assertEquals("One error", 1, res.errorCount());
    assertEquals("No failure", 0, res.failureCount());

    TestFailure f = (TestFailure)res.errors().nextElement();

    if (
        f.exceptionMessage() == null || 
        f.exceptionMessage().indexOf("Going to throw") == -1 ||
        f.exceptionMessage().indexOf("testMyExceptionWithStackTrace") == -1
   ) {
        fail("There should be output of the log:\n" + f.exceptionMessage());
    }
}
项目:incubator-netbeans    文件:NbModuleSuiteClusterPathFinalTest.java   
public void testClusterPathFinal() throws Exception {
    if (!NbModuleSuiteTest.isCluster("ide")) {
        // skip
        return;
    }
    LinkedList<File> clusters = new LinkedList<File>();
    NbModuleSuite.S.findClusters(clusters, Collections.singletonList("ide"));
    assertFalse("Something found", clusters.isEmpty());
    assertEquals("One element found", 1, clusters.size());
    final File ideCluster = clusters.get(0);
    System.setProperty("cluster.path.final", ideCluster.getPath() + ":" + new File(ideCluster.getParent(), "nonexistent"));
    Configuration conf = NbModuleSuite.createConfiguration(NbModuleSuiteClusterPath.class).gui(false).clusters(".*");
    Test test = conf.suite();
    test.run(new TestResult());
    String val = System.getProperty("my.clusters");
    assertNotNull("The test was running", clusters);
    assertNotNull("Value has been set", val);
    assertTrue("ide cluster shall be included: " + val, val.contains(ideCluster.getPath()));
    assertFalse("no java cluster shall be included: " + val, val.matches(".*java[:;].*"));
    assertFalse("no apisupport cluster shall be included: " + val, val.matches(".*apisupport[:;].*"));
    assertFalse("no ergonomics cluster shall be included: " + val, val.matches(".*ergonomics[:;].*"));
}
项目:incubator-netbeans    文件:Benchmark.java   
public final void run( TestResult result ) {
    try {
        Method testMethod = getClass().getMethod( name, emptyClassArray );
        for( int a=0; a<arguments.length; a++ ) {

            result.startTest( this );

            try {
                doOneArgument( testMethod, arguments[a] );
            } catch( AssertionFailedError err ) {
                result.addFailure( this, err );
            } catch( ThreadDeath td ) {
                throw td;                  // need to propagate this
            } catch( Throwable t ) {
                result.addError( this, t );
            }

            result.endTest( this );
        }
    } catch ( Exception e ) {
        e.printStackTrace();
    }
}
项目:incubator-netbeans    文件:ExpandFolderTest.java   
private void iterateTests(TestResult result, StringBuffer times, TestSuite suite, AtomicLong min, AtomicLong max) {
    Enumeration en = suite.tests();
    while (en.hasMoreElements()) {
        Test t = (Test)en.nextElement();
        if (t instanceof Callable) {
            try {
                Long v = (Long)((Callable) t).call();
                long time = v.longValue();
                if (time < min.longValue()) {
                    min.set(time);
                }
                if (time > max.longValue()) {
                    max.set(time);
                }
                // append(t.toString()).append(" value: ")
                times.append("Run: ").append(v).append('\n');
            } catch (Exception ex) {
                result.addError(this, ex);
            }
        }
        if (t instanceof TestSuite) {
            iterateTests(result, times, (TestSuite)t, min, max);
        }
    }
}
项目:incubator-netbeans    文件:LoggingControlTest.java   
public void testRuntimeExceptionsAlsoGenerateLog() throws Exception {
    if (throwIt != null) {
        Logger.getLogger("global").info("Ahoj");
        throw throwIt;
    }

    LoggingControlTest l = new LoggingControlTest("testRuntimeExceptionsAlsoGenerateLog");
    l.throwIt = new NullPointerException();
    TestResult res = l.run();
    assertEquals("No failures", 0, res.failureCount());
    assertEquals("One error", 1, res.errorCount());

    Object o = res.errors().nextElement();
    TestFailure f = (TestFailure)o;

    if (f.exceptionMessage() == null || f.exceptionMessage().indexOf("Ahoj") == -1) {
        fail("Logged messages shall be in exception message: " + f.exceptionMessage());
    }
}
项目:incubator-netbeans    文件:ProfilesTrackerTest.java   
@Override
public void run(TestResult result) {
    for(int i = 0; i < ENV.length; i++) {
        String contents = (String) ENV[i][0];
        String folder = (String) ENV[i][1];
        String type = (String) ENV[i][2];

        for(int j = 0; j < testCount(); j++) {
            Test test = testAt(j);
            if (test instanceof ProfilesTrackerTest) {
                ((ProfilesTrackerTest) test).setEnv(type, folder, contents);
            }
        }

        System.out.println("Running tests for: " + type);
        super.run(result);
    }
}
项目:myfaces-trinidad    文件:TestResponseWriter.java   
/**
 * Creates an XhtmlResponseWriter.
 * @param out a Writer to write to
 * @param contentType the xhtml content type
 * @param encoding the character encoding the Writer uses
 */
public TestResponseWriter(
  Writer out,
  String contentType,
  String encoding,
  Test   test,
  TestResult result) throws UnsupportedEncodingException
{
  if (out == null)
    throw new NullPointerException();

  _out = out;
  _encoding = encoding;
  _test = test;
  _result = result;
  CaboHttpUtils.validateEncoding(encoding);

  _onlyValidIds = "true".equals(
     System.getProperty("org.apache.myfaces.trinidad.TestIdValidity"));
  _testBlockLevel = "true".equals(
     System.getProperty("org.apache.myfaces.trinidad.TestBlockElementNesting"));
}
项目:myfaces-trinidad    文件:RenderKitTestCase.java   
@Override
public void run(TestResult result)
{
  // Cache the TestResult so we can directly add failure without
  // aborting the run
  _result = result;
  CatchSevere catchSevere = new CatchSevere();
  Logger apacheLogger = Logger.getLogger("org.apache");
  apacheLogger.addHandler(catchSevere);

  try
  {
    RenderKitBootstrap.setFactories(_facesConfigInfo);
    super.run(result);
  }
  finally
  {
    apacheLogger.removeHandler(catchSevere);
    RenderKitBootstrap.clearFactories();
  }
}
项目:gemini.blueprint    文件:OsgiJUnitService.java   
/**
 * Execute the JUnit test and publish results to the outside-OSGi world.
 *
 * @param test
 * @throws Exception
 */
protected void executeTest(OsgiJUnitTest test) throws Exception {
    // create holder
    // since we're inside OSGi, we have to use the special loading procedure
    OsgiTestInfoHolder holder = HolderLoader.INSTANCE.getHolder();

    // read the test to be executed
    String testName = holder.getTestMethodName();
    if (log.isDebugEnabled()) {
        log.debug("Reading test [" + testName + "] for execution inside OSGi");
    }
    // execute the test
    TestResult result = runTest(test, testName);

    if (log.isDebugEnabled()) {
        log.debug("Sending test results from OSGi");
    }
    // write result back to the outside world
    TestUtils.unpackProblems(result, holder);
}
项目:gemini.blueprint    文件:TestUtils.java   
/**
 * Clones the test result from a TestResult loaded through a different
 * classloader.
 * 
 * @param source test result loaded through a different classloader
 * @param destination test result reported to the outside framework
 * @param test initial test used for bootstrapping the integration framework
 * @return cloned test result
 */
public static TestResult cloneTestResults(OsgiTestInfoHolder source, TestResult destination, Test test) {
    // get errors
       for (Throwable throwable : source.getTestErrors()) {
           destination.addError(test, throwable);
       }

    // get failures
    // since failures are a special JUnit error, we have to clone the stack
       for (Throwable originalFailure : source.getTestFailures()) {
           AssertionFailedError clonedFailure = new AssertionFailedError(originalFailure.getMessage());
           clonedFailure.setStackTrace(originalFailure.getStackTrace());
           destination.addFailure(test, clonedFailure);
       }

    return destination;
}
项目:gemini.blueprint    文件:AbstractOsgiTests.java   
/**
 * {@inheritDoc}
 * <p/>
 * <p/> Replacement run method. Gets a hold of the TestRunner used for running this test so it can populate it with
 * the results retrieved from OSGi.
 */
public final void run(TestResult result) {

    // get a hold of the test result
    originalResult = result;

    result.startTest(osgiJUnitTest);
    result.runProtected(osgiJUnitTest, new Protectable() {

        public void protect() throws Throwable {
            AbstractOsgiTests.this.runBare();
        }
    });
    result.endTest(osgiJUnitTest);

    // super.run(result);
}
项目:reladomo    文件:MultiVmTestSuite.java   
public void run(TestResult result)
{
    try
    {
        createSlaveVm();
        slaveVm.startSlaveVm(testClass);
        super.run(result);
    }
    catch(RuntimeException e)
    {
        // we log this here, because junit 3.8 hides this exception
        this.logger.error("had a problem running the test", e);
        throw e;
    }
    finally
    {
        slaveVm.shutdownSlaveVm();
    }
}
项目:cacheonix-core    文件:ExtensionTest.java   
public void testRunningErrorsInTestSetup() {
    TestCase failure= new TestCase("failure") {
        public void runTest() {
            fail();
        }
    };

    TestCase error= new TestCase("error") {
        public void runTest() {
            throw new Error();
        }
    };

    TestSuite suite= new TestSuite();
    suite.addTest(failure);
    suite.addTest(error);

    TestSetup wrapper= new TestSetup(suite);

    TestResult result= new TestResult();
    wrapper.run(result);

    assertEquals(1, result.failureCount());
    assertEquals(1, result.errorCount());
}
项目:cacheonix-core    文件:FunctionalTestClassTestSuite.java   
public void run(TestResult testResult) {
    if ( testCount == 0 ) {
        // might be zero if database-specific...
        return;
    }
    try {
        log.info( "Starting test-suite [" + getName() + "]" );
        setUp();
        testPosition = 0;
        super.run( testResult );
    }
    finally {
        try {
            tearDown();
        }
        catch( Throwable ignore ) {
        }
        log.info( "Completed test-suite [" + getName() + "]" );
    }
}
项目:cacheonix-core    文件:FunctionalTestClassTestSuite.java   
public void runTest(Test test, TestResult testResult) {
    testPosition++;
    if ( environmentSetupError != null ) {
        testResult.startTest( test );
        testResult.addError( test, environmentSetupError );
        testResult.endTest( test );
        return;
    }
    if ( ! ( test instanceof FunctionalTestCase ) ) {
        super.runTest( test, testResult );
    }
    else {
        FunctionalTestCase functionalTest = ( ( FunctionalTestCase ) test );
        try {
            // disallow rebuilding the schema because this is the last test
            // in this suite, thus it is about to get dropped immediately
            // afterwards anyway...
            environment.setAllowRebuild( testPosition < testCount );
            functionalTest.setEnvironment( environment );
            super.runTest( functionalTest, testResult );
        }
        finally {
            functionalTest.setEnvironment( null );
        }
    }
}
项目:xstream    文件:SjsxpReaderTest.java   
public static Test suite() {
    try {
        Class.forName(className);
        return new TestSuite(SjsxpReaderTest.class);
    } catch (ClassNotFoundException e) {
        return new TestCase(SjsxpReaderTest.class.getName() + ": not available") {

            public int countTestCases() {
                return 1;
            }

            public void run(TestResult result) {
            }
        };
    }
}
项目:xstream    文件:SjsxpWriterTest.java   
public static Test suite() {
    try {
        Class.forName(className);
        return new TestSuite(SjsxpWriterTest.class);
    } catch (ClassNotFoundException e) {
        return new TestCase(SjsxpWriterTest.class.getName() + ": not available") {

            public int countTestCases() {
                return 1;
            }

            public void run(TestResult result) {
            }
        };
    }
}
项目:mondrian    文件:CacheHitTest.java   
/**
 * Loops <code>n</code> times, each time run a random test case
 * in the test <code>suite</code>
 *
 * @param suite the suite of test cases
 * @param n number of times
 * @throws Exception on error
 */
public void runRandomSuite(TestSuite suite, int n)
    throws Exception
{
    final TestResult tres = new TestResult();
    final MondrianServer server =
        MondrianServer.forConnection(getTestContext().getConnection());

    for (int i = 0; i < n; i++) {
        int suiteIdx = (int) (Math.random() * suite.testCount());
        TestSuite test = (TestSuite) suite.testAt(suiteIdx);
        int testIdx = (int) (Math.random() * test.testCount());
        test.testAt(testIdx).run(tres);
    }
    report(server.getMonitor().getServer());
}
项目:mondrian    文件:CacheHitTest.java   
/**
 * Loops <code>numIte</code> times, each time run all child test
 * suite in the <code>suite</code>
 *
 * @param suite the suite of test suites
 * @param numIter number of iterations
 * @throws Exception on error
 */
public void runTestSuiteInOrder(TestSuite suite, int numIter)
    throws Exception
{
    final TestResult tres = new TestResult();
    final MondrianServer server =
        MondrianServer.forConnection(getTestContext().getConnection());

    for (int i = 0; i < numIter; i++) {
        TestSuite test = (TestSuite) suite.testAt(i % suite.testCount());
        for (int j = 0; j < test.testCount(); j++) {
            test.testAt(j).run(tres);
        }
    }
    report(server.getMonitor().getServer());
}
项目:In-the-Box-Fork    文件:CoreTestRunner.java   
@Override
public TestResult doRun(Test suite, boolean wait) {
    setPrinter(createPrinter());

    /*
     * Make sure the original suite is unreachable after we have
     * created the new one, so GC can dispose terminated tests.
     */
    CoreTestSuite coreTestSuite = new CoreTestSuite(suite, fFlags, fStep, null);

    XmlReportPrinter xmlReportPrinter = xmlReportsDirectory != null
            ? new XmlReportPrinter(coreTestSuite)
            : null;

    TestResult result = super.doRun(coreTestSuite, wait);

    if (xmlReportPrinter != null) {
        System.out.print("Printing XML Reports... ");
        xmlReportPrinter.setResults(result);
        int numFiles = xmlReportPrinter.generateReports(xmlReportsDirectory);
        System.out.println(numFiles + " files written.");
    }

    return result;
}
项目:lcm    文件:ActiveTestSuite.java   
@Override
public void runTest(final Test test, final TestResult result) {
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                // inlined due to limitation in VA/Java
                //ActiveTestSuite.super.runTest(test, result);
                test.run(result);
            } finally {
                ActiveTestSuite.this.runFinished();
            }
        }
    };
    t.start();
}
项目:In-the-Box-Fork    文件:StatTestRunner.java   
public TestResult doRun(Test suite, boolean wait) throws Exception {
    StatsStore.open(jdbcDriver, connectionURL);
    TestResult result = new TestResult();
    result.addListener(fPrinter);
    result.addListener(fPerfStatCollector);
    long startTime= System.currentTimeMillis();
    StatsStore.now = startTime;
    suite.run(result);
    long endTime= System.currentTimeMillis();
    long runTime= endTime-startTime;
    fPrinter.print(result, runTime);
    fPerfStatCollector.digest();
    StatsStore.close();

    pause(wait);
    return result;
}
项目:OpenSPIFe    文件:TextJunitResultFormatter.java   
@Override
public void endTestSuite(TestResult result, long runTime) throws IOException {
    println("\ntests run: " + result.runCount());
    println("errors: " + result.errorCount());
    println("failures: " + result.failureCount());
    println("total run time: " + (runTime / 1000.0) + " seconds");
    println("test lengths in ascending order:");
    for (long duration : testTimes.keySet())
        println(testTimes.get(duration) + " - " + (duration / 1000.0) + " seconds");

    if (exception != null) {
        throw exception;
    }
    if ((out != System.out) && (out != System.err) && (out != null)) {
            out.close();
       }
}
项目:andes    文件:TKTestRunner.java   
/**
 * Runs a test or suite of tests, using the super class implemenation. This method wraps the test to be run
 * in any test decorators needed to add in the configured toolkits enhanced junit functionality.
 *
 * @param test The test to run.
 * @param wait Undocumented. Nothing in the JUnit javadocs to say what this is for.
 *
 * @return The results of the test run.
 */
public TestResult doRun(Test test, boolean wait)
{
    log.debug("public TestResult doRun(Test \"" + test + "\", boolean " + wait + "): called");

    // Wrap the tests in decorators for duration, scaling, repetition, parameterization etc.
    WrappedSuiteTestDecorator targetTest = decorateTests(test);

    // Delegate to the super method to run the decorated tests.
    log.debug("About to call super.doRun");

    TestResult result = super.doRun(targetTest, wait);
    log.debug("super.doRun returned.");

    /*if (result instanceof TKTestResult)
    {
        TKTestResult tkResult = (TKTestResult) result;

        tkResult.notifyEndBatch();
    }*/

    return result;
}
项目:spring-osgi    文件:AbstractOsgiTests.java   
/**
 * {@inheritDoc}
 * 
 * <p/> Replacement run method. Gets a hold of the TestRunner used for
 * running this test so it can populate it with the results retrieved from
 * OSGi.
 */
public final void run(TestResult result) {

    // get a hold of the test result
    originalResult = result;

    result.startTest(osgiJUnitTest);
    result.runProtected(osgiJUnitTest, new Protectable() {

        public void protect() throws Throwable {
            AbstractOsgiTests.this.runBare();
        }
    });
    result.endTest(osgiJUnitTest);

    // super.run(result);
}
项目:sosiefier    文件:TextRunnerTest.java   
public void testRunReturnsResult() {
    PrintStream oldOut = System.out;
    System.setOut(new PrintStream(
            new OutputStream() {
                @Override
                public void write(int arg0) throws IOException {
                }
            }
    ));
    try {
        TestResult result = junit.textui.TestRunner.run(new TestSuite());
        assertTrue(result.wasSuccessful());
    } finally {
        System.setOut(oldOut);
    }
}
项目:sosiefier    文件:TextFeedbackTest.java   
public void testFailure() {
    String expected = expected(new String[]{".F", "Time: 0", "Failures here", "", "FAILURES!!!", "Tests run: 1,  Failures: 1,  Errors: 0", ""});
    ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) {
        @Override
        public void printFailures(TestResult result) {
            getWriter().println("Failures here");
        }
    };
    runner.setPrinter(printer);
    TestSuite suite = new TestSuite();
    suite.addTest(new TestCase() {
        @Override
        public void runTest() {
            throw new AssertionFailedError();
        }
    });
    runner.doRun(suite);
    assertEquals(expected, output.toString());
}
项目:sosiefier    文件:TextFeedbackTest.java   
public void testError() {
    String expected = expected(new String[]{".E", "Time: 0", "Errors here", "", "FAILURES!!!", "Tests run: 1,  Failures: 0,  Errors: 1", ""});
    ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) {
        @Override
        public void printErrors(TestResult result) {
            getWriter().println("Errors here");
        }
    };
    runner.setPrinter(printer);
    TestSuite suite = new TestSuite();
    suite.addTest(new TestCase() {
        @Override
        public void runTest() throws Exception {
            throw new Exception();
        }
    });
    runner.doRun(suite);
    assertEquals(expected, output.toString());
}
项目:sosiefier    文件:ForwardCompatibilityPrintingTest.java   
public void testError() {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    TestRunner runner = new TestRunner(new TestResultPrinter(
            new PrintStream(output)));

    String expected = expected(new String[]{".E", "Time: 0",
            "Errors here", "", "FAILURES!!!",
            "Tests run: 1,  Failures: 0,  Errors: 1", ""});
    ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) {
        @Override
        public void printErrors(TestResult result) {
            getWriter().println("Errors here");
        }
    };
    runner.setPrinter(printer);
    TestSuite suite = new TestSuite();
    suite.addTest(new TestCase() {
        @Override
        public void runTest() throws Exception {
            throw new Exception();
        }
    });
    runner.doRun(suite);
    assertEquals(expected, output.toString());
}
项目:sosiefier    文件:ForwardCompatibilityPrintingTest.java   
public void testErrorAdapted() {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    TestRunner runner = new TestRunner(new TestResultPrinter(
            new PrintStream(output)));

    String expected = expected(new String[]{".E", "Time: 0",
            "Errors here", "", "FAILURES!!!",
            "Tests run: 1,  Failures: 0,  Errors: 1", ""});
    ResultPrinter printer = new TestResultPrinter(new PrintStream(output)) {
        @Override
        public void printErrors(TestResult result) {
            getWriter().println("Errors here");
        }
    };
    runner.setPrinter(printer);
    runner.doRun(new JUnit4TestAdapter(ATest.class));
    assertEquals(expected, output.toString());
}
项目:spring-osgi    文件:TestUtils.java   
/**
 * Clones the test result from a TestResult loaded through a different
 * classloader.
 * 
 * @param source test result loaded through a different classloader
 * @param destination test result reported to the outside framework
 * @param test initial test used for bootstrapping the integration framework
 * @return cloned test result
 */
public static TestResult cloneTestResults(OsgiTestInfoHolder source, TestResult destination, Test test) {
    // get errors
    for (Iterator iter = source.getTestErrors().iterator(); iter.hasNext();) {
        destination.addError(test, (Throwable) iter.next());
    }

    // get failures
    // since failures are a special JUnit error, we have to clone the stack
    for (Iterator iter = source.getTestFailures().iterator(); iter.hasNext();) {
        Throwable originalFailure = (Throwable) iter.next();
        AssertionFailedError clonedFailure = new AssertionFailedError(originalFailure.getMessage());
        clonedFailure.setStackTrace(originalFailure.getStackTrace());
        destination.addFailure(test, clonedFailure);
    }

    return destination;
}