Skip to content

Instantly share code, notes, and snippets.

@atsuya046
Last active October 13, 2015 03:33
Show Gist options
  • Save atsuya046/83309094eb8eddffae70 to your computer and use it in GitHub Desktop.
Save atsuya046/83309094eb8eddffae70 to your computer and use it in GitHub Desktop.
specs2 example
class Core {
def run(): Boolean = {
true
}
}
class CoreTest extends Specification with BeforeEach with AfterEach {
override protected def before: Any = {
println("before do.")
}
override protected def after: Any = {
println("after do.")
}
"example1 test" >> {
val sut = new Core()
val result = sut.run()
result must_==(true)
}
}
class Core {
def sumUp(a: Int, b: Int): Int = {
a + b
}
}
class CoreTest extends Specification with org.specs2.specification.Tables with ScalaCheck {
val sut = new Core()
"example2 test1" >> {
"1 + 1 = 2" >> {
sut.sumUp(1, 1) must_==(2)
}
"3 + 4 = 7" >> {
sut.sumUp(3, 4) must_==(7)
}
}
"example2 test with Tables" >> {
"a" | "b" | "result" |>
1 ! 1 ! 2 |
3 ! 4 ! 7 |
{(a, b, result) => sut.sumUp(a, b) must_==(result)}
}
"example2 test with ScalaCheck" >> {
prop {(a: Int, b: Int) => sut.sumUp(a, b) must_==(a + b)}
}
}
class Core(val tooHeavy: TooHeavy) {
def run(): Boolean = {
println(tooHeavy.get())
true
}
}
trait TooHeavy {
def get(): String
}
class TooHeavyMan extends TooHeavy {
override def get(): String = {
"It is too heavy..."
}
}
class CoreTest extends Specification with Mockito {
"example3 test with mock" >> {
val tooHeavy = mock[TooHeavy]
val sut = new Core(tooHeavy)
sut.run() must_==(true) // print "null"
}
"example3 test with stub" >> {
val tooHeavy = mock[TooHeavy]
tooHeavy.get() returns "Not heavy <3"
val sut = new Core(tooHeavy)
sut.run() must_==(true) // print "Not heavy <3"
}
"example3 test with spy" >> {
val tooHeavy = spy(new TooHeavyMan) // real object
val sut = new Core(tooHeavy)
sut.run() must_==(true) // print "It is too heavy..."
}
"example3 test with spy + stub" >> {
val tooHeavy = spy(new TooHeavyMan) // real object
tooHeavy.get() returns "Not heavy <3"
val sut = new Core(tooHeavy)
sut.run() must_==(true) // print "Not heavy <3"
}
}
class Core @Inject()(hoge: Hoge) {
def run() :Boolean = {
println(hoge.exec())
true
}
}
trait Hoge {
def exec(): String
}
class TestModule extends AbstractModule with ScalaModule {
def configure() = {
bind[Hoge].to[HogeImpl]
}
}
class HogeImpl extends Hoge {
override def exec(): String = {
"hogehoge"
}
}
class CoreTest extends Specification {
val injector = Guice.createInjector(new TestModule)
val sut = injector.getInstance(classOf[Core])
"example4 test" >> {
sut.run() must_==(true) // print "hogehoge"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment