Package

com

thoughtworks

Permalink

package thoughtworks

Visibility
  1. Public
  2. All

Type Members

  1. final class example extends Annotation with StaticAnnotation

    Permalink

    Generates unit tests from examples in Scaladoc in files.

    Generates unit tests from examples in Scaladoc in files.

    Getting started

    Suppose you have a source file src/main/scala/yourPackage/YourClass.scala, which contains some code examples in its Scaladoc. You can run those examples as test cases with this library.

    Step 1: Add this library as test dependency

    Add the following code in your build.sbt:

    libraryDependencies += "com.thoughtworks.example" %% "example" % "latest.release" % Test
    
    libraryDependencies += "org.scalatest" %% "scalatest"  % "latest.release" % Test
    
    addCompilerPlugin(("org.scalameta" % "paradise" % "3.0.0-M8").cross(CrossVersion.patch))
    
    // paradise plugin should only be enabled in test configuration.
    autoCompilerPlugins in Test := true
    autoCompilerPlugins in Compile := false
    
    

    Step 2: Create the test suite class

    Create a source file at src/test/scala/yourPackage/YourClassSpec.scala, with the following content:

    import com.thoughtworks.example
    
    @example("src/main/scala/yourPackage/YourClass.scala")
    class YourClassSpec extends org.scalatest.FreeSpec
    

    The @example annotation will extract code in Scaladoc in src/main/scala/yourPackage/YourClass.scala as a org.scalatest.FreeSpec

    Step 3: Run tests

    sbt test
    

    You will notice that all code blocks inside {{{ }}} in Scaladoc comments in src/test/scala/yourPackage/YourClass.scala are executed.

    Common code

    Code blocks before any Scaladoc tag are shared by all test cases. For example:

    import org.scalatest._, Matchers._

    Then Scalatest matchers will be available for all test cases.

    Author:

    杨博 (Yang Bo) <[email protected]>

    Annotations
    @compileTimeOnly( ... )
    Examples:
    1. A code block under a Scaladoc tag is a test case. The test case is inside a org.scalatest.FreeSpec

      this should be(a[FreeSpec])
    2. ,
    3. A code block may define variables.

      val i = 1
      val s = "text"

      Those variables are accessible from other code blocks under the same Scaladoc tag.

      i should be(1)
      s should be("text")
    Note

    A variable defined under a Scaladoc tag is not accessible from code blocks under another tags.

    "i" shouldNot compile
    See also

    example.scala on Github

Ungrouped