示例#1
0
 /**
  * Returns a {@link Statement}: apply all static {@link Value} fields annotated with {@link Rule}.
  *
  * @param statement the base statement
  * @return a WithClassRules statement if any class-level {@link Rule}s are found, or the base
  *     statement
  */
 private Statement withClassRules(Statement statement) {
   final List<TestRule> classRules = classRules();
   if (classRules.isEmpty()) {
     return statement;
   }
   Statement next = statement;
   for (final TestRule classRule : classRules) {
     next = classRule.apply(next, getDescription());
   }
   return next;
 }
示例#2
0
  /**
   * Ad hoc invocation of a callable wrapped in the start/finish behaviour of a JUnit rule.
   *
   * @param callable the callable to execute
   * @param rule the rule to wrap it in
   * @throws Exception on any exception thrown by the callable or the rule
   */
  public static <V> V callWith(Callable<V> callable, TestRule rule) throws Exception {
    class CallableStatement extends Statement {

      final Callable<V> callable;

      V result;

      CallableStatement(Callable<V> callable) {
        this.callable = callable;
      }

      @Override
      public void evaluate() throws Throwable {
        result = callable.call();
      }
    }

    try {
      CallableStatement statement = new CallableStatement(callable);
      rule.apply(statement, Description.EMPTY).evaluate();
      return statement.result;
    } catch (Throwable t) {
      if (t instanceof Exception) {
        throw (Exception) t;
      } else {
        throw (Error) t;
      }
    }
  }