Java 类org.junit.runners.model.Statement 实例源码

项目:Reer    文件:Sample.java   
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
    sampleName = getSampleName(method);
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (sampleName != null) {
                String hintForMissingSample = String.format("If '%s' is a new sample, try running 'gradle intTestImage'.", sampleName);
                TestFile srcDir = new IntegrationTestBuildContext().getSamplesDir().file(sampleName).assertIsDir(hintForMissingSample);
                logger.debug("Copying sample '{}' to test directory.", sampleName);
                srcDir.copyTo(getDir());
            } else {
                logger.debug("No sample specified for this test, skipping.");
            }
            base.evaluate();
        }
    };
}
项目:AndroidSnooper    文件:RunUsingLooper.java   
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      try {
        if(Looper.myLooper()==null) {
          Looper.prepare();
        }
        base.evaluate();
      } finally {
        Looper.myLooper().quit();
      }
    }
  };
}
项目:Reer    文件:RedirectStdOutAndErr.java   
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            originalStdOut = System.out;
            originalStdErr = System.err;
            stdOutRouter.setOut(originalStdOut);
            stdErrRouter.setOut(originalStdErr);
            try {
                System.setOut(stdOutPrintStream);
                System.setErr(stdErrPrintStream);
                base.evaluate();
            } finally {
                System.setOut(originalStdOut);
                System.setErr(originalStdErr);
                stdOutRouter = null;
                stdErrRouter = null;
                stdOutPrintStream = null;
                stdErrPrintStream = null;
                stdoutContent = null;
                stderrContent = null;
            }
        }
    };
}
项目:GongXianSheng    文件:RxSchedulersOverrideRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            RxAndroidPlugins.getInstance().reset();
            RxAndroidPlugins.getInstance().registerSchedulersHook(mRxAndroidSchedulersHook);

            RxJavaHooks.reset();
            RxJavaHooks.setOnIOScheduler(mRxJavaImmediateScheduler);
            RxJavaHooks.setOnNewThreadScheduler(mRxJavaImmediateScheduler);

            base.evaluate();

            RxAndroidPlugins.getInstance().reset();
            RxJavaHooks.reset();
        }
    };
}
项目:GitHub    文件:MockWebServerTest.java   
@Test public void statementStartsAndStops() throws Throwable {
  final AtomicBoolean called = new AtomicBoolean();
  Statement statement = server.apply(new Statement() {
    @Override public void evaluate() throws Throwable {
      called.set(true);
      server.url("/").url().openConnection().connect();
    }
  }, Description.EMPTY);

  statement.evaluate();

  assertTrue(called.get());
  try {
    server.url("/").url().openConnection().connect();
    fail();
  } catch (ConnectException expected) {
  }
}
项目:AndroidSnooper    文件:DataResetRule.java   
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      try {
        base.evaluate();
      } finally {
        SQLiteDatabase database = snooperDbHelper.getWritableDatabase();
        List<String> tableToDelete = Arrays.asList(HEADER_VALUE_TABLE_NAME, HEADER_TABLE_NAME, HTTP_CALL_RECORD_TABLE_NAME);
        for (String table : tableToDelete) {
          database.delete(table, null, null);
        }
        database.close();
      }
    }
  };
}
项目:github-users    文件:ExpectedUncaughtExceptionTest.java   
@Test
public void expectExceptionAndMessage_noExceptionThrown_shouldFail() throws Throwable {
  // given
  Statement originalStatement = mock(Statement.class);
  ExpectedUncaughtException uncaughtThrown = ExpectedUncaughtException.none();
  Statement statement = uncaughtThrown.apply(originalStatement, description);
  thrown.expect(AssertionError.class);
  thrown.expectMessage("No uncaught exception occurred:\n" +
      "Expected: <java.lang.Exception>");

  // when
  uncaughtThrown.expect(Exception.class);
  uncaughtThrown.expectMessage("foo");
  statement.evaluate();

  // then should fail
}
项目:GitHub    文件:RunWithRemoteService.java   
@Override
public Statement apply(final Statement base, Description description) {
    final RunTestWithRemoteService annotation = description.getAnnotation(RunTestWithRemoteService.class);
    if (annotation == null) {
        return base;
    }
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            before(annotation.remoteService());
            try {
                base.evaluate();
            } finally {
                if (!annotation.onLooperThread()) {
                    after();
                }
            }
        }
    };
}
项目:grpc-java-contrib    文件:GrpcContextRule.java   
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            // Reset the gRPC context between test executions
            Context prev = Context.ROOT.attach();
            try {
                base.evaluate();
                if (Context.current() != Context.ROOT) {
                    Assert.fail("Test is leaking context state between tests! Ensure proper " +
                            "attach()/detach() pairing.");
                }
            } finally {
                Context.ROOT.detach(prev);
            }
        }
    };
}
项目:RxRedux    文件:ImmediateSchedulersRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            RxJavaPlugins.setIoSchedulerHandler(scheduler -> Schedulers.trampoline());
            RxJavaPlugins.setComputationSchedulerHandler(scheduler -> Schedulers.trampoline());
            RxJavaPlugins.setNewThreadSchedulerHandler(scheduler -> Schedulers.trampoline());
            RxAndroidPlugins.setMainThreadSchedulerHandler(scheduler -> Schedulers.trampoline());
            try {
                base.evaluate();
            } finally {
                RxJavaPlugins.reset();
            }
        }
    };
}
项目:pact-spring-mvc    文件:PactTestRunner.java   
@Override
protected Statement methodInvoker(final FrameworkMethod method, final Object test) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            PactFrameworkMethod pactFrameworkMethod = (PactFrameworkMethod) method;
            if (pactFrameworkMethod.shouldExclude()) {
                LOG.warn("Test has been excluded. Test will show as passed but was *NOT* run.");
                return;
            }
            if (pactFrameworkMethod.getWorkflow() != null) {
                setUpProviderState(test, pactFrameworkMethod.getWorkflow());
                pactFrameworkMethod.invokeExplosively(test, pactFrameworkMethod.getWorkflow().getInteractions());
            } else {
                setUpProviderState(test, pactFrameworkMethod.getInteraction());
                pactFrameworkMethod.invokeExplosively(test, Collections.singletonList(pactFrameworkMethod.getInteraction()));
            }
        }
    };
}
项目:reactive-playing    文件:WordServiceWithRuleTest.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            RxJavaPlugins.setIoSchedulerHandler(scheduler ->
                    Schedulers.trampoline());
            RxJavaPlugins.setComputationSchedulerHandler(scheduler ->
                    Schedulers.trampoline());
            RxJavaPlugins.setNewThreadSchedulerHandler(scheduler ->
                    Schedulers.trampoline());
            try {
                base.evaluate();
            } finally {
                RxJavaPlugins.reset();
            }
        }
    };
}
项目:morf    文件:InjectMembersRule.java   
/**
 * @see org.junit.rules.MethodRule#apply(org.junit.runners.model.Statement, org.junit.runners.model.FrameworkMethod, java.lang.Object)
 */
@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      final List<Module> moduleWithTarget = new ArrayList<>(Arrays.asList(modules));
      if (target instanceof Module) {
        moduleWithTarget.add((Module) target);
      }
      Guice.createInjector(moduleWithTarget).injectMembers(target);
      try {
        base.evaluate();
      } finally {
        new ThreadSafeMockingProgress().reset();
      }
    }
  };
}
项目:monarch    文件:IgnoreUntilRule.java   
protected Statement throwOnIgnoreTest(Statement statement, Description description) {
  if (isTest(description)) {
    boolean ignoreTest = false;
    String message = "";

    IgnoreUntil testCaseAnnotation = description.getAnnotation(IgnoreUntil.class);

    if (testCaseAnnotation != null) {
      ignoreTest = evaluate(testCaseAnnotation, description);
      message = testCaseAnnotation.value();
    } else if (description.getTestClass().isAnnotationPresent(IgnoreUntil.class)) {
      IgnoreUntil testClassAnnotation =
          description.getTestClass().getAnnotation(IgnoreUntil.class);

      ignoreTest = evaluate(testClassAnnotation, description);
      message = testClassAnnotation.value();
    }

    if (ignoreTest) {
      throw new AssumptionViolatedException(format(message, description));
    }
  }

  return statement;
}
项目:github-users    文件:ExpectedUncaughtExceptionTest.java   
@Test
public void noneExpected_butUncaughtErrorOccurred_shouldFail() throws Throwable {
  // given
  Statement originalStatement = new Statement() {
    @Override
    public void evaluate() throws Throwable {
      Single.just("bar")
          .map(s -> { throw new Exception("foo"); })
          .subscribe();
    }
  };
  ExpectedUncaughtException uncaughtThrown = ExpectedUncaughtException.none();
  Statement statement = uncaughtThrown.apply(originalStatement, description);
  thrown.expect(AssertionError.class);
  thrown.expectMessage("Unexpected uncaught exception");

  // when
  statement.evaluate();

  // then should fail
}
项目:drinkwater-java    文件:MockJndiContextFactoryRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, MockInitialContextFactory.class.getName());
            MockInitialContextFactory.setCurrentContext(context);
            try {
                base.evaluate();
            } finally {
                System.clearProperty(Context.INITIAL_CONTEXT_FACTORY);
                MockInitialContextFactory.clearCurrentContext();
            }
        }
    };
}
项目:junit-rules    文件:DefaultTimeZoneRule.java   
@Override public Statement apply(final Statement base, final Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      final TimeZone timeZone = TimeZone.getDefault();

      try {
        if (preference != null) {
          TimeZone.setDefault(preference);
        }

        base.evaluate();
      } finally {
        TimeZone.setDefault(timeZone);
      }
    }
  };
}
项目:github-users    文件:ExpectedUncaughtExceptionTest.java   
@Test
public void expectMessage_noExceptionThrownButMessageExpected_shouldFail() throws Throwable {
  // given
  Statement originalStatement = mock(Statement.class);
  ExpectedUncaughtException uncaughtThrown = ExpectedUncaughtException.none();
  Statement statement = uncaughtThrown.apply(originalStatement, description);
  thrown.expect(AssertionError.class);
  thrown.expectMessage(
      "No uncaught exception occurred, but expected one with message: \n" +
          "Expected: \"foo\""
  );

  // when
  uncaughtThrown.expectMessage("foo");
  statement.evaluate();

  // then should fail
}
项目:nitrite-database    文件:Retry.java   
private Statement statement(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            Throwable caughtThrowable = null;

            // implement retry logic here
            for (int i = 0; i < retryCount; i++) {
                try {
                    base.evaluate();
                    return;
                } catch (Throwable t) {
                    caughtThrowable = t;
                    log.error(description.getDisplayName() + ": run " + (i+1) + " failed");
                }
            }
            log.info(description.getDisplayName() + ": giving up after " + retryCount + " failures");
            if (caughtThrowable != null) {
                throw caughtThrowable;
            }
        }
    };
}
项目:Architecture    文件:ImmediateSchedulersRule.java   
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      RxJavaPlugins.reset();
      RxJavaPlugins.setIoSchedulerHandler(scheduler -> Schedulers.trampoline());
      RxJavaPlugins.setComputationSchedulerHandler(scheduler -> Schedulers.trampoline());
      RxJavaPlugins.setNewThreadSchedulerHandler(scheduler -> Schedulers.trampoline());

      try {
        base.evaluate();
      } finally {
        RxJavaPlugins.reset();
      }
    }
  };
}
项目:spring-data-examples    文件:RequiresRedisSentinel.java   
@Override
public Statement apply(final Statement base, final Description description) {

    return new Statement() {

        @Override
        public void evaluate() throws Throwable {

            if (description.isTest()) {
                if (RequiresRedisSentinel.this.requiredSentinels != null) {
                    verify(RequiresRedisSentinel.this.requiredSentinels);
                }

            } else {
                verify(RequiresRedisSentinel.this.requiredSentinels);
            }

            base.evaluate();
        }
    };
}
项目:denbun    文件:TimeRule.java   
@Override public Statement apply(final Statement base, final Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      Now annotation = description.getAnnotation(Now.class);
      if (annotation == null) {
        base.evaluate();  // 現在時刻を固定しない
        return;
      }

      try {
        now = parse(annotation.value());
        lockCurrentTime(new Time.NowProvider() {
          @Override public long now() {
            return now;
          }
        });
        base.evaluate();
      } finally {
        unlockCurrentTime();
      }
    }
  };
}
项目:GongXianSheng    文件:TestComponentRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            BoilerplateApplication application = BoilerplateApplication.get(mContext);
            application.setComponent(mTestComponent);
            base.evaluate();
            application.setComponent(null);
        }
    };
}
项目:Jenkins-Plugin-Examples    文件:TimeoutStepTest.java   
@Issue("JENKINS-39134")
@LocalData
@Test public void serialForm() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            WorkflowJob p = story.j.jenkins.getItemByFullName("timeout", WorkflowJob.class);
            WorkflowRun b = p.getBuildByNumber(1);
            RunListener.fireStarted(b, TaskListener.NULL);
            story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b));
        }
    });
}
项目:Reer    文件:AbstractTestDirectoryProvider.java   
public Statement apply(final Statement base, Description description) {
    Class<?> testClass = description.getTestClass();
    init(description.getMethodName(), testClass.getSimpleName());

    suppressCleanupErrors = testClass.getAnnotation(LeaksFileHandles.class) != null
        || description.getAnnotation(LeaksFileHandles.class) != null;

    return new TestDirectoryCleaningStatement(base, description.getDisplayName());
}
项目:monarch    文件:SerializableExternalResource.java   
private Statement statement(final Statement base) {
  return new SerializableStatement() {
    @Override
    public void evaluate() throws Throwable {
      before();
      try {
        base.evaluate();
      } finally {
        after();
      }
    }
  };
}
项目:GitHub    文件:TestComponentRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            try {
                setupDaggerTestComponentInApplication();
                base.evaluate();
            } finally {
                mTestComponent = null;
            }
        }
    };
}
项目:GitHub    文件:TestComponentRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            try {
                setupDaggerTestComponentInApplication();
                base.evaluate();
            } finally {
                mTestComponent = null;
            }
        }
    };
}
项目:GitHub    文件:RecordingObserver.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      for (RecordingObserver<?> subscriber : subscribers) {
        subscriber.assertNoEvents();
      }
    }
  };
}
项目:GitHub    文件:RecordingSubscriber.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      for (RecordingSubscriber<?> subscriber : subscribers) {
        subscriber.assertNoEvents();
      }
    }
  };
}
项目:GitHub    文件:RxJavaPluginsResetRule.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      RxJavaPlugins.reset();
      try {
        base.evaluate();
      } finally {
        RxJavaPlugins.reset();
      }
    }
  };
}
项目:GitHub    文件:RecordingCompletableObserver.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      for (RecordingCompletableObserver subscriber : subscribers) {
        subscriber.assertNoEvents();
      }
    }
  };
}
项目:weld-junit    文件:InjectTest.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            base.evaluate();
            assertTrue(IamDependent.DESTROYED.get());
        }
    };
}
项目:GitHub    文件:WebSocketWriterTest.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      assertEquals("Data not empty", "", data.readByteString().hex());
    }
  };
}
项目:GitHub    文件:InMemoryFileSystem.java   
@Override public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override public void evaluate() throws Throwable {
      base.evaluate();
      ensureResourcesClosed();
    }
  };
}
项目:GitHub    文件:TearDownGlide.java   
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      try {
        base.evaluate();
      } finally {
        Glide.tearDown();
      }
    }
  };
}
项目:GitHub    文件:KeyTester.java   
@Override
public Statement apply(final Statement base, Description description) {
  return new Statement() {

    @Override
    public void evaluate() throws Throwable {
        isUsedAsRule = true;
        base.evaluate();
        if (isUsedWithoutCallingTest) {
          fail("You used KeyTester but failed to call test()!");
        }
    }
  };
}
项目:aws-sdk-java-v2    文件:ResourceCentricBlockJUnit4ClassRunner.java   
/**
 * Override the withBeforeClasses method to inject executing resource
 * creation between @BeforeClass methods and test methods.
 */
@Override
protected Statement withBeforeClasses(final Statement statement) {
    Statement withRequiredResourcesCreation = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            if (classRequiredResourcesAnnotation != null) {
                beforeRunClass(classRequiredResourcesAnnotation.value());
            }
            statement.evaluate();
        }
    };
    return super.withBeforeClasses(withRequiredResourcesCreation);
}
项目:Jenkins-Plugin-Examples    文件:TimeoutStepTest.java   
/**
 * The simplest possible timeout step ever.
 */
@Test
public void basic() throws Exception {
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(
                    "node { timeout(time:5, unit:'SECONDS') { sleep 10; echo 'NotHere' } }", true));
            WorkflowRun b = story.j.assertBuildStatus(Result.ABORTED, p.scheduleBuild2(0).get());
            story.j.assertLogNotContains("NotHere", b);
        }
    });
}
项目:android-mvp-architecture    文件:TestComponentRule.java   
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            try {
                setupDaggerTestComponentInApplication();
                base.evaluate();
            } finally {
                mTestComponent = null;
            }
        }
    };
}