下面列出了junit.framework.TestListener#junit.framework.TestResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
}
/**
* 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);
}
}
/**
* Setup the security manager for this Derby decorator/TestSetup
* and then call the part's run method to run the decorator and
* the test it wraps.
*/
public final void run(TestResult result)
{
// install a default security manager if one has not already been
// installed
if ( System.getSecurityManager() == null )
{
/* gd if (TestConfiguration.getCurrent().defaultSecurityManagerSetup())
{
BaseTestCase.assertSecurityManager();
}
*/
}
super.run(result);
}
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());
}
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 );
}
}
}
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());
}
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());
}
}
/**
* Prints the header of the report
*/
public void printHeader(final TestResult result) {
if (result.wasSuccessful()) {
writer().println();
writer().print("OK");
writer().println(" (" + result.runCount() + " tests)");
} else {
writer().println();
writer().println("FAILURES!!!");
writer().println("~~ Test Results ~~~~~~~~~~~~");
writer().println(" Run: " + result.runCount());
writer().println(" Failures: " + result.failureCount());
writer().println(" Errors: " + result.errorCount());
}
}
@Override
public void run(TestResult result) {
try {
setUp();
try {
runGroupedTests(result);
} finally {
tearDown();
}
// everything went smoothly. report a successful test to make the ends meet
runTest(new FailedTest(getClass(),null),result);
} catch (Throwable e) {
// something went wrong
runTest(new FailedTest(getClass(),e),result);
}
}
@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);
}
}
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() + "]" );
}
}
@Override
public void run(TestResult result) {
Lookup l = Lookup.getDefault();
assertEquals("We can run only with our Lookup", Lkp.class, l.getClass());
Lkp lkp = (Lkp)l;
lkp.reset();
super.run(result);
}
/**
* Runs the tests and collects their result in a TestResult.
*/
public void run(TestResult result) {
if(isPrepared()){
runAllTests(result);
cleanit();
}
if(gotFailed())
createFailLog(result);
}
private final void createFailLog(TestResult result){
//Create a new test case
final String nameFailed = getName()+"FailLog";
MultiTestCase dummy = new MultiTestCase(){
public void execute(){}
};
dummy.setName(nameFailed);
dummy.setError(err);
runTest(dummy, result);
}
/**
* Creates all testcases and runs them.
*/
protected void runAllTests(TestResult result){
for(Object parameter: getParameters()){
for(ParametricTestCase testCase: cases(parameter)){
if(testCase != null){
testCase.parametrize(parameter);
runTest(testCase, result);
}
}
}
}
public void runTest(Test test, TestResult result)
{
MultiVmTest multiVmTest = (MultiVmTest) test;
multiVmTest.setApplicationPorts(this.applicationPort1, this.applicationPort2);
RemoteWorkerVm remoteWorkerVm = workerVm.getRemoteWorkerVm();
multiVmTest.setRemoteWorkerVm(remoteWorkerVm);
remoteWorkerVm.executeMethod("workerVmSetUp");
super.runTest(test, result);
remoteWorkerVm.executeMethod("workerVmTearDown");
}
@Override
public void runTest(Test test, TestResult result) {
int e = result.errorCount();
int f = result.failureCount();
LOG.log(Level.FINE, "Running test {0}", test);
super.runTest(test, result);
LOG.log(Level.FINE, "Finished: {0}", test);
if (e == result.errorCount() && f == result.failureCount()) {
NbModuleLogHandler.checkFailures((TestCase) test, result, test instanceof NbTestCase ? ((NbTestCase) test).getWorkDirPath() : Manager.getWorkDirPath());
}
}
public void testRunningErrorInTestSetup() {
TestCase test= new TestCase("failure") {
public void runTest() {
fail();
}
};
TestSetup wrapper= new TestSetup(test);
TestResult result= new TestResult();
wrapper.run(result);
assertTrue(!result.wasSuccessful());
}
public void testFailOnMessage() {
System.setProperty("generate.msg", "true");
System.setProperty("generate.exc", "false");
Test instance =
NbModuleSuite.createConfiguration(NbModuleSuiteException.class).
gui(false).
failOnMessage(Level.WARNING)
.suite();
TestResult r = junit.textui.TestRunner.run(instance);
assertEquals("One failure", 1, r.failureCount());
assertEquals("No errors", 0, r.errorCount());
TestFailure f = r.failures().nextElement();
assertEquals("Failure name", "testGenerateMsgOrException", ((TestCase)f.failedTest()).getName());
}
public void testFailOnException() {
System.setProperty("generate.msg", "false");
System.setProperty("generate.exc", "true");
Test instance =
NbModuleSuite.createConfiguration(NbModuleSuiteException.class).
gui(false).
failOnException(Level.INFO)
.suite();
TestResult r = junit.textui.TestRunner.run(instance);
assertEquals("One failure", 1, r.failureCount());
assertEquals("No errors", 0, r.errorCount());
TestFailure f = r.failures().nextElement();
assertEquals("Failure name", "testGenerateMsgOrException", ((TestCase)f.failedTest()).getName());
}
public void testSuccessfulRun() {
TestResult result= new TestResult();
fTest.run(result);
assertEquals(fTest.countTestCases(), result.runCount());
assertEquals(0, result.errorCount());
assertEquals(0, result.failureCount());
}
public void testActiveRepeatedTest1() {
Test test= new RepeatedTest(createActiveTestSuite(), 1);
TestResult result= new TestResult();
test.run(result);
assertEquals(100, result.runCount());
assertEquals(0, result.failureCount());
assertEquals(0, result.errorCount());
}
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)) {
public void printFailures(TestResult result) {
getWriter().println("Failures here");
}
};
runner.setPrinter(printer);
TestSuite suite = new TestSuite();
suite.addTest(new TestCase() { public void runTest() {throw new AssertionFailedError();}});
runner.doRun(suite);
assertEquals(expected, output.toString());
}
public void testServices() throws Exception{
Configuration conf = NbModuleSuite.createConfiguration(NbModuleSuiteMeta.class).gui(false);
Test test = conf.suite();
test.run(new TestResult());
assertNotNull("The test was running", System.getProperty("meta"));
assertEquals("result" + System.getProperty("meta"), "ok", System.getProperty("meta"));
}
public void testRepeatedMoreThanOnce() {
Test test= new RepeatedTest(fSuite, 3);
assertEquals(6, test.countTestCases());
TestResult result= new TestResult();
test.run(result);
assertEquals(6, result.runCount());
}
public void testIOExceptionIsWrappedWithLogMsg() throws Exception {
LoggingTest inner = new LoggingTest("throwIOThrowable");
inner.toThrow = new IOException("Ahoj");
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().indexOf("Going to throw") == -1) {
fail("There should be output of the log:\n" + f.exceptionMessage());
}
}
public static void main(String args[]) {
TestRunner runner = new TestRunner();
TestSuite suite = (TestSuite) suite();
TestResult results;
for (int i = 0; i < suite.testCount(); i++) {
System.out.print(testNames[i]);
results = runner.doRun(suite.testAt(i), false);
System.out.println("Results: " + results.runCount() +
" tests run, " + results.failureCount() +
" failures, " + results.errorCount() +
" errors.");
System.out.print("\n----------------------------------------\n");
}
}
public static Test suite() {
System.setProperty("ignore.random.failures", "false");
final Test t = NbTestSuite.linearSpeedSuite(LinearSpeedTest.class, 2,2);
class ThisHasToFail extends TestCase {
public int countTestCases() {
return 1;
}
public String getName() {
return "LinearSpeedTest";
}
public void run(TestResult testResult) {
TestResult r = new TestResult();
t.run(r);
int count = r.errorCount() + r.failureCount();
if (count == 0) {
testResult.startTest(this);
testResult.addFailure(this, new AssertionFailedError("LinearSpeedTest must fail: " + count));
testResult.endTest(this);
} else {
testResult.startTest(this);
testResult.endTest(this);
}
}
}
return new ThisHasToFail();
}
public void testRepeatedOnce() {
Test test= new RepeatedTest(fSuite, 1);
assertEquals(2, test.countTestCases());
TestResult result= new TestResult();
test.run(result);
assertEquals(2, result.runCount());
}
public void testNoServer() {
Configuration conf = NbModuleSuite.createConfiguration(TD.class);
conf = J2eeTestCase.addServerTests(conf).gui(false);
Test t = NbModuleSuite.create(conf);
t.run(new TestResult());
assertEquals("just empty test - no server is registered", 1, t.countTestCases());
}