Open2
ScalaTest の整理

Testing style
- The FunSuite style : xUnit に近い
- The FlatSpec style : xUnit に近く、BDD形式で書きたい時
- The FunSpec style : Ruby の Rspec に近い
- The WordSpec style : specs or specs2 に近い
- The FreeSpec style : 一番柔軟性がある
個人的には FreeSpec style が一番癖がなく書きやすいと感じる
import org.scalatest.freespec.AnyFreeSpec
class SetSpec extends AnyFreeSpec {
"A Set" - {
"when empty" - {
"should have size 0" in {
assert(Set.empty.size == 0)
}
"should produce NoSuchElementException when head is invoked" in {
assertThrows[NoSuchElementException] {
Set.empty.head
}
}
}
}
}

Mockito
Java 向けの mock テストフレームワーク
Scala + MockitolibraryDependencies += "org.scalatestplus" %% "mockito-5-12" % "3.2.19.0" % "test"
// val mockCollaborator = mock(classOf[Collaborator])
// Scala の場合 trait を指定可能
val mockCollaborator = mock[Collaborator]
さらに MockitoSugar が使え、より簡易な構文が使える。
case class Data(retrievalDate: java.util.Date)
trait DataService {
def findData: Data
}
import org.scalatest._
import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play._
import org.mockito.Mockito._
class ExampleMockitoSpec extends PlaySpec with MockitoSugar {
"MyService#isDailyData" should {
"return true if the data is from today" in {
val mockDataService = mock[DataService]
when(mockDataService.findData) thenReturn Data(new java.util.Date())
val myService = new MyService() {
override def dataService = mockDataService
}
val actual = myService.isDailyData
actual mustBe true
}
}
}
参考