### Adding MUnit Dependency (Mill) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This Mill build configuration defines a test module that extends `ScalaTests` and `TestModule.Munit`. It specifies the MUnit library as an Ivy dependency using the `ivyDeps` override. ```Scala object test extends ScalaTests with TestModule.Munit { override def ivyDeps = Agg( ivy"org.scalameta::munit::@STABLE_VERSION@" ) } ``` -------------------------------- ### Adding MUnit Dependency (sbt) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This sbt configuration adds MUnit as a test-scoped library dependency. The `%%` operator ensures the correct Scala binary version is used. For non-JVM projects, `%%%` should be used instead. ```sbt libraryDependencies += "org.scalameta" %% "munit" % "@STABLE_VERSION@" % Test // Use %%% for non-JVM projects. ``` -------------------------------- ### Running All MUnit Tests (sbt Shell) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This shell command sequence demonstrates how to enter the sbt shell and then execute all MUnit tests using the `test` command. It's recommended to stay in the sbt shell for better compiler performance. ```sh $ sbt > test ``` -------------------------------- ### Adding MUnit Dependency (scala-cli) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This snippet shows how to add MUnit as a test dependency in a scala-cli project. It uses the `using test.dep` directive to specify the MUnit library and its stable version. ```Scala //> using test.dep org.scalameta::munit::@STABLE_VERSION@ ``` -------------------------------- ### Configuring MUnit Test Framework (sbt < 1.5.0) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md For sbt versions older than 1.5.0, this configuration is required to explicitly register MUnit as a test framework. It instantiates `munit.Framework` to enable MUnit test discovery and execution. ```sbt testFrameworks += new TestFramework("munit.Framework") ``` -------------------------------- ### Running a Specific MUnit Test Suite (sbt Shell) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This sbt shell command uses `testOnly` to execute tests only within a specified test suite, such as `com.MySuite`. This is useful for focusing on specific tests during development. ```sh # sbt shell > testOnly com.MySuite ``` -------------------------------- ### Creating a Basic MUnit Test Suite Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This Scala code defines a simple MUnit test suite named `MySuite` that extends `munit.FunSuite`. It includes a single test case named 'hello' which demonstrates the `assertEquals` assertion, comparing an `obtained` value to an `expected` value. ```Scala class MySuite extends munit.FunSuite { test("hello") { val obtained = 42 val expected = 43 assertEquals(obtained, expected) } } ``` -------------------------------- ### Adding MUnit Dependency (Maven) Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This XML snippet shows how to declare MUnit as a test-scoped dependency in a Maven `pom.xml` file. It specifies the `groupId`, `artifactId` (with Scala 3 suffix), `version`, and `scope`. ```XML org.scalameta munit_3 @STABLE_VERSION@ test ``` -------------------------------- ### Running Individual MUnit Test Case with .only Marker Source: https://github.com/scalameta/munit/blob/main/docs/getting-started.md This diff snippet illustrates how to use the `.only` marker on a test case name to run only that specific test. This is an alternative to running tests from an IDE's gutter icon. ```Scala - test("name") { + test("name".only) { // ... } ``` -------------------------------- ### Composing Functional Test-Local Fixtures in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This example illustrates how to combine multiple functional test-local fixtures into a single fixture using `FunFixture.map2`. It creates a fixture that provides two distinct temporary files, verifying that they are different and regular files. This allows for more complex test setups. ```Scala // Fixture with access to two temporary files. val files2 = FunFixture.map2(files, files) files2.test("two") { case (file1, file2) => assertNotEquals(file1, file2) assert(Files.isRegularFile(file1), s"Files.isRegularFile($file1)") assert(Files.isRegularFile(file2), s"Files.isRegularFile($file2)") } ``` -------------------------------- ### Implementing Reusable Suite-Local Fixture in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This example shows how to implement a reusable suite-local fixture using `munit.Fixture[T]`. It overrides `beforeAll` to establish a database connection once for the entire test suite and `afterAll` to close it, ensuring efficient resource management across multiple tests within the same suite. ```Scala import java.sql.Connection import java.sql.DriverManager class MySuite extends munit.FunSuite { val db = new Fixture[Connection]("database") { private var connection: Connection = null def apply() = connection override def beforeAll(): Unit = { connection = DriverManager.getConnection("jdbc:h2:mem:", "sa", null) } override def afterAll(): Unit = { connection.close() } } override def munitFixtures = List(db) test("test1") { db() // database connection has been initialized } test("test2") { // ... db() // the same `db` instance as in "test1" } } ``` -------------------------------- ### Defining Suite-Local Fixtures with beforeAll/afterAll in MUnit (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This snippet demonstrates how to implement suite-local setup and teardown logic using `beforeAll()` and `afterAll()` methods in an MUnit `FunSuite`. It shows how to establish and close a database connection once for the entire test suite, ensuring resources are managed efficiently across multiple test cases. ```Scala import java.sql.Connection import java.sql.DriverManager class MySuite extends munit.FunSuite { var db: Connection = null // Runs once before all tests start. override def beforeAll(): Unit = { // start in-memory database connection. db = DriverManager.getConnection("jdbc:h2:mem:", "sa", null) } // Runs once after all tests have completed, regardless if tests passed or failed. override def afterAll(): Unit = { db.close() } } ``` -------------------------------- ### Converting ScalaTest Matchers (shouldEqual) to MUnit Source: https://github.com/scalameta/munit/blob/main/docs/scalatest.md This example demonstrates how to replace ScalaTest's `shouldEqual` matcher, typically used with `with Matchers`, with MUnit's `assertEquals` for equivalent assertion functionality. ```diff - result shouldEqual Some(Name(first, last)) + assertEquals(result, Some(Name(first, last))) ``` -------------------------------- ### Initializing MUnit Test Suite in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet initializes a basic MUnit test suite by defining an object `Tests` that extends `munit.FunSuite` and imports its members. This setup is a prerequisite for declaring tests within the MUnit framework. ```scala object Tests extends munit.FunSuite import Tests._ ``` -------------------------------- ### Converting ScalaTest WordSpec to MUnit FunSuite Source: https://github.com/scalameta/munit/blob/main/docs/scalatest.md This example shows how to flatten `WordSpec` style tests, which use nested descriptions, into MUnit's flat `FunSuite` structure to ensure all tests are executed. ```diff -class FooSpec extends AnyWordSpec with Matchers { +class FooSpec extends FunSuite { - "Foo" must { - "succeed" in { + test("Foo must succeed") { ... - } ``` -------------------------------- ### Defining Basic ScalaCheck Properties in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This example demonstrates how to define property-based tests by extending `munit.ScalaCheckSuite`. It uses `forAll` from ScalaCheck to generate arbitrary inputs and verifies properties using boolean expressions, such as commutativity of addition and the identity property of zero. ```Scala import munit.ScalaCheckSuite import org.scalacheck.Prop._ class IntegerSuite extends ScalaCheckSuite { property("addition is commutative") { forAll { (n1: Int, n2: Int) => n1 + n2 == n2 + n1 } } property("0 is the identity of addition") { forAll { (n: Int) => n + 0 == n } } } ``` -------------------------------- ### Declaring Integer Variables in Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet declares two immutable integer variables, `a` and `b`, and initializes them with values 1 and 2 respectively. These variables are used as examples for subsequent assertion demonstrations. ```Scala val a = 1 val b = 2 ``` -------------------------------- ### Implementing Custom Test Filtering with MUnit Tags Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-02-01-hello-world.md This advanced MUnit example shows how to create a custom `TestTransform` to conditionally ignore tests based on environment properties like operating system and Scala version. It defines a `Windows213` tag and applies a transformation that marks tests with this tag as `Ignore` if the environment does not match Windows and Scala 2.13. ```Scala import scala.util.Properties import munit._ object Windows213 extends Tag("Windows213") class MySuite extends FunSuite { override def munitTestTransforms = super.munitTestTransforms ++ List( new TestTransform("Windows213", { test => val isIgnored = test.tags(Windows213) && !( Properties.isWin && Properties.versionNumberString.startsWith("2.13") ) if (isIgnored) test.tag(Ignore) else test }) ) test("windows-213".tag(Windows213)) { // Only runs when operating system is Windows and Scala version is 2.13 } test("normal test") { // Always runs like a normal test. } } ``` -------------------------------- ### Implementing Asynchronous Test Fixtures with MUnit FutureFixture (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This example illustrates how to use `munit.FutureFixture[T]` to manage asynchronous test resources. It defines a `file` fixture that creates a temporary file before each test (`beforeEach`) and deletes it after each test (`afterEach`), returning `Future[Unit]` for these operations. This ensures proper cleanup even if tests fail. ```Scala import java.nio.file._ import java.sql.Connection import java.sql.DriverManager import munit.FutureFixture import munit.FunSuite import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class AsyncFilesSuite extends FunSuite { val file = new FutureFixture[Path]("files") { var file: Path = null def apply() = file override def beforeEach(context: BeforeEach): Future[Unit] = Future { file = Files.createTempFile("files", context.test.name) } override def afterEach(context: AfterEach): Future[Unit] = Future { // Always gets called, even if test failed. Files.deleteIfExists(file) } } override def munitFixtures = List(file) test("exists") { // `file` is the temporary file that was created for this test case. assert(Files.exists(file())) } } ``` -------------------------------- ### Integrating Existing ScalaCheck Properties into MUnit Suite Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This example demonstrates how to use the `PropertiesAdapter` trait to include pre-existing ScalaCheck `Properties` (like `LegacyIntProps`) within an MUnit `ScalaCheckSuite`. It allows for a gradual migration, enabling new MUnit properties to coexist with older ScalaCheck definitions. ```scala object LegacyIntProps extends Properties("Int") { property("commutative") = forAll((x: Int, y: Int) => x + y == y + x) property("identity") = forAll((x: Int) => x + 0 == x) } class IntSuite extends ScalaCheckSuite with PropertiesAdapter { // Include existing ScalaCheck Properties... include(LegacyIntProps) // ...and write new properties using MUnit property("addition is associative") { forAll { (x: Int, y: Int, z: Int) => x + y + z == x + (y + z) } } } ``` -------------------------------- ### Sharing Test Suite Configuration in MUnit (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This example illustrates how to share common configurations across multiple MUnit test suites by declaring an abstract `BaseSuite` that extends `munit.FunSuite`. This `BaseSuite` can override properties like `munitTimeout` and `munitTestTransforms`, allowing derived suites like `MyFirstSuite` and `MySecondSuite` to inherit these settings. ```Scala abstract class BaseSuite extends munit.FunSuite { override val munitTimeout = Duration(1, "min") override def munitTestTransforms = super.munitTestTransforms ++ List(???) // ... } class MyFirstSuite extends BaseSuite { /* ... */ } class MySecondSuite extends BaseSuite { /* ... */ } ``` -------------------------------- ### Using ScalaCheck API for Multiple Property Conditions Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-03-24-scalacheck.md This example illustrates how to combine multiple conditions within a single ScalaCheck property using boolean expressions (`&&`) and labels (`:|`). Labels help identify which specific part of the expression fails, providing more context during test failures. ```Scala property("integer identities") { forAll { (n: Int) => (n + 0 == n) :| "0 is the addition identity" && (n * 1 == n) :| "1 is the multiplication identity" } } ``` -------------------------------- ### Marking a ScalaCheck Property as Expected to Fail Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This example shows how to mark a ScalaCheck property as expected to fail using MUnit's `fail` method. This is useful for documenting known issues or for tests that are temporarily failing but should not break the build. ```Scala property("issue-123".fail) { forAll { (n: Int) => buggyFunction(n) } } ``` -------------------------------- ### Combining Ignore and Pending Tags in MUnit Scala Tests Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This example illustrates how to combine `.ignore` and `.pending` tags on a single MUnit test. This allows a test that is currently failing (and thus ignored) to also be marked as pending with a comment, providing context for why it's ignored and indicating it's awaiting a fix. ```Scala test("this test worked yesterday".ignore.pending("platform investigation")) { assert(LocalDate.now.equals(yesterday)) } ``` -------------------------------- ### Equivalent Boolean Expression for ScalaCheck Property Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This snippet shows the equivalent boolean expression for the property demonstrated in the previous example, where multiple assertions are combined. While functionally similar, this method offers less detailed error reporting than using MUnit's `assertEquals`. ```Scala property("integer identities") { forAll { (n: Int) => (n + 0 == n) && (n * 1 == n) } } ``` -------------------------------- ### Customizing ScalaCheck Test Parameters in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This example illustrates how to override the `scalaCheckTestParameters` method in `ScalaCheckSuite` to customize ScalaCheck's behavior. Parameters like `withMinSuccessfulTests` and `withMaxDiscardRatio` control the number of successful tests and the acceptable discard ratio for generated inputs. ```Scala import munit.ScalaCheckSuite import org.scalacheck.Prop._ class IntegerSuite extends ScalaCheckSuite { override def scalaCheckTestParameters = super.scalaCheckTestParameters .withMinSuccessfulTests(200) .withMaxDiscardRatio(10) property("addition is commutative") { forAll { (n1: Int, n2: Int) => n1 + n2 == n2 + n1 } } } ``` -------------------------------- ### MUnit Test Output with Dynamic Scala Version Suffix Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet illustrates the console output when tests are run with dynamic name customization based on the Scala version. It shows how a test named 'foo' gets suffixes like '-2.11.2', '-2.12.10', and '-2.13.1', making it easier to pinpoint failures related to specific Scala versions. ```Scala ==> X munit.ScalaVersionFrameworkSuite.foo-2.11.2 /path/to/ScalaVersionSuite.scala:11 assertion failed 10: test("foo") { 11: assert(!scalaVersion.startsWith("2.11")) 12: } at munit.Assertions.fail(Assertions.scala:121) + munit.ScalaVersionFrameworkSuite.foo-2.12.10 + munit.ScalaVersionFrameworkSuite.foo-2.13.1 ``` -------------------------------- ### Customizing MUnit Value Transforms for LazyFuture in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet demonstrates how to extend MUnit's asynchronous type handling by overriding `munitValueTransforms`. It adds a `ValueTransform` for `LazyFuture` to ensure its `run()` method is called, making the test correctly fail when the wrapped `Future` throws an exception, as seen in the 'ok-task' example. ```scala import scala.concurrent.ExecutionContext.Implicits.global class TaskSuite extends munit.FunSuite { override def munitValueTransforms = super.munitValueTransforms ++ List( new ValueTransform("LazyFuture", { case LazyFuture(run) => run() }) ) implicit val ec = ExecutionContext.global test("ok-task") { LazyFuture { Thread.sleep(5000) // Test will fail because `LazyFuture.run()` is automatically called throw new RuntimeException("BOOM!") } } } ``` -------------------------------- ### Demonstrating `compileErrors` Limitations with Variables in MUnit Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This example illustrates a limitation of `compileErrors()`: it only accepts string literals. Passing variables or string interpolators, as shown here with `code` and `s"/* code */ $code"`, will result in a compile error for the test itself, not the intended code snippet. ```Scala val code = """val x: String = 2""" compileErrors(code) compileErrors(s"/* code */ $code") ``` -------------------------------- ### Dynamically Customizing MUnit Test Names with Scala Version Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This example shows how to override `munitTestTransforms` to dynamically append the current Scala version to test names. This is useful for identifying which Scala version caused a test failure when running tests across multiple versions, improving log readability and debugging. ```Scala class ScalaVersionSuite extends munit.FunSuite { val scalaVersion = scala.util.Properties.versionNumberString override def munitTestTransforms = super.munitTestTransforms ++ List( new TestTransform("append Scala version", { test => test.withName(test.name + "-" + scalaVersion) }) ) test("foo") { assert(!scalaVersion.startsWith("2.11")) } } ``` -------------------------------- ### Declaring MUnit Test with Custom LazyFuture Type in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet defines a custom `LazyFuture` type and demonstrates a test using it. The `LazyFuture` wraps a `Future` but only executes it when `run()` is called. Without custom MUnit handling, tests using `LazyFuture` might pass unexpectedly if `run()` is not invoked, as shown by the 'buggy-task' example. ```scala import scala.concurrent.ExecutionContext case class LazyFuture[+T](run: () => Future[T]) object LazyFuture { def apply[T](thunk: => T)(implicit ec: ExecutionContext): LazyFuture[T] = LazyFuture(() => Future(thunk)) } test("buggy-task") { LazyFuture { Thread.sleep(10) // WARNING: test will pass because `LazyFuture.run()` was never called throw new RuntimeException("BOOM!") } } ``` -------------------------------- ### Correct Usage of `compileErrors` with String Literal in MUnit Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet demonstrates the correct way to use `compileErrors()` by providing the code snippet directly as a string literal. This resolves the issue shown in the previous example where variables or interpolators were used, allowing MUnit to correctly assert the compile-time error for `val x: String = 2`. ```Scala compileErrors("val x: String = 2") ``` -------------------------------- ### Creating a Basic MUnit Test Suite Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-02-01-hello-world.md This Scala code defines a simple MUnit test suite by extending `munit.FunSuite`. It includes a single test case named 'hello' that uses `assert` to check a condition, demonstrating the basic structure of an MUnit test. ```Scala // src/test/scala/com/MySuite.scala class MySuite extends munit.FunSuite { test("hello") { assert(41 == 42) } } ``` -------------------------------- ### Adding MUnit Dependency in sbt Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-02-01-hello-world.md This snippet demonstrates how to add MUnit as a library dependency and configure its test framework in an sbt build file. It specifies the MUnit version and registers the `munit.Framework` for test execution. ```Scala // build.sbt libraryDependencies += "org.scalameta" %% "munit" % "0.4.3" testFrameworks += new TestFramework("munit.Framework") ``` -------------------------------- ### Initializing MUnit Test Suite in Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet initializes a basic MUnit test suite by extending `munit.FunSuite` and disabling ANSI colors for consistent output. It then imports all members from the `Tests` object, making MUnit's assertion methods available in the scope. ```Scala object Tests extends munit.FunSuite { override val munitAnsiColors = false } import Tests._ ``` -------------------------------- ### Converting Basic ScalaTest FunSuite to MUnit Source: https://github.com/scalameta/munit/blob/main/docs/scalatest.md This snippet demonstrates how to replace `org.scalatest.FunSuite` with `munit.FunSuite` and adapt `ignore` and `pending` test syntax for MUnit compatibility. ```diff - import org.scalatest.munit.AnyFunSuite - import org.scalatest.FunSuite + import munit.FunSuite - class MySuite extends FunSuite with BeforeAll with AfterAll { + class MySuite extends FunSuite { test("name") { // unchanged } - ignore("ignored") { + test("ignored".ignore) { // unchanged } - test("pending") (pending) + test("pending".pending) { + // zero or more assertions + } ``` -------------------------------- ### Defining Ad-Hoc Test-Local Fixtures in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This snippet demonstrates how to create ad-hoc test-local fixtures by directly overriding `beforeEach` and `afterEach` methods within a `munit.FunSuite`. It sets up a temporary file before each test and cleans it up afterwards, providing a simple way to manage resources on a per-test basis without a separate `Fixture` class. ```Scala import java.nio.file._ class MySuite extends munit.FunSuite { var path: Path = null // Runs before each individual test. override def beforeEach(context: BeforeEach): Unit = { path = Files.createTempFile("MySuite", context.test.name) } // Runs after each individual test. override def afterEach(context: AfterEach): Unit = { Files.deleteIfExists(path) } test("test1") { // ... path // will be deleted after this test case finishes } test("test2") { // ... path // not the same `path` as in "test1" } } ``` -------------------------------- ### Defining Case Class and Instances in Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet defines a `case class` named `Library` with properties `name`, `awesome`, and `versions`. It then creates two instances, `munitLibrary` and `mdocLibrary`, which are used to demonstrate `assertEquals()` with complex data structures. ```Scala case class Library(name: String, awesome: Boolean, versions: Range = 0.to(1)) val munitLibrary = Library("MUnit", true) val mdocLibrary = Library("MDoc", true) ``` -------------------------------- ### Defining Basic ScalaCheck Properties with MUnit Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-03-24-scalacheck.md This snippet demonstrates how to define basic property-based tests in MUnit by extending the `ScalaCheckSuite` trait. It uses `forAll` to test fundamental mathematical properties like the commutativity of addition and the identity of zero, showcasing the core syntax for writing properties. ```Scala import munit.ScalaCheckSuite import org.scalacheck.Prop._ class IntegerSuite extends ScalaCheckSuite { property("addition is commutative") { forAll { (n1: Int, n2: Int) => n1 + n2 == n2 + n1 } } property("0 is the identity of addition") { forAll { (n: Int) => n + 0 == n } } } ``` -------------------------------- ### Printing Full Stack Traces in MUnit (Shell) Source: https://github.com/scalameta/munit/blob/main/docs/troubleshooting.md This command demonstrates how to pass the `-F` flag to the `testOnly` task in sbt, enabling full stack trace printing for MUnit tests. This is useful for debugging cryptic errors by preventing MUnit from trimming redundant information. ```Shell $ sbt > myproject/testOnly -- -F ``` -------------------------------- ### Defining Reusable Test-Local Fixture in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This snippet demonstrates creating a reusable test-local fixture by extending `munit.Fixture[T]`. It overrides `beforeEach` to create a temporary file before each test and `afterEach` to delete it, ensuring resource cleanup. The fixture is registered with the test suite via `munitFixtures`. ```Scala import java.nio.file._ import munit._ class FilesSuite extends FunSuite { val file = new Fixture[Path]("files") { var file: Path = null def apply() = file override def beforeEach(context: BeforeEach): Unit = { file = Files.createTempFile("files", context.test.name) } override def afterEach(context: AfterEach): Unit = { // Always gets called, even if test failed. Files.deleteIfExists(file) } } override def munitFixtures = List(file) test("exists") { // `file` is the temporary file that was created for this test case. assert(Files.exists(file())) } } ``` -------------------------------- ### Breaking Changes in MUnit v0.5.x Method Signatures (Diff) Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-02-16-async.md This diff highlights the breaking changes introduced in MUnit v0.5.x, primarily the transition of method return types and parameter types from `Any` to `Future[Any]`. This change enables proper asynchronous test handling by requiring test bodies to return `Future`s. ```diff -- MUnit v0.4.x ++ MUnit v0.5.x - def munitTestValue(body: Any): Any + def munitTestValue(body: => Any): Future[Any] - def munitRunTest(options: TestOptions, body: Any): Any + def munitRunTest(options: TestOptions, body: () => Future[Any]): Future[Any] - def munitExpectFailure(options: TestOptions, body: Any): Any + def munitExpectFailure(options: TestOptions, body: () => Future[Any]): Future[Any] - def munitFlaky(options: TestOptions, body: Any): Any + def munitFlaky(options: TestOptions, body: () => Future[Any]): Future[Any] ``` -------------------------------- ### Avoiding Stateful Operations in MUnit Test Class Constructors (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This snippet illustrates an anti-pattern: initializing stateful resources directly in the test class constructor. It warns that such resources (like a database connection) might be initialized even if no tests run, potentially leading to resource leaks if `afterAll()` is not called. It emphasizes using `beforeAll()` for proper resource management. ```Scala import java.sql.DriverManager class MySuite extends munit.FunSuite { // Don't do this, because the class may get initialized even if no tests run. val db = DriverManager.getConnection("jdbc:h2:mem:", "sa", null) override def afterAll(): Unit = { // May never get called, resulting in connection leaking. db.close() } } ``` -------------------------------- ### Adding MUnit Diff Module Dependency (sbt) Source: https://github.com/scalameta/munit/blob/main/website/blog/2024-05-22-release-1.0.0.md This snippet demonstrates how to include the `munit-diff` module as a separate dependency in an sbt project. This allows developers to leverage MUnit's powerful diffing capabilities without needing to integrate the entire test framework. ```sbt libraryDependencies += "org.scalameta" %% "munit-diff" % "1.0.0" ``` -------------------------------- ### Creating Functional Test-Local Fixture in MUnit Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This snippet demonstrates how to define a functional test-local fixture using `munit.FunFixture` in Scala. It sets up a temporary file before each test and ensures its deletion afterwards, even if the test fails. The fixture provides a `Path` object to the test case. ```Scala import java.nio.file._ class FunFixtureSuite extends munit.FunSuite { val files = FunFixture[Path]( setup = { test => Files.createTempFile("tmp", test.name) }, teardown = { file => // Always gets called, even if test failed. Files.deleteIfExists(file) } ) files.test("basic") { file => assert(Files.isRegularFile(file), s"Files.isRegularFile($file)") } } ``` -------------------------------- ### `assertEquals()` with Case Classes in MUnit Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet demonstrates `assertEquals()` comparing two instances of a `case class`, `munitLibrary` and `mdocLibrary`. MUnit automatically generates a detailed diff highlighting the differences between the objects when the assertion fails. ```Scala assertEquals(munitLibrary, mdocLibrary) ``` -------------------------------- ### Tagging MUnit Tests for Inclusion/Exclusion (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md Demonstrates how to define and apply tags to individual MUnit tests using `new munit.Tag` and `.tag()`. These tags can then be used from the command line to include or exclude specific groups of tests. ```scala class TagsSuite extends munit.FunSuite { val include = new munit.Tag("include") val exclude = new munit.Tag("exclude") test("a".tag(include)) {} test("b".tag(exclude)) {} test("c".tag(include).tag(exclude)) {} test("d") {} } ``` -------------------------------- ### Creating Custom Effect Type Fixtures with MUnit AnyFixture (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/fixtures.md This snippet demonstrates how to define a custom fixture type, `ResourceFixture`, by extending `munit.AnyFixture[T]`. It shows how to override lifecycle methods (`beforeAll`, `beforeEach`, `afterEach`, `afterAll`) to return a hypothetical `Resource[Unit]` effect type, enabling integration with custom effect systems. This pattern helps IDEs with type inference for custom effect types. ```Scala import munit.AfterEach import munit.BeforeEach // Hypothetical effect type called "Resource" sealed abstract class Resource[+T] object Resource { def unit: Resource[Unit] = ??? } abstract class ResourceFixture[T](name: String) extends munit.AnyFixture[T](name) { // The main purpose of "ResourceFixture" is to help IDEs auto-complete // the result type "Resource[Unit]" instead of "Any" when implementing the // "ResourceFixture" class. override def beforeAll(): Resource[Unit] = Resource.unit override def beforeEach(context: BeforeEach): Resource[Unit] = Resource.unit override def afterEach(context: AfterEach): Resource[Unit] = Resource.unit override def afterAll(): Resource[Unit] = Resource.unit } ``` -------------------------------- ### Creating Custom sbt Test Tasks with MUnit Tags (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md Shows how to define custom sbt configurations and tasks (e.g., `Slow`, `All`) to run specific subsets of MUnit tests based on tags. This enables creating dedicated commands for different test categories like "slow tests" or "all tests". ```scala val MUnitFramework = new TestFramework("munit.Framework") val Slow = config("slow").extend(Test) val All = config("all").extend(Test) lazy val myproject = project .configs(Slow, All) .settings( testFrameworks += MUnitFramework, inConfig(Slow)(Defaults.testTasks), inConfig(All)(Defaults.testTasks), testOptions.in(All) := List(), testOptions.in(Test) += Tests.Argument(MUnitFramework, "--exclude-tags=Slow"), testOptions.in(Slow) -= Tests.Argument(MUnitFramework, "--exclude-tags=Slow"), testOptions.in(Slow) += Tests.Argument(MUnitFramework, "--include-tags=Slow") ) ``` -------------------------------- ### Converting Basic ScalaTest Assertions to MUnit Source: https://github.com/scalameta/munit/blob/main/docs/scalatest.md This snippet illustrates the optional conversion of `assert(a == b)` to `assertEquals(a, b)` in MUnit for improved error messages on assertion failures. ```diff - assert(a == b) + assertEquals(a, b) ``` -------------------------------- ### Running MUnit Tests with Category Filters (Shell) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md These shell commands illustrate how to execute MUnit tests by including or excluding specific categories from the command line. The `--include-categories` and `--exclude-categories` flags are used with `testOnly` to filter test suites based on the categories defined in the Scala code. ```sh # matches: MySlowSuite, MySlowFastSuite > testOnly -- --include-categories=myapp.Slow # matches: MySlowSuite > testOnly -- --include-categories=myapp.Slow --exclude-categories=myapp.Fast ``` -------------------------------- ### Customizing MUnit Diff Context Size - Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet demonstrates how to customize the diff output in MUnit by defining an implicit `munit.diff.DiffOptions` instance. It sets the `withContextSize` to 10, increasing the number of context lines shown around modified lines in test failures, making discrepancies easier to spot. Requires `munit.FunSuite` and `munit.diff.DiffOptions`. ```scala import munit.FunSuite class CustomContextSizeTest extends FunSuite { private implicit val diffOptions = munit.diff.DiffOptions.withContextSize(10) test("contextSize") { val a = List("a", "a", "a", "a", "a", "a", "a", "a", "a") val b = List("a", "a", "a", "a", "b", "a", "a", "a", "a") assertEquals(a,b) } } ``` -------------------------------- ### Handling By-Name vs. Eager Parameters in MUnit Test Helpers - Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet illustrates the importance of using by-name parameters (`=> Array[Byte]`) in MUnit test helper functions to prevent slow or stateful operations from being evaluated eagerly during class construction. `checkByName` correctly defers `readAllBytes` execution to the test body, while `checkEager` evaluates it immediately, which can lead to issues if the file doesn't exist or the operation is costly. ```scala // OK: `bytes` parameter is by-name so `readAllBytes` is evaluated in test body. def checkByName(name: String, bytes: => Array[Byte]): Unit = test(name) { /* use bytes */ } // Not OK: `bytes` parameter is eager so `readAllBytes` is evaluated in class constructor. def checkEager(name: String, bytes: Array[Byte]): Unit = test(name) { /* use bytes */ } import java.nio.file.{Files, Paths} checkByName("file", Files.readAllBytes(Paths.get("build.sbt"))) checkEager("file", Files.readAllBytes(Paths.get("build.sbt"))) ``` -------------------------------- ### Demonstrating Async Test Failure in MUnit v0.4.x (Scala) Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-02-16-async.md This snippet illustrates a problematic asynchronous test case in MUnit v0.4.x. Despite the `Promise` failing after 100 milliseconds, the test would incorrectly succeed, highlighting the lack of true async support. It uses `Promise` and `setTimeout` to simulate an asynchronous operation. ```Scala test("should fail after 100 milliseconds") { val p = Promise[Unit]() setTimeout(100) { p.failure(new RuntimeException("boom")) } p.future } ``` -------------------------------- ### Using MUnit Assertions for Multiple Property Conditions Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-03-24-scalacheck.md This snippet presents an alternative to ScalaCheck's boolean expressions for multi-condition properties by leveraging MUnit's built-in assertions like `assertEquals`. This approach improves readability, simplifies the expression, and provides more precise error reporting by highlighting the exact line of failure. ```Scala property("integer identities") { forAll { (n: Int) => assertEquals(n + 0, n, "0 is the addition identity") assertEquals(n * 1, n, "1 is the multiplication identity") } } ``` -------------------------------- ### Running a Single MUnit Test with .only (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md Shows how to use the `.only` modifier on a `test` definition to execute only that specific test case within a suite, without requiring command-line arguments. Other tests in the suite will be skipped. ```scala object Tests extends munit.FunSuite import Tests._ test("issue-457") { // will not run } test("issue-456".only) { // only test that runs } test("issue-455") { // will not run } ``` -------------------------------- ### Filtering MUnit Tests by Glob Pattern (Shell) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md Demonstrates how to use `testOnly -- $GLOB` in the sbt shell to run tests matching a fully qualified name glob pattern. This allows running specific test cases or all tests within a package. ```sh # sbt shell > testOnly -- *issue-456 > testOnly -- com.foo.controllers.* ``` -------------------------------- ### Declaring Reusable MUnit Tests with Helper Function and Location - Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This Scala snippet demonstrates how to create a reusable helper function `check` for defining MUnit tests, reducing duplication. It takes `name`, `original` list, and `expected` option as parameters. Crucially, it includes an `implicit loc: munit.Location` parameter to ensure that test failures point to the specific `check` call site rather than the `assertEquals` line within the helper, improving debugging. ```scala def check[T]( name: String, original: List[T], expected: Option[T] )(implicit loc: munit.Location): Unit = { test(name) { val obtained = original.headOption assertEquals(obtained, expected) } } check("basic", List(1, 2), Some(1)) check("empty", List(), Some(1)) check("null", List(null, 2), Some(null)) ``` -------------------------------- ### Migrating ScalaTest GeneratorDrivenPropertyChecks with Matchers to MUnit ScalaCheckSuite (Diff) Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This diff illustrates migrating a ScalaTest `FunSuite` using `GeneratorDrivenPropertyChecks` and `Matchers` to an MUnit `ScalaCheckSuite`. It involves updating imports, extending `ScalaCheckSuite`, replacing `test` with `property`, and converting ScalaTest matchers (`should be`) to MUnit assertions (`assertEquals`). ```diff -import org.scalatest.Matchers -import org.scalatest.prop.GeneratorDrivenPropertyChecks -import org.scalatest.FunSuite +import munit.ScalaCheckSuite +import org.scalacheck.Prop._ -class IntegerSuite extends FunSuite with GeneratorDrivenPropertyChecks with Matchers { +class IntegerSuite extends ScalaCheckSuite { - test("addition and multiplication are commutative") { + property("addition and multiplication are commutative") { forAll { (n1: Int, n2: Int) => forAll { (n1: Int, n2: Int) => - (n1 + n2) should be (n2 + n1) - (n1 * n2) should be (n2 * n1) + assertEquals(n1 + n2, n2 + n1) + assertEquals(n1 * n2, n2 * n1) } } } ``` -------------------------------- ### Fixing Invalid MUnit Test Class Definition (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/troubleshooting.md This snippet illustrates the correction for the `InvalidTestClassError` in MUnit. It shows that test suites must be defined as a `class` instead of an `object` to ensure they have a public constructor and runnable methods, resolving the initialization error. ```Scala class MySuite extends munit.FunSuite { ... } ``` -------------------------------- ### Verifying ScalaCheck Properties with MUnit Assertions Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This snippet demonstrates using MUnit's built-in assertions, like `assertEquals`, within a ScalaCheck property. This approach provides more detailed error reporting, including source location, compared to simple boolean expressions. ```Scala import munit.ScalaCheckSuite import org.scalacheck.Prop._ class IntegerSuite extends ScalaCheckSuite { property("integer identities") { forAll { (n: Int) => assertEquals(n + 0, n) assertEquals(n * 1, n) } } } ``` -------------------------------- ### Dynamically Filtering MUnit Test Cases (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md This Scala snippet shows how to override the `munitTests()` method in an `munit.FunSuite` to dynamically filter test cases. It demonstrates skipping tests based on the operating system, specifically excluding tests without the 'Windows' tag when running on Windows, while allowing tagged tests to run. ```scala import scala.util.Properties case object Windows extends munit.Tag("Windows") class MyWindowsTagSuite extends munit.FunSuite { override def munitTests(): Seq[Test] = { val default = super.munitTests() if (!Properties.isWin) default else default.filter(_.tags.contains(Windows)) } test("files".tag(Windows)) { // will always run, including on Windows } test("files") { // will not run in Windows } } ``` -------------------------------- ### Basic `fail()` Usage in MUnit Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet demonstrates the `fail()` method, which immediately causes the current test case to fail. It takes a string argument that serves as the failure message, in this case, "test failed". ```Scala fail("test failed") ``` -------------------------------- ### Declaring Basic MUnit Test in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet demonstrates how to declare a basic test case in MUnit using the `test()` function. A basic test passes if its body executes without throwing an exception. It serves as a fundamental building block for test suites. ```scala test("basic") { } ``` -------------------------------- ### Customizing MUnit Printer for Date Comparison in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet shows how to customize MUnit's `Printer` to modify how values are compared and displayed. By overriding `printer` to extract only the date part of an `Instant`, it allows `assertEquals` to consider two `Instant` objects equal if their dates match, ignoring the time component. ```scala import java.time.Instant import munit.FunSuite import munit.diff.Printer class CompareDatesOnlyTest extends FunSuite { override val printer = Printer.apply { // take only the date part of the Instant case instant: Instant => instant.toString.takeWhile(_ != 'T') } test("dates only") { val expected = Instant.parse("2022-02-15T18:35:24.00Z") val actual = Instant.parse("2022-02-15T18:36:01.00Z") assertEquals(actual, expected) // true } } ``` -------------------------------- ### Migrating munitTestValue Override to MUnit v0.5.x (Scala) Source: https://github.com/scalameta/munit/blob/main/website/blog/2020-02-16-async.md This Scala snippet demonstrates the updated override for `munitTestValue` in MUnit v0.5.x. It now accepts a call-by-name parameter and returns a `Future[Any]`, correctly integrating with the new asynchronous API by flatMapping over the super call's result to handle `LazyFuture`s. ```Scala override def munitTestValue(testValue: => Any): Future[Any] = super.munitTestValue(testValue).flatMap { case LazyFuture(run) => run() case value => Future.successful(value) } ``` -------------------------------- ### Customizing MUnit Printer for List of Chars in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet demonstrates customizing MUnit's `Printer` to alter the string representation of `List[Char]` values, particularly for failure clues. By converting `List[Char]` to a single string, it provides a more readable diff output when `assertEquals` fails, making it easier to identify discrepancies between character lists. ```scala import munit.FunSuite import munit.diff.Printer class CustomListOfCharPrinterTest extends FunSuite { override val printer = Printer.apply { case l: List[Char] => l.mkString } test("lists of chars") { val expected = List('h', 'e', 'l', 'l', 'o') val actual = List('h', 'e', 'l', 'l', '0') assertEquals(actual, expected) } } ``` -------------------------------- ### Migrating ScalaTest Checkers to MUnit ScalaCheckSuite (Diff) Source: https://github.com/scalameta/munit/blob/main/docs/integrations/scalacheck.md This diff shows the changes required to migrate a ScalaTest `FunSuite` using `Checkers` to an MUnit `ScalaCheckSuite`. Key changes include updating imports, extending `ScalaCheckSuite`, and replacing `test` with `property` and `check` with `forAll`. ```diff -import org.scalatest.prop.Checkers -import org.scalatest.FunSuite +import munit.ScalaCheckSuite import org.scalacheck.Prop._ -class IntegerSuite extends FunSuite with Checkers { +class IntegerSuite extends ScalaCheckSuite { - test("addition is commutative") { + property("addition is commutative") { - check { (n1: Int, n2: Int) => + forAll { (n1: Int, n2: Int) => n1 + n2 == n2 + n1 } } } ``` -------------------------------- ### Dynamically Ignoring MUnit Test Suite with munitIgnore (Scala) Source: https://github.com/scalameta/munit/blob/main/docs/filtering.md Shows how to override the `munitIgnore: Boolean` method within a test suite to conditionally skip the entire suite based on a dynamic condition, such as the operating system. ```scala class MyWindowsOnlySuite extends munit.FunSuite { override def munitIgnore: Boolean = !scala.util.Properties.isWin test("windows-only") { // only runs on Windows } } ``` -------------------------------- ### Converting Complex ScalaTest Matchers (have size) to MUnit Source: https://github.com/scalameta/munit/blob/main/docs/scalatest.md This snippet shows how to convert more complex ScalaTest matchers, such as `should have size`, into simpler MUnit assertions using `assertEquals` and direct property access. ```diff - myList should have size 2 + assertEquals(myList.length, 2) ``` -------------------------------- ### Tagging MUnit Tests as Pending in Scala Source: https://github.com/scalameta/munit/blob/main/docs/tests.md This snippet demonstrates how to use the `.pending` tag in MUnit to mark work-in-progress or incomplete test cases. Pending tests must pass their assertions but are reported as Ignored, unless they fail, in which case they are reported as Failures. It also shows how to add optional comments for tracking purposes. ```Scala // Empty placeholder, without logged comments: test("time travel".pending) { // Test case to be written yesterday } // Empty placeholder, with logged comments: test("time travel".pending("requirements from product owner")) { // Is this funded yet?? } // Empty placeholder, tracked for action: test("time travel".pending("INTERN-101")) { // Test case to be written by an intern } // Incomplete (WIP) placeholder, tracked for action: test("time travel".pending("QA-404")) { assert(LocalDate.now.isAfter(yesterday)) // QA team to provide specific examples for regression-test coverage } ``` -------------------------------- ### `assert()` with `clue()` on Complex Expressions in MUnit Scala Source: https://github.com/scalameta/munit/blob/main/docs/assertions.md This snippet demonstrates `clue()` wrapping more complex expressions, specifically `List(a).head`. When the assertion `clue(List(a).head) > clue(b)` fails, the values of both `List(a).head` and `b` are included in the error message for better debugging. ```Scala assert(clue(List(a).head) > clue(b)) ```