Skip to content

Instantly share code, notes, and snippets.

@ara-ta3
Created August 18, 2021 12:24
Show Gist options
  • Save ara-ta3/130f2bd4c7020c31b7612149b0d7dc86 to your computer and use it in GitHub Desktop.
Save ara-ta3/130f2bd4c7020c31b7612149b0d7dc86 to your computer and use it in GitHub Desktop.

PrivateMethodをscalatestでテストする

$sbt test
[info] welcome to sbt 1.5.1 (Oracle Corporation Java 15)
[info] loading settings for project global-plugins from plugins.sbt ...
[info] loading global plugins from /Users/arata/.sbt/1.0/plugins
[info] loading project definition from /Users/arata/Documents/Workspace/scala/scalatest/project
[info] loading settings for project root from build.sbt ...
[info] set current project to scalameter-getting-started (in build file:/Users/arata/Documents/Workspace/scala/scalatest/)
[info] TestSpec:
[info] test
[info] - addPositiveNumber
[info] - addOne
[info] - minusOne
[info] Run completed in 247 milliseconds.
[info] Total number of tests run: 3
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 3, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.

Ref

val commonSettings = Seq(
version := "0.1-SNAPSHOT",
scalaVersion := "2.13.6",
scalacOptions ++= Seq(
"-deprecation",
"-feature",
"-unchecked",
"-language:implicitConversions",
"-Xlint",
"-Xfatal-warnings",
"-Ywarn-numeric-widen",
"-Ywarn-unused",
"-Ywarn-unused:imports",
"-Ywarn-value-discard"
)
)
lazy val root = (project in file("."))
.settings(commonSettings)
.settings(
name := "scalameter-getting-started",
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "3.2.9"
)
)
import org.scalatest.PrivateMethodTester
import org.scalatest.freespec.AnyFreeSpec
class TestSpec extends AnyFreeSpec with PrivateMethodTester {
"test" - {
val t = new Test()
"addPositiveNumber" in {
assert(t.addPositiveNumber(10, 10) == 20)
}
val addOne = PrivateMethod[Int](Symbol("addOne"))
"addOne" in {
assert(t.invokePrivate(addOne(10)) == 11)
}
val minusOne = PrivateMethod[Int](Symbol("minusOne"))
"minusOne" in {
assert(t.invokePrivate(minusOne(10)) == 9)
}
}
}
class Test {
def addPositiveNumber(x: Int, y: Int): Int = if (y <= 0) {
x
} else {
addPositiveNumber(addOne(x), minusOne(y))
}
private def addOne(x: Int): Int = x + 1
private def minusOne(x: Int): Int = x - 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment