Package inspiredbyte.examples.rules

Source Code of inspiredbyte.examples.rules.StaticTimeRule

package inspiredbyte.examples.rules;

import inspiredbyte.examples.rules.annotations.StaticTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class StaticTimeRule implements TestRule {

  private static DateTimeFormatter formatter = DateTimeFormat.forPattern("MM-dd-yyyy HH:mm:ss");

  @Override
  public Statement apply(Statement base, Description description) {
    StaticTime staticTime = description.getAnnotation(StaticTime.class);

    return staticTime != null ? new StaticTimeStatement(base, getValue(staticTime)) : base;
  }

  private long getValue(StaticTime staticTime) {
    return !"".equals(staticTime.value())
        ? formatter.parseLocalDateTime(staticTime.value()).toDate().getTime()
        : System.currentTimeMillis();
  }

  static class StaticTimeStatement extends Statement {

    private Statement base;
    private long value;

    public StaticTimeStatement(Statement base, long value) {
      this.base = base;
      this.value = value;
    }

    @Override
    public void evaluate() throws Throwable {
      try {
        DateTimeUtils.setCurrentMillisFixed(value);
        base.evaluate();
      } finally {
        DateTimeUtils.setCurrentMillisSystem();
      }
    }
  }
}
TOP

Related Classes of inspiredbyte.examples.rules.StaticTimeRule

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.