Sbt (1) 一個 sbt project

上一篇我們示範了如何見識一個簡單的 sbt project,今天要來談談 project 的結構和設定檔。

project 的結構習慣上長得像這樣 (上次我們的 Hello world 只用了綠色的部份就可以運作):

<directory>
  project/
    build.properties
  src/
    main/
      scala/
      java/
      resources/
  test/
    scala/
    java/
    resources/
  target/
build.sbt
  1. project/build.properties: 包含 sbt 的版本號,沒建會自己生成。要查詢 sbt 的版本號 可以使用 "sbt sbtVersion"指令
  2. build.sbt: 包含 project 名稱, project 版本, 語言版本和 build tasks 之類的
  3. src, test: source code 和測試程式碼
  4. target: 放 build 完的檔案

1. 開啟 sbt:

$ sbt

2. Tasks:

前面有提到 task,task 就是 sbt 可以執行的動作。

顯示所有的 tasks:

> tasks

我們上次使用的 compile 和 run 都是 tasks,compile 會產生 target 資料夾。


3. Settings:

除了可用的 Tasks 外,我們還可以觀察 project 的 settings:

顯示所有的 settings:

> settings

scalaSource 是 scala 的 source path,我們來看看它的預設路徑:

> scalaSource

[info] .../SbtTest/src/main/scala

所以我們的 .scala 要放在對應的路徑下才能被 sbt 找到。


4. 撰寫和執行測試:

修改 build.sbt

scalaVersion := "2.12.6"
organization := "com.example"

lazy val hello = (project in file("."))
  .settings(
    name := "Hello",
    libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test,
  )

libraryDependencies 指定了要使用的套件,我們要撰寫測試所以使用 scalatest。 你可以從 https://mvnrepository.com/artifact/org.scalatest 找到適合的版本。

進入特定版本後選擇 SBT,它會教你如何添加這個套件。

如果你是一邊開著 sbt 一邊修改 build.sbt 的話,你的改動不會立刻影響到 sbt。 這時候要在 sbt 執行 reload,reload 完你會發現 prompt 改變:

> reload

sbt:Hello>

再開一個 terminal,建立測試檔案,測試檔案要放在 src/test/scala 資料夾:

$ mkdir -p src/test/scala
$ cd src/test/scala
$ vim HelloTest.scala

撰寫一個不會過的測試:

import org.scalatest._

class HelloTest extends FunSuite with DiagrammedAssertions {
  test("Hello should start with H") {
    assert("hello".startsWith("H"))
  }
}

執行測試:

sbt:Hello> test

測試失敗就代表 ok 了:

[info] Done compiling.
[info] HelloTest:
[info] - Hello should start with H *** FAILED ***
[info]   assert("hello".startsWith("H"))
[info]          |       |          |
[info]          "hello" false      "H" (HelloTest.scala:5)
[info] Run completed in 236 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 0, failed 1, canceled 0, ignored 0, pending 0
[info] *** 1 TEST FAILED ***
[error] Failed tests:
[error] 	HelloTest
[error] (Test / test) sbt.TestsFailedException: Tests unsuccessful

留言

熱門文章