scalasbtsbt-native-packager

How to publish Test Only Objects in a sbt project


I have been developing a common library for my team, where I need to provide mock data for end users to write unit-test code. Ideally, the mock object should only be available to tests of packages referencing mine, but I am not sure how to do this.

My package structure is:

├── common
│   ├── src
│   │   ├── main
│   │   │   ├── resources
│   │   │   └── scala
│   │   └── test
│   │       ├── resources
│   │       └── scala
│   │           └── MockData.scala // <--- object defined here
├── build.sbt

In my build.sbt, I have

Test / publishArtifact := true
Test / publish := true

packageBin / publishArtifact := true

And I use sbt clean; sbt compile; sbt publishLocal to publish my library locally.

In the project referencing the above library, I added the following to the build.sbt:


ThisBuild / libraryDependencies ++= Seq(
  "org.my" %% "common" % "0.0.1",
  "org.my" %% "common" % "0.0.1" % Test,
)

but when writing tests, I cannot find objects defined in MockData.scala.

Please provide some hints, much appreciated.

------------------ UPDATE ------------------

After googling around, I'd decided to write a separate module for publishing test data only. So my package structure becomes:

├── common
│   ├── src
│   │   ├── main
│   │   │   ├── resources
│   │   │   └── scala
│   │   └── test
│   │       ├── resources
│   │       └── scala
├── common-testkit
│   ├── src
│   │   └── main
│   │       ├── resources
│   │       └── scala
│   │           └── MockData.scala // <--- object defined here
├── build.sbt

Solution

  • The issue is in the way you ask to retrieve the test code in your other project.

    "org.my" %% "common" % "0.0.1" % Test means to depends on the "main" code of project common when running the tests of your other project. That's what the scope Test (after the version) means.

    What you want is to depend on the "test code" of common project when running your tests. This is done by specifying what is called a "classifier" in sbt:

    "org.my" %% "common" % "0.0.1" % Test classifier "tests"