{"id":13801445,"url":"https://github.com/mockito/mockito-scala","last_synced_at":"2026-04-15T19:00:34.777Z","repository":{"id":33045193,"uuid":"138417954","full_name":"mockito/mockito-scala","owner":"mockito","description":"Mockito for Scala language","archived":false,"fork":false,"pushed_at":"2026-04-05T10:18:36.000Z","size":2911,"stargazers_count":362,"open_issues_count":24,"forks_count":58,"subscribers_count":14,"default_branch":"release/2.x","last_synced_at":"2026-04-05T12:12:54.426Z","etag":null,"topics":["cats","mock","mocking-framework","mocking-library","mockito","mocks","scala","scalatest","scalaz","specs2","tdd","test-automation","test-driven-development","testing","testing-tools"],"latest_commit_sha":null,"homepage":"http://mockito.org","language":"Scala","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mockito.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2018-06-23T16:45:29.000Z","updated_at":"2026-04-05T10:18:41.000Z","dependencies_parsed_at":"2023-02-15T12:15:48.964Z","dependency_job_id":"f1fb1876-cb49-41a1-bbed-690776fb826b","html_url":"https://github.com/mockito/mockito-scala","commit_stats":{"total_commits":736,"total_committers":36,"mean_commits":"20.444444444444443","dds":0.6942934782608696,"last_synced_commit":"0196423377352d6de1353791d980be5b32c76c71"},"previous_names":[],"tags_count":194,"template":false,"template_full_name":null,"purl":"pkg:github/mockito/mockito-scala","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockito%2Fmockito-scala","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockito%2Fmockito-scala/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockito%2Fmockito-scala/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockito%2Fmockito-scala/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mockito","download_url":"https://codeload.github.com/mockito/mockito-scala/tar.gz/refs/heads/release/2.x","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockito%2Fmockito-scala/sbom","scorecard":{"id":579179,"data":{"date":"2025-08-11","repo":{"name":"github.com/mockito/mockito-scala","commit":"be2546235504260a5e23db369722ff91548e46a5"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":6,"checks":[{"name":"Code-Review","score":6,"reason":"Found 18/28 approved changesets -- score normalized to 6","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Token-Permissions","score":10,"reason":"GitHub workflow tokens follow principle of least privilege","details":["Warn: jobLevel 'contents' permission set to 'write': .github/workflows/ci.yml:62","Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:18"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Maintained","score":10,"reason":"30 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:39: update your workflow using https://app.stepsecurity.io/secureworkflow/mockito/mockito-scala/ci.yml/release/2.x?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:42: update your workflow using https://app.stepsecurity.io/secureworkflow/mockito/mockito-scala/ci.yml/release/2.x?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:54: update your workflow using https://app.stepsecurity.io/secureworkflow/mockito/mockito-scala/ci.yml/release/2.x?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:55: update your workflow using https://app.stepsecurity.io/secureworkflow/mockito/mockito-scala/ci.yml/release/2.x?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:74: update your workflow using https://app.stepsecurity.io/secureworkflow/mockito/mockito-scala/ci.yml/release/2.x?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:79: update your workflow using https://app.stepsecurity.io/secureworkflow/mockito/mockito-scala/ci.yml/release/2.x?enable=pin","Info:   0 out of   5 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   1 third-party GitHubAction dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'release/2.x'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Packaging","score":10,"reason":"packaging workflow detected","details":["Info: Project packages its releases by way of GitHub Actions.: .github/workflows/ci.yml:60"],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Binary-Artifacts","score":9,"reason":"binaries present in source code","details":["Warn: binary detected: sbt/sbt-launch.jar:1"],"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 27 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-20T18:42:33.701Z","repository_id":33045193,"created_at":"2025-08-20T18:42:33.701Z","updated_at":"2025-08-20T18:42:33.701Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31855432,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-15T15:24:51.572Z","status":"ssl_error","status_checked_at":"2026-04-15T15:24:39.138Z","response_time":63,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cats","mock","mocking-framework","mocking-library","mockito","mocks","scala","scalatest","scalaz","specs2","tdd","test-automation","test-driven-development","testing","testing-tools"],"created_at":"2024-08-04T00:01:22.882Z","updated_at":"2026-04-15T19:00:34.769Z","avatar_url":"https://github.com/mockito.png","language":"Scala","funding_links":[],"categories":["Table of Contents","Testing"],"sub_categories":["Testing"],"readme":"# Mockito Scala\n\n\u003ca href=\"http://site.mockito.org\"\u003e\n\u003cimg src=\"https://github.com/mockito/mockito/raw/release/2.x/src/javadoc/org/mockito/logo.png\"\n     srcset=\"https://github.com/mockito/mockito/raw/release/2.x/src/javadoc/org/mockito/logo@2x.png 2x\"\n     alt=\"Mockito\" /\u003e\n\u003c/a\u003e\n\nThe most popular mocking framework for Java, now in Scala!!!\n\n[![Maven Central](https://img.shields.io/maven-central/v/org.mockito/mockito-scala_2.12.svg)](https://search.maven.org/search?q=mockito-scala)\n\n[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/mockito-scala/)\n\n[![Cats Friendly](https://typelevel.org/cats/img/cats-badge-tiny.png)](https://typelevel.org/cats/)\n## Why separate project?\n\nThe library has independent developers, release cycle and versioning from core mockito library (\u003chttps://github.com/mockito/mockito\u003e). This is intentional because core Mockito developers don't use Scala and cannot confidently review PRs, and set the vision for the Scala library.\n\n## Dependency\n\n*   Artifact identifier: \"org.mockito:mockito-scala_[scala-version]:[version]\"\n*   Artifact identifier: \"org.mockito:mockito-scala-scalatest_[scala-version]:[version]\"\n*   Artifact identifier: \"org.mockito:mockito-scala-specs2_[scala-version]:[version]\"\n*   Artifact identifier: \"org.mockito:mockito-scala-cats_[scala-version]:[version]\"\n*   Artifact identifier: \"org.mockito:mockito-scala-scalaz_[scala-version]:[version]\"\n*   Latest version - see [release notes](/docs/release-notes.md)\n*   Repositories: [Maven Central](https://search.maven.org/search?q=mockito-scala)\n\n\n### Please ensure you don't declare `mockito-core` as a dependency. `mockito-scala` will pull the appropriate version automatically\n\n\n### Note: For more examples and use cases than the ones shown below, please refer to the library's specific tests\n- [Cats](/cats/src/test)\n- [ScalaTest](/scalatest/src/test)\n- [Specs2](/specs2/src/test)\n- [Scalaz](/scalaz/src/test)\n\n## Partial unification\nIf you're in Scala 2.12 you'll probably want to add the compiler flag `-Ypartial-unification`, if you don't you risk some compile errors when trying to stub complex types using the idiomatic syntax\n\n## Notes for 2.1.0\n\n### Scala 3: `mock[T]` wrapper methods must be `inline`\n\nIn Scala 3, `mock[T]` uses a compile-time macro to register by-name/vararg parameter metadata\nand value-class return types for `T`. This macro only works when `T` is concrete at the call site,\nwhich requires every method in the call chain to be `inline`.\n\nIf you wrap `mock[T]` in a helper, declare it `inline`:\n\n```scala\n// CORRECT — T is concrete at every call site\ninline def lenientMock[T \u003c: AnyRef: ClassTag]: T =\n  mock[T](Mockito.withSettings().strictness(Strictness.LENIENT))\n\n// WRONG — T is erased; by-name/vararg metadata will NOT be registered\ndef lenientMock[T \u003c: AnyRef: ClassTag]: T =\n  mock[T](Mockito.withSettings().strictness(Strictness.LENIENT))\n```\n\nWithout `inline`, stubs on by-name or vararg methods will silently fail to match at runtime.\n\n## Notes for 2.0.0\nWe dropped support for Scala 2.11 and Java 8, as Mockito 5 dropped support for Java 8.\nJava 11 is now the minimum supported version.\n\n## Notes for 1.13.6\n\nWe slightly changed the way one would expect no/no more interactions with a mock object in Expectations DSL.\nFrom now on, `expect (...) to` should only be used on stubbed methods, and can't express expectations about interactions with the mock objects itself.\n\nIn order to express expectations on a mock, one would use `expect (...) on` (note the use of `on` vs `to`) where such expectations are supported.\n\n* Instead of `expect no calls to aMock`, use `expect no calls on aMock`.\n* Instead of `expect noMore calls to aMock`, use `expect noMore calls on aMock`.\n\nExpectations about no _method_ calls stay the same: `expect no calls to aMock.bar(*)`.  \n\n## Notes for 1.13.0\n\nWe added a new experimental Expectations DSL for idiomatic syntax. It behaves differently from the original idiomatic verifications: \nthe user declares intent to verify by using `expect` at the beginning of the line rather than at the end of it - similar to \"verify\" in Mockito Java.\n\nNow, you can do `expect a call to aMock.bar(*)` where previously you did `aMock.bar(*) was called`. More examples in [Expect DSL](#expect-dsl)\n\nNote that since this DSL is currently experimental, it's not stable - the DSL itself may evolve, components and base traits may move or be renamed, and incompatible changes may be introduced between minor/patch versions.\n\nIn order to use it...\n* with Scalatest base traits, mix in `org.mockito.scalatest.IdiomaticMockitoBase with org.mockito.PrefixExpectations` instead of `org.mockito.scalatest.IdiomaticMockito` (or `org.mockito.scalatest.AsyncIdiomaticMockitoBase`)\n* with another test framework, mix in trait `org.mockito.IdiomaticMockito.WithExpect` or use its companion object\n\n\n## Notes for v1.4.0\nAs Specs2 support was added, now the library has been split in 3 different artifacts\n- **mockito-scala** being the core\n- **mockito-scala-scalatest** having specific classes that provide extra support for Scalatest\n- **mockito-scala-specs2** having specific classes that provide extra support for Specs2\n\nFrom now on, when using the idiomatic syntax, you'll get any non-matcher parameter automatically wrapped in an `eqTo`, \nthis means you shouldn't need to use it manually anymore. This is to provide a consistent behaviour when a custom `scalactic.Equality` has been defined for\na type.\n\nThe traits that provide the specifics for each test framework are \n- Scalatest: \n    - `org.mockito.scalatest.MockitoSugar` and `org.mockito.scalatest.IdiomaticMockito` for standard specs\n    - `org.mockito.scalatest.AsyncMockitoSugar`, `org.mockito.scalatest.AsyncIdiomaticMockito` for async specs\n- Specs2: `org.mockito.specs2.Mockito`\n\nThis version also includes a lot of under-the-hood fixes and improvements that provide an even better experience.\n\n## Note for v1.2.0\nAs now the varargs support works consistently across the whole lib, no no special syntax is needed, so if you were using `eqTo` with varargs, i.e. \n```scala\nverify(myObj).myMethod(eqTo(\"arg1\", \"arg2\"))\n```\nYou must change it now to\n```scala\nverify(myObj).myMethod(eqTo(\"arg1\"), eqTo(\"arg2\"))\n```\n\n## Migration Notes for version 1.0.0\n* `DefaultAnswer` was moved from `org.mockito.DefaultAnswer` to `org.mockito.stubbing.DefaultAnswer`\n* The recommended way to use the pre-defined `DefaultAnswer`s is via the object `org.mockito.DefaultAnswers`\n* `*` matcher is now defined in `org.mockito.ArgumentMatchersSugar`, mixin (or use the companion object) this trait whenever you wanna use it\n* `argumentCaptor[String]` was removed, replace by `ArgCaptor[T]` (`Captor[T]` was renamed to `ArgCaptor[T]` to add clarity), `ValCaptor[T]` was deprecated, (see [Improved ArgumentCaptor](#improved-argumentcaptor))\n* The usage of `org.mockito.Answer[T]` was removed from the API in favour of [Function Answers](#function-answers)\n* If you were using something like `doAnswer(_ =\u003e \u003csomething\u003e).when ...` to lazily compute a return value when the method is actually called you should now write it like `doAnswer(\u003csomething\u003e).when ...`, no need of passing a function as that argument is by-name\n* If you have chained return values like `when(myMock.foo) thenReturn \"a\" thenReturn \"b\" etc...` the syntax has changed a bit to `when(myMock.foo) thenReturn \"a\" andThen \"b\" etc...`\n* Idiomatic syntax has some changes to remove postFix operations and also allow support for mixing values and argument matchers [Mix-and-Match](#mix-and-match)\n```scala\naMock.bar shouldCallRealMethod                              =\u003e aMock.bar shouldCall realMethod\n\naMock wasCalled on bar                                      =\u003e aMock.bar was called\naMock wasCalled onlyOn bar                                  =\u003e aMock.bar wasCalled onlyHere\naMock was never called on bar                               =\u003e aMock.bar wasNever called\naMock wasCalled twiceOn bar                                 =\u003e aMock.bar wasCalled twice\naMock wasCalled sixTimesOn bar                              =\u003e aMock.bar wasCalled sixTimes\naMock was never called                                      =\u003e aMock.bar wasNever called\naMock was never called again                                =\u003e aMock.bar wasNever calledAgain\n\n\"mocked!\" willBe returned by aMock bar                      =\u003e \"mocked!\" willBe returned by aMock.bar\n\"mocked!\" willBe answered by aMock bar                      =\u003e \"mocked!\" willBe answered by aMock.bar\n((i: Int) =\u003e i * 10) willBe answered by aMock bar *         =\u003e ((i: Int) =\u003e i * 10) willBe answered by aMock.bar(*)\ntheRealMethod willBe called by aMock bar                    =\u003e theRealMethod willBe called by aMock.bar\nnew IllegalArgumentException willBe thrown by aMock bar     =\u003e new IllegalArgumentException willBe thrown by aMock.bar\n```\n* eqToVal matcher syntax was improved to look more natural [Value Class Matchers](#value-class-matchers) \nNOTE: `eqToVal` has been deprecated in v 1.0.2 as `eqTo` is now aware of value classes\n```scala\nverify(myObj).myMethod(eqToVal[MyValueClass](456))    =\u003e verify(myObj).myMethod(eqToVal(MyValueClass(456)))\nmyObj.myMethod(eqToVal[MyValueClass](456)) was called =\u003e myObj.myMethod(eqToVal(MyValueClass(456))) was called\n``` \n\n## Getting started\n\n## `org.mockito.MockitoSugar`\n\nFor a more detailed explanation read [this](https://medium.com/@bbonanno_83496/introduction-to-mockito-scala-ede30769cbda)\n\nThis trait wraps the API available on `org.mockito.Mockito` from the Java version, but it provides a more Scala-like syntax, mainly\n*   Fixes the compiler errors that sometimes occurred when using overloaded methods that use varargs like doReturn\n*   Eliminates the need to use `classOf[T]`\n*   Eliminates parenthesis when possible to make the test code more readable\n*   Adds `spyLambda[T]` to allow spying lambdas (they don't work with the standard spy as they are created as final classes by the compiler)\n*   Supports mocking inline mixins like `mock[MyClass with MyTrait]`\n*   Full support for by-name arguments (the full support was added in **1.4.0**, before it was partial).\n*   Adds support for working with default arguments\n\nThe companion object also extends the trait to allow the usage of the API without mixing-in the trait in case that's desired\n\n## `org.mockito.ArgumentMatchersSugar`\n\nFor a more detailed explanation read [this](https://medium.com/@bbonanno_83496/introduction-to-mockito-scala-part-2-ba1a79cc4c53)\n\nThis trait exposes all the existent `org.mockito.ArgumentMatchers` but again it gives them a more Scala-like syntax, mainly\n*   `eq` was renamed to `eqTo` to avoid clashing with the Scala `eq` operator for identity equality, `eq` also supports value classes out of the box and relies on `org.scalactic.Equality[T]` (see [Scalactic integration](#scalactic-integration)) \n*   `any[T]` works even when the type can't be inferred, removing the need of using the likes of `anyString`, `anyInt`, etc (see [Notes](#dead-code-warning))\n*   `any[T]` also supports value classes (in this case you MUST provide the type parameter)\n*   `isNull` and `isNotNull` are deprecated as using nulls in Scala is clear code smell\n*   Adds support for value classes via `anyVal[T]` and `eqToVal[T]()` **NOTE: both had been deprecated (use `any[T]` or `eqTo[T]` instead)**\n*   Adds `function0` to easily match for a function that returns a given value\n*   Adds `argMatching` that takes a partial function to match, i.e. `argMatching({ case Baz(_, \"pepe\") =\u003e })`\n\nAgain, the companion object also extends the trait to allow the usage of the API without mixing-in the trait in case that's desired\n\n### Value Class Matchers\n`eqTo` and `any[T]` support value classes since v1.0.2, so no special syntax is needed for them (but you MUST provide the type param for `any[T]` otherwise you'll get a NPE)\n\n## Improved ArgumentCaptor\n\nFor a more detailed explanation read [this](https://medium.com/@bbonanno_83496/introduction-to-mockito-scala-part-3-383c3b2ed55f)\n\nA new set of classes were added to make it easier, cleaner and more elegant to work with ArgumentCaptors, they also add \nsupport to capture value classes without any annoying syntax\n\nThere is a new `object org.mockito.captor.ArgCaptor[T]` that exposes a nicer API\n\nBefore:\n```scala\nval aMock  = mock[Foo]\nval captor = argumentCaptor[String]\n\naMock.stringArgument(\"it worked!\")\n\nverify(aMock).stringArgument(captor.capture())\n\ncaptor.getValue shouldBe \"it worked!\"\n```\nNow:\n```scala\nval aMock  = mock[Foo]\nval captor = ArgCaptor[String]\n\naMock.stringArgument(\"it worked!\")\n\nverify(aMock).stringArgument(captor)\n\ncaptor hasCaptured \"it worked!\"\n```\n\nAs you can see there is no need to call `capture()` nor `getValue` anymore (although they're still there if you need them as `capture` and `value` respectively)\n\nThe only scenario where you still have to call `capture` by hand is where the argument you want to capture is `Any` on the method signature, in that case the `implicit` conversion that automatically does the capture\n```scala\nimplicit def asCapture[T](c: Captor[T]): T = c.capture\n```\nis not called as the compiler finds no need to convert `Captor[Any]` into `Any`, as it is already an instance of `Any`, given that `Any` is the parent of every type in Scala. Because of that, the type does not need any transformation to be passed in.\n\nThere is another constructor `ValCaptor[T]` that should be used to capture value classes\n**NOTE: Since version 1.0.2 `ValCaptor[T]` has been deprecated as `ArgCaptor[T]` now support both, standard and value classes**\n\nBoth `ArgCaptor[T]` and `ValCaptor[T]` return an instance of `Captor[T]` so the API is the same for both\n\n## `org.mockito.MockitoScalaSession`\n\n### Basic usage\n\nThis is a wrapper around `org.mockito.MockitoSession`, it's main purpose (on top of having a Scala API) \nis to improve the search of mis-used mocks and unexpected invocations to reduce debugging effort when something doesn't work\n\nTo use it just wrap your code with it, e.g.\n```scala\nMockitoScalaSession().run {\n    val foo = mock[Foo]\n    when(foo.bar(\"pepe\")) thenReturn \"mocked\"\n    foo.bar(\"pepe\") shouldBe \"mocked\"\n}\n``` \nThat's it! that block of code will execute within a session which will take care of checking the use of the framework and,\nif the test fails, it will try to find out if the failure could be related to a mock being used incorrectly\n\n### Spies\n\nSpies for partial mocking of real objects\n\n```scala\n\"LinkedList size\" should \"return 100\" in {\n    val spiedList = spy(new util.LinkedList[String])\n    when(spiedList.size).thenReturn(100)\n    assert(spiedList.size === 100)\n  }\n```  \n\n### Leniency\n\nIf for some reason we want that a mock created within the scope of a session does not report failures for some or all methods we can specify leniency for it.\n\nFor the whole mock or spy to be ignored by the session, so basically a mock/spy that behaves as if the session didn't exist at all, we can make it lenient, e.g.\n```scala\nval aMock = mock[Foo](withSettings.lenient())\nval aSpy = spy(new Bar, lenient = true)\n```\n\nNow, if we just want to make one or more methods to be ignored by the session checks, we can make the method call lenient, this works as any other stubbing, so what it matters what matchers you define\n```scala\naMock.myMethod(*) isLenient()\n//or\nwhen(aMock.myMethod(*)).isLenient()\n``` \n\n## Strict Mode\n\nFor a more detailed explanation read [this](https://medium.com/@bbonanno_83496/introduction-to-mockito-scala-part-3-383c3b2ed55f)\n\nWhen using Scalatest and `org.mockito.scalatest.IdiomaticMockito` this is the default mode, you can override the strictness to be lenient by doing `val strictness: Strictness = Strictness.Lenient`\nThe implication under the hood is that every test will run inside a `MockitoScalaSession`, so **all** of them will run in **Strict Stub** mode.\n\n`org.mockito.scalatest.IdiomaticMockito` also includes `org.mockito.IdiomaticMockito` and `org.mockito.ArgumentMatchersSugar` so you have pretty much all\nthe mockito-scala API available in one go, i.e.\n\n```scala\nclass MyTest extends WordSpec with IdiomaticMockito\n```\n\nIMPORTANT: A session is defined on a per-test basis, and only the mocks created within the scope of the session are \nhandled by it, so if you have class level fields with mocks, i.e. mocks that are not created within the test, they will\nbe ignored by the session. If you use the same mocks in all or most of the tests and want to avoid the boilerplate while\nstill usfing the advantages of strict stubbing then declare those mocks in a setup trait.\n\n```scala\nclass MySpec extends WordSpec with Mockito {\n   trait Setup {\n      val myMock = mock[Sth] \n      myMock.someMethod returns \"something\" /*stub common to **all** tests -notice that if it's not used by all of them then the session will find it as an unused stubbing on those-*/\n   }\n\n   \"some feature\" should {\n       \"test whatever i want\" in new Setup {\n            myMock.someOtherMethod(*) returns None /*stub specific only to this test*/\n             ...test\n       }\n\n      \"test something else\" in new Setup {\n             myMock.someOtherMethod(\"expected value\") returns Some(\"result\")  /*stub specific only to this test*/\n             ...test\n       }\n   }\n}\n```\n\nThis will give you a fresh new instance of `myMock` for each test but at the same time you only declare the creation/common stubbing once.\n\n\n## `org.mockito.integrations.scalatest.ResetMocksAfterEachTest` | `org.mockito.integrations.scalatest.ResetMocksAfterEachAsyncTest`\n\nInspired by [this](https://stackoverflow.com/questions/51387234/is-there-a-per-test-non-specific-mock-reset-pattern-using-scalaplayspecmockito) StackOverflow question,\nmockito-scala provides these traits that helps to automatically reset any existent mock after each test is run\nThe trait has to be mixed **after** `org.mockito.MockitoSugar` in order to work, otherwise your test will not compile\nThe code shown in the StackOverflow question would look like this if using this mechanism\n\nNOTE: MockitoFixture and ResetMocksAfterEachTest are mutually exclusive, so don't expect them to work together\n\n```scala\nclass MyTest extends PlaySpec with MockitoSugar with ResetMocksAfterEachTest\n\nprivate val foo = mock[Foo]\n\noverride def fakeApplication(): Application = new GuiceApplicationBuilder().overrides(bind[Foo].toInstance(foo)).build\n```\n\nThe main advantage being we don't have to remember to reset each one of the mocks...\n\nIf for some reason we want to have a mock that is not reset automatically while using this trait, then it should be \ncreated via the companion object of `org.mockito.MockitoSugar` so is not tracked by this mechanism\n\n## Idiomatic Mockito\n\nBy adding the trait `org.mockito.IdiomaticMockito` you get access to some improved methods in the API\n\nThis API is heavily inspired on Scalatest's Matchers, so if you have used them, you'll find it very familiar\n\nHere we can see the old syntax on the left and the new one on the right\n\n```scala\ntrait Foo {\n  def bar: String\n  def bar(v: Int): Int\n}\n  \nval aMock = mock[Foo]  \n  \nwhen(aMock.bar) thenReturn \"mocked!\"                            \u003c=\u003e aMock.bar returns \"mocked!\"\nwhen(aMock.bar) thenReturn \"mocked!\" thenReturn \"mocked again!\" \u003c=\u003e aMock.bar returns \"mocked!\" andThen \"mocked again!\"\nwhen(aMock.bar) thenCallRealMethod()                            \u003c=\u003e aMock.bar shouldCall realMethod\nwhen(aMock.bar).thenThrow[IllegalArgumentException]             \u003c=\u003e aMock.bar.shouldThrow[IllegalArgumentException]\nwhen(aMock.bar) thenThrow new IllegalArgumentException          \u003c=\u003e aMock.bar throws new IllegalArgumentException\nwhen(aMock.bar) thenAnswer(_ =\u003e \"mocked!\")                      \u003c=\u003e aMock.bar answers \"mocked!\"\nwhen(aMock.bar(any)) thenAnswer(_.getArgument[Int](0) * 10)     \u003c=\u003e aMock.bar(*) answers ((i: Int) =\u003e i * 10)\n\ndoReturn(\"mocked!\").when(aMock).bar                             \u003c=\u003e \"mocked!\" willBe returned by aMock.bar\ndoAnswer(_ =\u003e \"mocked!\").when(aMock).bar                        \u003c=\u003e \"mocked!\" willBe answered by aMock.bar\ndoAnswer(_.getArgument[Int](0) * 10).when(aMock).bar(any)       \u003c=\u003e ((i: Int) =\u003e i * 10) willBe answered by aMock.bar(*)\ndoCallRealMethod.when(aMock).bar                                \u003c=\u003e theRealMethod willBe called by aMock.bar\ndoThrow(new IllegalArgumentException).when(aMock).bar           \u003c=\u003e new IllegalArgumentException willBe thrown by aMock.bar\n\ndoNothing().when(aMock).bar                                     \u003c=\u003e aMock.bar.doesNothing()\n  \nverifyZeroInteractions(aMock)                                   \u003c=\u003e aMock wasNever called\nverify(aMock).bar                                               \u003c=\u003e aMock.bar was called\nverify(aMock).bar(any)                                          \u003c=\u003e aMock.bar(*) was called\n\nverify(aMock, only).bar                                         \u003c=\u003e aMock.bar wasCalled onlyHere\nverify(aMock, never).bar                                        \u003c=\u003e aMock.bar wasNever called\n\nverify(aMock, times(2)).bar                                     \u003c=\u003e aMock.bar wasCalled twice\nverify(aMock, times(2)).bar                                     \u003c=\u003e aMock.bar wasCalled 2.times\n\nverify(aMock, times(6)).bar                                     \u003c=\u003e aMock.bar wasCalled sixTimes\nverify(aMock, times(6)).bar                                     \u003c=\u003e aMock.bar wasCalled 6.times\n\nverify(aMock, atLeast(6)).bar                                   \u003c=\u003e aMock.bar wasCalled atLeastSixTimes\nverify(aMock, atLeast(6)).bar                                   \u003c=\u003e aMock.bar wasCalled atLeast(sixTimes)\nverify(aMock, atLeast(6)).bar                                   \u003c=\u003e aMock.bar wasCalled atLeast(6.times)\n\nverify(aMock, atMost(6)).bar                                    \u003c=\u003e aMock.bar wasCalled atMostSixTimes\nverify(aMock, atMost(6)).bar                                    \u003c=\u003e aMock.bar wasCalled atMost(sixTimes)\nverify(aMock, atMost(6)).bar                                    \u003c=\u003e aMock.bar wasCalled atMost(6.times)\n\nverify(aMock, timeout(2000).atLeast(6)).bar                     \u003c=\u003e aMock.bar wasCalled (atLeastSixTimes within 2.seconds)\n\nverifyNoMoreInteractions(aMock)                                 \u003c=\u003e aMock wasNever calledAgain\n\nval order = inOrder(mock1, mock2)                               \u003c=\u003e InOrder(mock1, mock2) { implicit order =\u003e\norder.verify(mock2).someMethod()                                \u003c=\u003e   mock2.someMethod() was called\norder.verify(mock1).anotherMethod()                             \u003c=\u003e   mock1.anotherMethod() was called\n                                                                \u003c=\u003e }\n```\n\nAs you can see the new syntax reads a bit more natural, also notice you can use `*` instead of `any[T]`\n\nCheck the [tests](/scalatest/src/test/scala/user/org/mockito/scalatest/IdiomaticMockitoTest.scala) for more examples\n\nNOTE: When using the willBe syntax for stubbing, you can only stub one value to be returned, this is due to a limitation of the \ntype inference. If for some reason you have to do that (ideally all functions should be referentially transparent, so you wouldn't have to), you can \nuse the traditional syntax via the MockitoSugar companion object `MockitoSugar.doReturn(\"meh\").when(myMock).foo` or you\ncan use an answer that can decide what to return given whatever condition you need to simulate \n`{ (args) =\u003e if(\u003ccondition\u003e) something else somethingElse } willBe answered by myMock.foo`\n\n## Expect DSL\n\n**NOTE**: This DSL is experimental, may be unstable and may introduce incompatible changes between minor/patch versions\n\nThis DSL is available as a prefix alternative to `aMock.bar was called` DSL provided by [Idiomatic Mockito](#idiomatic-mockito)\nwhile keeping the original mocking and stubbing functionality. As you can see, with the new syntax you declare the\nintent of verification before describing the called pattern, so it reads even more naturally then before.\n\nIt is available via `org.mockito.IdiomaticMockito.WithExpect` mix-in (or its companion object). Mocking and stubbing works the same as before, and below are the examples of how verifications should be done.\n\n```scala\ntrait Foo {\n  def bar: String\n  def bar(v: Int): Int\n}\n  \nval aMock = mock[Foo]  \n  \nverifyZeroInteractions(aMock)                     \u003c=\u003e expect no calls on aMock\n\nverify(aMock).bar                                 \u003c=\u003e expect a call to aMock.bar\nverify(aMock).bar(any)                            \u003c=\u003e expect a call to aMock.bar(*)\n\nverify(aMock, only).bar                           \u003c=\u003e expect only call to aMock.bar\nverify(aMock, never).bar                          \u003c=\u003e expect no calls to aMock.bar\n\nverify(aMock, times(2)).bar                       \u003c=\u003e expect exactly 2.calls to aMock.bar\nverify(aMock, times(2)).bar                       \u003c=\u003e expect two calls to aMock.bar\nverify(aMock, times(2)).bar                       \u003c=\u003e expect (2.calls) to aMock.bar\n\nverify(aMock, times(6)).bar                       \u003c=\u003e expect exactly 6.calls to aMock.bar\nverify(aMock, times(6)).bar                       \u003c=\u003e expect six calls to aMock.bar\nverify(aMock, times(6)).bar                       \u003c=\u003e expect (6.calls) to aMock.bar\n\nverify(aMock, atLeast(6)).bar                     \u003c=\u003e expect atLeast 6.calls to aMock.bar\nverify(aMock, atLeast(6)).bar                     \u003c=\u003e expect atLeastSix calls to aMock.bar\n\nverify(aMock, atMost(6)).bar                      \u003c=\u003e expect atMost 6.calls to aMock.bar\nverify(aMock, atMost(6)).bar                      \u003c=\u003e expect atMostSix calls to aMock.bar\n\nverify(aMock, timeout(2000).times(2)).bar         \u003c=\u003e expect (2.calls within 2.seconds) to aMock.bar\nverify(aMock, timeout(2000).atLeast(6)).bar       \u003c=\u003e expect (atLeast(6.calls) within 2.seconds) to aMock.bar\n\nverifyNoMoreInteractions(aMock)                   \u003c=\u003e expect noMore calls on aMock\nverifyNoMoreInteractions(ignoreStubs(aMock))      \u003c=\u003e expect noMore calls(ignoringStubs) on aMock\n\nval order = inOrder(mock1, mock2)                 \u003c=\u003e InOrder(mock1, mock2) { implicit order =\u003e\norder.verify(mock2).someMethod()                  \u003c=\u003e   expect a call to mock2.someMethod()\norder.verify(mock1).anotherMethod()               \u003c=\u003e   expect a call to mock1.anotherMethod()\n                                                  \u003c=\u003e }\n```\n\n## Default Answers\nWe defined a new type `org.mockito.stubbing.DefaultAnswer` which is used to configure the default behaviour of a mock when a non-stubbed invocation\nis made on it.\n\nThe object `org.mockito.DefaultAnswers` contains each one of the provided ones\n\nAll the mocks created will use `ReturnsSmartNulls` by default, this is different to the Java version, which returns null for any non-primitive or non-final class.\n\nA \"Smart Null\", is nothing else than a mock of the type returned by the called method.\nThe main advantage of doing that is that if the code tries to call any method on this mock, instead of failing with a NPE the mock will\nthrow a different exception with a hint of the non-stubbed method that was called (including its params),\nthis should make much easier the task of finding and fixing non-stubbed calls\n\nMost of the Answers defined in `org.mockito.Answers` have it's counterpart in `org.mockito.DefaultAnswers`, and on top of that\nwe also provide `ReturnsEmptyValues` which will try its best to return an empty object for well known types, \ni.e. `Nil` for `List`, `None` for `Option` etc.\nThis DefaultAnswer is not part of the default behaviour as we think a SmartNull is better, to explain why, let's imagine we\nhave the following code.\n\n```scala\nclass UserRepository {\n  def find(id: Int): Option[User]\n}\nclass UserController(userRepository: UserRepository) {\n  def get(userId: Int): Option[Json] = userRepository.find(userId).map(_.toJson)\n}\n\nclass UserControllerTest extends WordSpec with IdiomaticMockito {\n\n  \"get\" should {\n     \"return the expected json\" in {\n        val repo = mock[UserRepository]\n        val testObj = new UserController(repo)\n\n        testObj.get(123) shouldBe Some(Json(....)) //overly simplified for clarity\n      }\n    }\n}\n```\n\nNow, in that example that test could fail in 3 different ways\n\n1) With the standard implementation of Mockito, the mock would return null and we would get a NullPointerException, which we all agree it's far from ideal, as it's hard to know where did it happen in non trivial code\n2) With the default/empty values, we would get a `None`, so the final result would be `None` and we will get an assertion error as `None` is not `Some(Json(....))`, but I'm not sure how much improvement over the NPE this would be, because in a non-trivial method we may have many dependencies returning `Option` and it could be hard to track down which one is returning `None` and why\n3) With a smart-null, we would return a `mock[Option]` and as soon as our code calls to `.map()` that mock would fail with an exception telling you what non-stubbed method was called and on which mock (in the example would say something you called the `find` method on some `mock of type UserRepository`) \n\nAnd that's why we use option 3 as default\n\nOf course you can override the default behaviour, for this you have 2 options\n\n1) If you wanna do it just for a particular mock, you can, at creation time do `mock[MyType](MyDefaultAnswer)`\n2) If you wanna do it for all the mocks in a test, you can define an `implicit`, i.e. `implicit val defaultAnswer: DefaultAnswer = MyDefaultAnswer`\n\nDefaultAnswers are also composable, so for example if you wanted empty values first and then smart nulls you could do `implicit val defaultAnswer: DefaultAnswer = ReturnsEmptyValues orElse ReturnsSmartNulls`\n\n## Function Answers\n`org.mockito.Answer[T]` can be a bit boilerplate-ish, \nto simplify the usage for both versions is that we replaced it by standard scala functions, so instead of \n```scala\nwhen(myMock.foo(\"bar\", 42)) thenAnswer new Answer[String] {\n  override def answer(invocation: InvocationOnMock): String = i.getArgument[String](0) + i.getArgument[Int](1)\n}\n```\nWe can now write: \n```scala\nwhen(myMock.foo(\"bar\", 42)) thenAnswer ((i: InvocationOnMock) =\u003e i.getArgument[String](0) + i.getArgument[Int](1))\n```\n\nI guess we all agree that's much better, but, it gets even better, we can now pass standard functions that work over the arguments, we only need to take care to pass the right types, so the previous example would become\n```scala\nwhen(myMock.foo(\"bar\", 42)) thenAnswer ((v1: String, v2: Int) =\u003e v1 + v2)\n```\n\n\n## Mix and match\n\n### Mixing normal values with argument matchers\n\nSince mockito 1.0.0, when you use the idiomatic syntax, you are not forced anymore to use argument matchers for all your parameters as soon as you use one, \nso stuff like this is now valid (not a comprehensive list, just a bunch of examples)\n```scala\ntrait Foo {\n  def bar(v: Int, v2: Int, v3: Int = 42): Int\n}\n  \nval aMock = mock[Foo]  \n  \naMock.bar(1,2) returns \"mocked!\"\naMock.bar(1,*) returns \"mocked!\"\naMock.bar(*,*) returns \"mocked!\"\naMock.bar(*,*, 3) returns \"mocked!\"\n\n\"mocked!\" willBe returned by aMock.bar(1,2)\n\"mocked!\" willBe returned by aMock.bar(1,*)\n\"mocked!\" willBe returned by aMock.bar(*,*)\n\"mocked!\" willBe returned by aMock.bar(*,*, 3)\n\naMock.bar(1,2) was called\naMock.bar(1,*) was called\naMock.bar(*,*) was called\naMock.bar(*,*, 3) was called\n```\nSo far there is one caveat, if you have a curried function that has default arguments on the second (or any following) argument list, the macro that achieves this will fail, \nthis is related to how the default method is created by the compiler.\nI'll write a more detailed explanation at some point, but there are more than one reason why this is probably never going to work\nThe workaround is quite easy though, just provide a value (or a matcher) for that argument and you are good to go.\n\n\n## Numeric matchers\n\nA new set of matchers to deal with number comparison were introduced (see [Scalactic tolerance](#tolerance) for approximation),\nthe syntax is slightly different to make them more readable, so now we can write stuff like (notice the 'n')\n```scala\naMock.method(5)\n\naMock.method(n \u003e 4.99) was called\naMock.method(n \u003e= 5) was called\naMock.method(n \u003c 5.1) was called\naMock.method(n \u003c= 5) was called\n```  \n\n## Varargs\n\nMost matchers that makes sense to, work with varargs out of the box, the only thing to notice is that if you are passing more than one value \nand want to use `eqTo` then you should pass all of them to the same instance of `eqTo` e.g.\n\n```scala\ntrait FooWithVarArgAndSecondParameterList {\n  def bar(bells: String*)(cheese: String): String\n}\n\nfoo.bar(eqTo(\"cow\", \"blue\"))(*) was called //RIGHT\nfoo.bar(eqTo(\"cow\"), eqTo(\"blue\"))(*) was called //WRONG - it will complain it was expecting 2 matchers but got 3\n```\n\n## Scalactic integration\n\n### Equality\n\nSince version 1.0.0 the `eqTo` matcher uses the `org.scalactic.Equality[T]` typeclass, this doesn't change anything on the API\nand existent code will not be affected, but it allows you to override the standard equality of any class by just providing an\nimplicit `Equality` in scope, e.g.\n```scala\nimplicit val fooEquality: Equality[Foo] = new Equality[Foo] { \n  override def areEqual(a: Foo, b: Any): Boolean = /*Do the comparison as you like*/ \n}\n\naMock.method(eqTo(/*some foo instance/*))\n```\n\n\n### Tolerance\n\nYou can use Scalactic's `Spread[T]` to deal with the precision errors in floating points, so you can now  write stuff like\n```scala\naMock.method(4.999)\n\naMock.method(n =~ 5.0 +- 0.001) was called\n```\n\n### Prettifier\n\nAn instance of `org.scalactic.Prettifier` is implicitly pulled by the `EqTo` matcher to provide a nicer (and customisable) printing of \nyour types when an verification fails. `EqTo` is also used internally by `Mockito` to print the arguments of every invocation, so you'll \nget a consistent printing for both the expectation and the actual call.\n\nIf you want to customise the print of any type you just need to declare your `Prettifier` in the implicit scope like\n\n```scala\n  implicit val prettifier: Prettifier = new Prettifier {\n    override def apply(o: Any): String = o match {\n      case Baz2(_, s) =\u003e s\"PrettifiedBaz($s)\"\n      case other      =\u003e Prettifier.default(other)\n    }\n  }\n```\n\n## Cats integration\nBy adding the module `mockito-scala-cats` 2 new traits are available, `IdiomaticMockitoCats` and `MockitoCats` which are meant to be mixed-in in\ntests that use `IdiomaticMockito` and `MockitoSugar` respectively.\nPlease look at the [tests](/cats/src/test) for more detailed examples\n\n### MockitoCats\nThis traits adds `whenF()` which allows stubbing methods that return an Applicative (or an ApplicativeError) to be stubbed by just providing \nthe content of said applicative (or the error).\nSo for \n```scala\ntrait Foo {\n    def returnsOption[T](v: T): Option[T]\n    def returnsMT[M[_], T](v: T): M[T]\n}\n// We can now write \nval aMock = mock[Foo]\nwhenF(aMock.returnsOption(*)) thenReturn \"mocked!\"\nwhenF(aMock.returnsMT[Future, String](*)) thenReturn \"mocked!\"\n// Rather than\nwhen(aMock.returnsOption(*)) thenReturn Some(\"mocked!\")\nwhen(aMock.returnsMT[Future, String](*)) thenReturn Future.successful(\"mocked!\")\n\n//We could also do stubbings in a single line if that's all we need from the mock\nval inlineMock: Foo = whenF(mock[Foo].returnsOption(*)) thenReturn \"mocked!\"\n\n// For errors we can do\ntype ErrorOr[A] = Either[Error, A]\nval failingMock: Foo = whenF(mock[Foo].returnsMT[ErrorOr, MyClass](*)) thenFailWith Error(\"error\")\n//Rather than\nval failingMock: Foo = when(mock[Foo].returnsMT[ErrorOr, MyClass](*)) thenReturn Left(Error(\"error\"))\n```\n\nThe trait also provides and implicit conversion from `cats.Eq` to `scalactic.Equality` so if you have an implicit `cats.Eq` instance in scope,\nit will be automatically used by the `eqTo` matcher.\n\n### IdiomaticMockitoCats\n\nSimilar to `MockitoCats` but for the idiomatic syntax (including the conversion from `cats.Eq` to `scalactic.Equality`), so the code would look like\n\n```scala\ntrait Foo {\n    def returnsOption[T](v: T): Option[T]\n    def returnsMT[M[_], T](v: T): M[T]\n}\n// We can now write \nval aMock = mock[Foo]\naMock.returnsOption(*) returnsF \"mocked!\"\naMock.returnsMT[Future, String](*) returnsF \"mocked!\"\n// Rather than\naMock.returnsOption(*) returns Some(\"mocked!\")\naMock.returnsMT[Future, String](*) returns Future.successful(\"mocked!\")\n\n//We could also do stubbings in a single line if that's all we need from the mock\nval inlineMock: Foo = mock[Foo].returnsOption(*) returnsF \"mocked!\"\n\n// For errors we can do\ntype ErrorOr[A] = Either[Error, A]\nval failingMock: Foo = mock[Foo].returnsMT[ErrorOr, MyClass](*) raises Error(\"error\")\n//Rather than\nval failingMock: Foo = mock[Foo].returnsMT[ErrorOr, MyClass](*) returns Left(Error(\"error\"))\n```\n\n## Scalaz integration\nBy adding the module `mockito-scala-scalaz` 2 new traits are available, `IdiomaticMockitoScalaz` and `MockitoScalaz` which are meant to be mixed-in in\ntests that use `IdiomaticMockito` and `MockitoSugar` respectively.\nPlease look at the [tests](/scalaz/src/test) for more detailed examples\n\n### MockitoScalaz\nThis traits adds `whenF()` which allows stubbing methods that return an Applicative (or an ApplicativeError) to be stubbed by just providing \nthe content of said applicative (or the error).\nSo for \n```scala\ntrait Foo {\n    def returnsOption[T](v: T): Option[T]\n    def returnsMT[M[_], T](v: T): M[T]\n}\n// We can now write \nval aMock = mock[Foo]\nwhenF(aMock.returnsOption(*)) thenReturn \"mocked!\"\nwhenF(aMock.returnsMT[Future, String](*)) thenReturn \"mocked!\"\n// Rather than\nwhen(aMock.returnsOption(*)) thenReturn Some(\"mocked!\")\nwhen(aMock.returnsMT[Future, String](*)) thenReturn Future.successful(\"mocked!\")\n\n//We could also do stubbings in a single line if that's all we need from the mock\nval inlineMock: Foo = whenF(mock[Foo].returnsOption(*)) thenReturn \"mocked!\"\n\n// For errors we can do\ntype ErrorOr[A] = Either[Error, A]\nval failingMock: Foo = whenF(mock[Foo].returnsMT[ErrorOr, MyClass](*)) thenFailWith Error(\"error\")\n//Rather than\nval failingMock: Foo = when(mock[Foo].returnsMT[ErrorOr, MyClass](*)) thenReturn Left(Error(\"error\"))\n```\n\nThe trait also provides and implicit conversion from `scalaz.Equal` to `scalactic.Equality` so if you have an implicit `scalaz.Equal` instance in scope,\nit will be automatically used by the `eqTo` matcher.\n\n### IdiomaticMockitoScalaz\n\nSimilar to `MockitoScalaz` but for the idiomatic syntax (including the conversion from `scalaz.Equal` to `scalactic.Equality`), so the code would look like\n\n```scala\ntrait Foo {\n    def returnsOption[T](v: T): Option[T]\n    def returnsMT[M[_], T](v: T): M[T]\n}\n// We can now write \nval aMock = mock[Foo]\naMock.returnsOption(*) returnsF \"mocked!\"\naMock.returnsMT[Future, String](*) returnsF \"mocked!\"\n// Rather than\naMock.returnsOption(*) returns Some(\"mocked!\")\naMock.returnsMT[Future, String](*) returns Future.successful(\"mocked!\")\n\n//We could also do stubbings in a single line if that's all we need from the mock\nval inlineMock: Foo = mock[Foo].returnsOption(*) returnsF \"mocked!\"\n\n// For errors we can do\ntype ErrorOr[A] = Either[Error, A]\nval failingMock: Foo = mock[Foo].returnsMT[ErrorOr, MyClass](*) raises Error(\"error\")\n//Rather than\nval failingMock: Foo = mock[Foo].returnsMT[ErrorOr, MyClass](*) returns Left(Error(\"error\"))\n```\n\n## Mocking Scala `object`\n\nSince version 1.16.0 it is possible to mock `object` methods, given that such definitions are global, the way to mock them is slightly different in order to ensure we restore the real implementation of the object after we are done\n\nTo enable `withObjectMocked` feature, it is mandatory to create the file `src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker` containing a single line:\n \n```scala\n mock-maker-inline\n```\n\nExample:\n\n```scala\nobject FooObject {\n  def simpleMethod: String = \"not mocked!\"\n}\n\n\"mock\" should {\n    \"stub an object method\" in {\n      FooObject.simpleMethod shouldBe \"not mocked!\"\n\n      withObjectMocked[FooObject.type] {\n        FooObject.simpleMethod returns \"mocked!\"\n        //or\n        when(FooObject.simpleMethod) thenReturn \"mocked!\"\n\n        FooObject.simpleMethod shouldBe \"mocked!\"\n      }\n\n      FooObject.simpleMethod shouldBe \"not mocked!\"\n    }\n}\n```\n\nAs you can see, the effect of the mocking is only available inside the code block passed to `withObjectMocked`, when such block ends the behavior of the object is restored to its original implementation\n\n\n## Notes\n\n### Dead code warning\nif you have enabled the compiler flag `-Ywarn-dead-code`, you will see the warning _dead code following this construct_ \nwhen using the `any` or `*` matchers , this is because in some cases the compiler can not infer the return type of those \nmatchers and it will default to `Nothing`, and this compiler warning is shown every time `Nothing` is found on our code.\nThis will **NOT** affect the behaviour of Mockito nor your test in any way, so it can be ignored, but in case you \nwant to get rid of it then you have 2 options:\n\n1) If you are not too fuss about dead code warnings in test code, you can add `scalacOptions in Test -= \"-Ywarn-dead-code\"` to \nyour build.sbt and that warning will be ignored for your tests **only**\n2) If you wanna keep the warning enabled for potentially real dead code statements, but get rid of the warnings related to the \nmatchers usage then you have to explicitly provide the type for the matcher, thus `any` would become `any[MyType]` and\n`*` would become `*[MyType]` (you can also use `anyShort`, `anyInt`, etc for the primitive types)\n \n## Authors\n\n* **Bruno Bonanno** - *Initial work* - [bbonanno](https://github.com/bbonanno)\n\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmockito%2Fmockito-scala","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmockito%2Fmockito-scala","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmockito%2Fmockito-scala/lists"}