Skip to content

Instantly share code, notes, and snippets.

@marpiec
Last active December 19, 2015 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marpiec/5a4a11ce12a9bf81aff9 to your computer and use it in GitHub Desktop.
Save marpiec/5a4a11ce12a9bf81aff9 to your computer and use it in GitHub Desktop.
Simple switching environment for tests. On example of getting a current time.
package com.blogspot.mpieciukiewicz.clock
import org.joda.time.{DateTimeZone, DateTime, Instant}
trait Clock {
def now(): Instant
def dateNow(): DateTime
}
object Clock {
private var clockInstance: Clock = SystemClock
def now() = clockInstance.now()
def dateNow() = clockInstance.dateNow()
def changeClock(newClock:Clock)(codeBlock: => Unit) {
val oldClock = Clock.clockInstance
clockInstance = newClock
codeBlock
clockInstance = oldClock
}
}
object SystemClock extends Clock {
def now() = Instant.now()
def dateNow() = DateTime.now()
}
class FakeClock(fixed: DateTime) extends Clock {
def now() = fixed.toInstant
def dateNow() = fixed
}
object Test {
import Clock.changeClock
def testedMethod() {
println(Clock.dateNow())
}
def main(args: Array[String]) {
testedMethod()
changeClock(new FakeClock(new DateTime(2013, 7, 15, 0, 0, DateTimeZone.UTC))) {
testedMethod()
changeClock(new FakeClock(new DateTime(2012, 2, 2, 0, 0, DateTimeZone.UTC))) {
testedMethod()
}
testedMethod()
}
testedMethod()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment