-
-
Save marpiec/5a4a11ce12a9bf81aff9 to your computer and use it in GitHub Desktop.
Simple switching environment for tests. On example of getting a current time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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