Skip to content

Instantly share code, notes, and snippets.

@marpiec marpiec/ClockAndTest.scala Secret
Last active Dec 19, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.