Open2

ScalaTest の整理

shikazukishikazuki

Testing style

https://www.scalatest.org/user_guide/selecting_a_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
        }
      }
    }
  }
}
shikazukishikazuki

Mockito

Java 向けの mock テストフレームワーク
https://site.mockito.org/

Scala + Mockito
https://www.scalatest.org/plus/mockito
libraryDependencies += "org.scalatestplus" %% "mockito-5-12" % "3.2.19.0" % "test"

// val mockCollaborator = mock(classOf[Collaborator])
// Scala の場合 trait を指定可能
val mockCollaborator = mock[Collaborator]

さらに MockitoSugar が使え、より簡易な構文が使える。
https://www.playframework.com/documentation/ja/2.4.x/ScalaTestingWithScalaTest

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
    }
  }
}

参考

https://www.toptal.com/java/a-guide-to-everyday-mockito