Git Product home page Git Product logo

scalamock's Introduction

ScalaMock

Native Scala mocking.

Official website: scalamock.org

Examples

Expectations-First Style

test("drawline interaction with turtle") {
  // Create mock Turtle object
  val m = mock[Turtle]
  
  // Set expectations
  (m.setPosition _).expects(10.0, 10.0)
  (m.forward _).expects(5.0)
  (m.getPosition _).expects().returning(15.0, 10.0)

  // Exercise System Under Test
  drawLine(m, (10.0, 10.0), (15.0, 10.0))
}

Record-then-Verify (Mockito) Style

test("drawline interaction with turtle") {
  // Create stub Turtle
  val m = stub[Turtle]
  
  // Setup return values
  (m.getPosition _).when().returns(15.0, 10.0)

  // Exercise System Under Test
  drawLine(m, (10.0, 10.0), (15.0, 10.0))

  // Verify expectations met
  (m.setPosition _).verify(10.0, 10.0)
  (m.forward _).verify(5.0)
}

A more complete example is on our Quickstart page.

Features

  • Fully typesafe
  • Full support for Scala features such as:
    • Polymorphic (type parameterised) methods
    • Operators (methods with symbolic names)
    • Overloaded methods
    • Type constraints
  • ScalaTest and Specs2 integration
  • Mock and Stub support
  • Macro Mocks and JVM Proxy Mocks
  • Scala.js support
  • built for Scala 2.12, 2.13, 3
  • Scala 2.10 support was included up to ScalaMock 4.2.0
  • Scala 2.11 support was included up to ScalaMock 5.2.0

Using ScalaMock

Artefacts are published to Maven Central and Sonatype OSS.

For ScalaTest, to use ScalaMock in your Tests, add the following to your build.sbt:

libraryDependencies += Seq("org.scalamock" %% "scalamock" % "5.2.0" % Test,
    "org.scalatest" %% "scalatest" % "3.2.0" % Test)

Scala 3 Migration Notes

  1. Type should be specified for methods with by-name parameters
trait TestTrait:
  def byNameParam(x: => Int): String

val t = mock[TestTrait]

// this one no longer compiles
(t.byNameParam _).expects(*).returns("")

// this one should be used instead
(t.byNameParam(_: Int)).expects(*).returns("")
  • Not initialized vars are not supported anymore, use scala.compiletime.uninitialized instead
  • Vars are not mockable anymore
trait X:
  var y: Int  // No longer compiles
  
  var y: Int = scala.compile.uninitialized // Should be used instead

Mocking of non-abstract java classes is not available without workaround

public class JavaClass {
    public int simpleMethod(String b) { return 4; }
}
val m = mock[JavaClass] // No longer compiles

class JavaClassExtended extends JavaClass

val mm = mock[JavaClassExtended] // should be used instead

Documentation

For usage in Maven or Gradle, integration with Specs2, and more example examples see the User Guide

Acknowledgements

YourKit is kindly supporting open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit's leading software products: YourKit Java Profiler and YourKit .NET Profiler.

Many thanks to Jetbrains for providing us with an OSS licence for their fine development tools such as IntelliJ IDEA.

Also, thanks to https://github.com/fthomas/scala-steward for helping to keep our dependencies updated automatically.

scalamock's People

Contributors

backuitist avatar barkhorn avatar by-dam avatar cb372 avatar cheeseng avatar ddworak avatar dodnert avatar dwickern avatar goshacodes avatar hhimanshu avatar hydra avatar lj-ditrapani avatar luiz290788 avatar maqdev avatar mkasberg avatar nimatrueway avatar paulbutcher avatar pawel-wiejacha avatar philippus avatar povder avatar scala-steward avatar sethtisue avatar sullis avatar valericus avatar wangxhere avatar xuwei-k avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scalamock's Issues

3.1 stable?

Was wondering if 3.1 will be released soon and moved into Maven Central? Unfortunately the Sonatype Snapshots repo has been unstable lately and is causing problems with builds.

ScalaMock and Futures

Hi! I am trying to use stub functions with Futures. I have written following test case:

"ScalaMock stub" must {
  "pass this test" in {
    val s = stubFunction[Int]
    s.when().returns(1)
    Await.result(Future { s() }, 10 seconds)
    s.verify().once()
  }
  "pass this test once more" in {
    val s = stubFunction[Int]
    s.when().returns(1)
    Await.result(Future { s() }, 10 seconds)
    s.verify().once()
  }
}

The first test passes, but the second fails with the following message:

verify should appear after all code under test has been exercised
java.lang.RuntimeException: verify should appear after all code under test has been exercised
    at scala.sys.package$.error(package.scala:27)
    at org.scalamock.Verify$class.handle(CallHandler.scala:120)
    at org.scalamock.StubFunction0$$anon$1.handle(StubFunction.scala:29)
    at org.scalamock.StubFunction0$$anon$1.handle(StubFunction.scala:29)
    at org.scalamock.UnorderedHandlers$$anonfun$handle$1.apply(UnorderedHandlers.scala:27)
    at org.scalamock.UnorderedHandlers$$anonfun$handle$1.apply(UnorderedHandlers.scala:26)
    at scala.collection.immutable.List.foreach(List.scala:309)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
    at scala.collection.mutable.ListBuffer.foreach(ListBuffer.scala:45)
    at org.scalamock.UnorderedHandlers.handle(UnorderedHandlers.scala:26)
    at org.scalamock.MockFactoryBase$class.handle(MockFactoryBase.scala:120)
...

Is it a bug or am I doing something wrong?

Can't mock classes in the scala.* or java.* packages

I first noticed this when trying to mock a DatagramSocket, but reproduced a minimal example by just using Object. You can see the change as a single commit on my fork of the example scalamock project here. (By the way, I'm using sbt 0.11.2. Not sure if that matters.)

Running generate-mocks seems to work, but creates invalid code that doesn't compile when you try to run test:

> test
[info] Compiling 5 Scala sources and 2 Java sources to /home/caleb/test/ScalaMockExample/target/scala-2.9.1/mock-classes...
[error] /home/caleb/test/ScalaMockExample/target/scala-2.9.1/src_managed/mock/scala/java/net/DatagramSocket$JavaFeatures.java:8: `]' expected but identifier found.
[error]   public static java.lang.Class[_] implClass = (java.lang.Class[_])org.scalamock.ReflectionUtilities.getObjectField(clazz, "implClass");
[error]
...

Apologies if this is covered somewhere in the docs. I didn't read anything specifically about mocking pure Java classes, but I was hoping that would work as my code generally has at least a few java standard library dependencies that would be nice to mock.

Thanks!

Mock (lazy) vals

I want to mock classes having vals and lazy vals. When I try this:

import org.scalamock.scalatest.MockFactory
import org.scalatest.FunSpec

class LazyValTest extends FunSpec with MockFactory {

  describe("A mocked instance should have its lazy vals mockable.") {

    class ClassToMock {
      lazy val mockMe = 5 * 3
      val mockMeToo = 5

      def getLazyVal = mockMe
      def getNormalVal = mockMeToo
    }

    val mockedInstance = stub[ClassToMock]

    (mockedInstance.getNormalVal _) expects () returning 3

    (mockedInstance.getLazyVal _) expects () returning 5

    (mockedInstance._mockMe _) expects () returning 5

    (mockedInstance.mockMeToo _) expects () returning 3
  }

}

I get the following compile error:
_ must follow method; cannot follow mockedInstance.mockMe.type

Am I doing this wrong or is this an error?

Thanks in advance for your help.

How do you mock a val/no-arg def?

Hey. This should go to mailing list, but I couldn't find a link to one in documentation, so I guess this can be marked as documentation bug.

How does one mock following:

class Foo {
  def get = 3
}

I've tried:

val m = mock[Foo]
(m.get).expects().returning(10)
(m.get _).expects().returning(10)

But this does not seem to work. So, how does one do it?

Deprecation warning caused by upgrade to 2.10.3

[warn] /Users/c-birchall/projects/ScalaMock/core/src/main/scala/org/scalamock/Mock.scala:209: method TypeDef in trait Trees is deprecated: Use the canonical TypeDef constructor to create an abstract type or type parameter and then initialize its position and symbol manually
[warn]           m.typeParams map TypeDef _,
[warn]                            ^
[warn] one warning found

The deprecated factory method (reflect.api.Trees#TypeDef(Symbol)) relies on a lot of stuff in reflect.internal.Symbol, and I don't see how to easily recreate that using only the public API.

Expectations defined outside of scope of mock object creation cause NPE's

import org.scalatest.{FunSuite, OneInstancePerTest}
import org.scalamock.scalatest.MockFactory

trait Foo {
  def foo (i: Int): Int
}

class JUnitStyleFixtureTest extends FunSuite with OneInstancePerTest with MockFactory {
  val fix = mock[Foo]

  test("this shouldn't cause an NPE") {
    (fix.foo _) expects (1)
    fix.foo(1)
  }
}
> test-only JUnitStyleFixtureTest
[info] JUnitStyleFixtureTest:
[info] - this shouldn't cause an NPE *** FAILED ***
[info]   java.lang.NullPointerException:
[info]   at org.scalamock.FakeFunction.handle(FakeFunction.scala:37)
[info]   at org.scalamock.FakeFunction1.apply(FakeFunction.scala:53)
[info]   at JUnitStyleFixtureTest$$anon$1.foo(JUnitStyleFixtureTest.scala:9)
[info]   at JUnitStyleFixtureTest$$anonfun$1.apply$mcV$sp(JUnitStyleFixtureTest.scala:13)
...

The problem looks to be that when FakeFunction is instantiated, its MockFactoryBase hasn't yet initialized some of its expectation-related state.

It seems like there needs to be a way for resetExpectations to carry through to all mocks created by a given MockFactoryBase.

Some failed attempts to fix:

  • Switching from val to lazy val here broke ConcurrencyTest
  • Adding initialValue to ThreadLocal here replaced the NPE with an expectations exception

ScalaMock does not work with ScalaTest's TestNG/JUnit Support Traits

ScalaMock currently does not integrate with ScalaTest's TestNGSuite or JUnitSuite traits. I am using ScalaMock_2.9.1-2.2 and ScalaTest_2.9.1-1.6.1.

Here's a sample test, using TestNGSuite:

import org.scalamock.ProxyMockFactory
import org.scalamock.scalatest.MockFactory
import org.scalatest.testng.TestNGSuite

class ScalaMockTestNG extends TestNGSuite with MockFactory with ProxyMockFactory

The following error is produced:

error: overriding method runTests in trait TestNGSuite of type (testName: Option[String], reporter: org.scalatest.Reporter, stopper: org.scalatest.Stopper, filter: org.scalatest.Filter, configMap: Map[String,Any], distributor: Option[org.scalatest.Distributor], tracker: org.scalatest.Tracker)Unit;
 method runTests in trait MockFactory of type (testName: Option[String], reporter: org.scalatest.Reporter, stopper: org.scalatest.Stopper, filter: org.scalatest.Filter, configMap: Map[String,Any], distributor: Option[org.scalatest.Distributor], tracker: org.scalatest.Tracker)Unit cannot override final member;
 other members with override errors are: runTest
class ScalaMockTestNG extends TestNGSuite with MockFactory with ProxyMockFactory
      ^
one error found

It appears that ScalaTest's TestNGSuite does not use the runTest method.

From the ScalaTest TestNGSuite source (http://code.google.com/p/scalatest/source/browse/tags/release-1.6.1/src/main/scala/org/scalatest/testng/TestNGSuite.scala ):

 The main purpose of this method implementation is to render a compiler error an attempt
 to mix in a trait that overrides <code>runTests</code>. Because this
 trait does not actually use <code>runTests</code>, the attempt to mix
 in behavior would very likely not work.

specs2 support

What happened to scalamock-specs2-support? The code for it is still in the repository.

Compilation error using MockFactory with ScalaTest 2.0.M6-SNAP21

I've tried the preview release of ScalaTest and it breaks in the withFixture method.

[error] D:\app\ACalculatorTest.scala:10: overriding method
thFixture in trait Suite of type (test: ACalculatorTest.this.NoArgTest)org.scalatest.Outcome;
[error] method withFixture in trait MockFactory of type (test: ACalculatorTest.this.NoArgTest)Unit has incompatible type
[error] class ACalculatorTest extends FunSpec with MockFactory with TieringFixture {
[error] ^

class ACalculatorTest extends FunSpec with MockFactory {

val aMock = mockFunction[JDouble, JDouble]
... }

This code compiles with 2.0.M5

mocking default arguments

when setting expectations for a method with default arguments, the compiler will report ambiguity in the call.

I had to explicitly set the argument in the test in order for it to complete the expectation.

then, the test would fail with:

once (never called - UNSATISFIED)

So i had to resort to specifying the default value for that parameter in the call. This defeats the purpose of the default argument.

generated mocks for objects with nested classes do not compile

Compiling the GeneratedMockFactory created when mocking the object below causes compilation errors.

package com.test
object ObjectWithNestedClass {

 class NestedClass {
   def meth = "nested class method"
 }

}

then the GeneratedMockFactory will define the implicit conversion:

implicit def toMock$27(m: com.test.ObjectWithNestedTypes#NestedClass) = m.asInstanceOf[com.test.Mock$$ObjectWithNestedTypes#Mock$NestedClass]

the supplied argument should be of type com.test.ObjectWithNestedTypes.NestedClass

Overloaded methods with parameters passed by-name cannot be mocked

I m using ScalaMock to create a stub of the FileSystemManager interface but keep encountering error during compile time because ScalaMock 3 is unable to resolve the overloaded method FileObject resolveFile(String name, FileSystemOptions fileSystemOptions). Here is the test demonstrating this problem:

import org.scalatest.FunSuite
import org.scalamock.scalatest.MockFactory
import org.apache.commons.vfs2._

class OverloadedMethodSuite extends FunSuite with MockFactory {

    test("stub an overloaded method") {
        val s = stub[FileSystemManager]

        // ScalaMock 3 is failing at the next line
        (s.resolveFile(_: String, _: FileSystemOptions)).when("test", null).returns(null)

        assert(s.resolveFile("test", null) == null)
    }
}

The error message is as follows:

: Unable to resolve overloaded method resolveFile
[info] (m.resolveFile(_: String, _: FileSystemOptions)).when("test", null).returns(null)

Incorrect sbt dependency snippets on scalamock.org

The http://www.scalamock.org site reads:

libraryDependencies +=
  "org.scalamock" % "scalamock-scalatest-support-2.10.0-RC1" % "3.0.M5"

and with Specs2:

libraryDependencies +=
  "org.scalamock" % "scalamock-specs2-support-2.10.0-RC1" % "3.0.M5"

But there should be an underscore, not a hyphen, between "support" and "2.10.0", and it should be "3.0-M5" not "3.0.M5". (Or same for a later RC of Scala 2.10.)

Type mismatch error from scalac when trying to mock a certain trait

On Scala 2.10.0, trying to mock[A] in Scalatest using ScalaMock with:

trait A {
  def getOrElse[B1 >: OBJ](key: ID, default: => B1): B1 = get(key) match {
    case Some(v) => v
    case None => default
  }
}

yields:

[error] /path/to/mock-caller.scala:19: type mismatch;
[error]  found   : B1(in method getOrElse)
[error]  required: (some other)B1(in method getOrElse)
[error]     val mockA = mock[A]

I can dig into this but wanted to see if anyone had suggestions.

Support for matchers in ScalaMock

Perhaps I'm missing something, but it appears that there's no matcher support in ScalaMock like there is in Mockito and jMock.

If there's indeed no support for matchers, I'd love to see it in the near future - preferably providing Hamcrest support.

Fail fast for excessive mock calls

I'm not sure if this is the forum you prefer - but I created an interesting problem for myself using scalamock - I was testing something in a separate thread that needed to have a particular condition in order to stop doing its business (and in the case of the test, to stop call my mock function). So being the brilliant developer I am - I chose not to set that stop condition and moved on to the next test. The tests would intermittently take a long time to run, would use up all available memory and would occasionally hang.

I whipped out visualvm to troubleshoot - and saw a bunch of "Call" objects (millions) - and realized probably in the CallLog class, it keeps references to every call made.

I know this was my mistake - but a handy feature would be a quick blow up on this after some arbitrary threshold - maybe a threshold based on the available heap or something - or I don't know - even just an arbitrary number of calls.

I may offer a pull request if I can work something out quickly.....and you may not even want this, but I thought I'd post it here.

Can't mock Traversable (or any other collection)

object TestScalaMock extends FeatureSpec with MockFactory {
  val mockTraversable = mock[Traversable[String]]
}

gives compile-time error:

[error] /home/alex/code/test-scala-mock/src/test/scala/test/TestScalaMock.scala:25: type mismatch;
[error]  found   : Array[B(in method copyToArray)]
[error]  required: Array[(some other)B(in method copyToArray)]
[error]   val mockTraversable = mock[Traversable[String]]

This is with Scala 2.10.0, ScalaTest 1.9.1, ScalaMock 3.0.1, sbt 0.12.0, no compiler options (except -depracated and -unchecked). Other collections give various errors, seems like not all of the methods are being mocked correctly.

Some additional ones I tried:

[error]  found   : scala.math.Ordering[B(in method sorted)]
[error]  required: scala.math.Ordering[(some other)B(in method sorted)]
[error]   val mockSeq = mock[Seq[String]]
[error]  found   : scala.collection.immutable.Set[(some other)B(in method toSet)]
[error]  required: scala.collection.immutable.Set[B(in method toSet)]
[error]   val mockSet = mock[Set[String]]
[error]  found   : B1(in method withDefaultValue)
[error]  required: (some other)B1(in method withDefaultValue)
[error]   val mockMap = mock[Map[String, String]]

Can't compile mocks with methods that has by name parameters

The generated mock for the S object in Lift does not compile since it has methods with by name parameters. Below is a simpler example (than the entire S object) that illustrates the issue.

object Foo {
  def foo(s:String)(t:String):List[String] = List(s,t)

  def bar(id: String)(f: โ‡’ List[(NodeSeq, Option[String])]): List[NodeSeq] = null
}

Not sure if this is the only remaining issue with mocking the S object in lift. Will give it a swift try!

ScalaMock 3.0 problems with polymorphic types

This is with scala 2.10.0 and java 1.6.0_37 on OS X. It looks like java generics aren't cooperating?

class MockingTest extends FunSuite with MockFactory {

  test("mock[Connection] won't compile") {
    val conn = mock[java.sql.Connection]
    // overloaded method value apply with alternatives:
    // [error]   (v1: Class[X(in value mock$unwrap$0)])Object <and>
    // [error]   (v1: Class[(some other)X(in value mock$unwrap$0)])Object
  }

  test("mock[Wrapper] won't compile") {
    val wrap = mock[java.sql.Wrapper]
    // same error
  }

  trait ExtendedWrapper extends java.sql.Wrapper
  test("mock[ExtendedWrapper] won't compile") {
    val wrap = mock[ExtendedWrapper]
    // same error
  }

  trait OverriddenWrapper extends java.sql.Wrapper {
    override def unwrap[T](clazz: Class[T]): T
  }
  test("compiles fine") {
    val wrap = mock[OverriddenWrapper]
  }

}

trait with val foo: A => B cannot be mocked?

I'm using scala 2.10-RC5, scalamock 3.0-M7 and sbt 0.12

dependencies for the build script:
"org.scalatest" %% "scalatest" % "2.0.M5-B1" % "test" cross CrossVersion.full,
"org.scalamock" %% "scalamock-scalatest-support" % "3.0-M7" % "test" cross CrossVersion.full,

import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import org.scalamock.scalatest.MockFactory

class Test_Mock extends FlatSpec with ShouldMatchers with MockFactory {
type Position = (Double, Double)
trait Turtle {
def penDown()
def turn(angle: Double)
def getPosition: (Double, Double)
def getAngle: Double
val arrivedTarget: Position => Boolean
}

"somthing" should "do something" in {
val mockTurtle = mock[Turtle](mockTurtle.getPosition _).expects().returning(0.0, 0.0)
mockTurtle.getPosition should equal(0.0, 0.0)
}
}

yields the compilation error:
[error] C:...: trait Function1 takes type parameters
[error] val mockTurtle = mock[Turtle]

mock objects for scala objects with multiple parameter list methods are not generated properly

When mocking an object like:

object Foo {
def foo(s:String)(t:String):List[String] = List(s,t)
}

The generated mock does not compile:

object Foo extends Mock$$Foo {

def foo(s: String): (t: String)List[String] = if (forwardTo$Mocks != null) forwarder$0(s) else mock$0(s)
// other generated methods here
}

As you can see the generated mock does not implement the correct method signature. After the first parameter list it inserts โ€œ:โ€ expecting a return type.

ScalaMock 3 shows unexpected calls on proxy mocks defined at the class level

Similarly to issue #25 if you define a proxy mock outside the scope of the test you get unexpected results, but not the NPE that is happening in #25. This code worked with the proxy mocks from scalamock 2. This was attempted using 3.1-MILESTONE as of today (Feb 11, 2013).

An example in included below:

import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
class ProxyMockTests extends FunSuite with ShouldMatchers with org.scalamock.scalatest.proxy.MockFactory {
    trait TraitWithMethodImplemented {
      def implemented = "implemented"
    }
    val mockTrait = mock[TraitWithMethodImplemented]

    test("one") {
      mockTrait.expects('implemented)().returning("Blah")
      mockTrait.implemented
    }

    test("two") {
      mockTrait.expects('implemented)().returning("Blah2")
      mockTrait.implemented
    }
  }

This yields the following output:

[info] ProxyMockTests:
[info] - one
[info] - two *** FAILED ***
[info]   Unexpected call: implemented()
[info] 
[info] Expected:
[info] inAnyOrder {
[info]   implemented() once (never called - UNSATISFIED)
[info] }
[info] 
[info] Actual: (Option.scala:120)
[error] Failed: : Total 2, Failed 1, Errors 0, Passed 1, Skipped 0

ScalaMock does not work with ScalaTest 2.0.M3

My built.sbt is

resolvers += "Sonatype OSS Releases" at
"http://oss.sonatype.org/content/repositories/releases/"

libraryDependencies ++= Seq(
"net.databinder.dispatch" %% "core" % "0.9.0",
"org.scalatest" %% "scalatest" % "2.0.M3" % "test",
"org.scalaz" %% "scalaz-core" % "6.0.4",
"org.scalamock" %% "scalamock-scalatest-support" % "latest.integration"
)

The following fails to compile:

import org.scalatest._
import org.scalamock.scalatest.MockFactory

class StackSpec extends FlatSpec with MockFactory {
}

class StackSpec needs to be a mixin, since:
[error] method runTest in trait MockFactory of type (testName: String, reporter: org.scalatest.Reporter, stopper: org.scalatest.Stopper, configMap: Map[String,Any], tracker: org.scalatest.Tracker)Unit is marked abstract' andoverride', but no concrete implementation could be found in a base class
[error] method runTests in trait MockFactory of type (testName: Option[String], reporter: org.scalatest.Reporter, stopper: org.scalatest.Stopper, filter: org.scalatest.Filter, configMap: Map[String,Any], distributor: Option[org.scalatest.Distributor], tracker: org.scalatest.Tracker)Unit is marked abstract' andoverride', but no concrete implementation could be found in a base class
[error] class StackSpec extends FlatSpec with MockFactory {
[error] ^
[error] one error found

generate-mock is successful but test fails

I'm trying ScalaMock 2.2 with Scala 2.9.1 and sbt 0.11.2 according to the procedure of the following entry:
http://www.paulbutcher.com/2011/11/scalamock-step-by-step/

I could generate mock sources by "sbt generate-mocks" into target/scala-2.9.1/src_managed, but I can't run "sbt test" because test compilation is failed.

C:\scalamock-test>sbt test
[info] Loading global plugins from C:\Users\takezoe\.sbt\plugins
[info] Loading project definition from C:\scalamock-test\project\project
[info] Loading project definition from C:\scalamock-test\project
[info] Set current project to scalamock-test (in build file:/C:/scalamock-test/)
[info] Compiling 2 Scala sources to C:\scalamock-test\target\scala-2.9.1\test-classes...
[error] C:\scalamock-test\src\test\scala\jp\sf\amateras\scala\test\scalamock\ScalaMockTest.scala:5: object generated is not a member of package org.scalamock
[error] import org.scalamock.generated.GeneratedMockFactory
[error]                      ^
[error] C:\scalamock-test\src\test\scala\jp\sf\amateras\scala\test\scalamock\ScalaMockTest.scala:12: not found: value mock
[error]     val helloworld = mock[HelloWorld]
[error]                      ^
[error] C:\scalamock-test\src\test\scala\jp\sf\amateras\scala\test\scalamock\ScalaMockTest.scala:21: not found: value mockObject
[error]     val util = mockObject(StringUtils)
[error]                ^
[error] three errors found
[error] {file:/C:/scalamock-test/}scalamock-test/test:compile: Compilation failed
[error] Total time: 2 s, completed 2012/03/01 4:57:43

It seems compiler does not see src_managed but I can't understand why...

Can't mock traits with ScalaTest and ScalaMock

I'm having trouble mocking traits with ScalaMock and ScalaTest. This - http://stackoverflow.com/questions/14283879/how-do-i-use-scalamock-proxy-mocks - describes my problem. Here is the same example converted to the latest 3.1-SNAPSHOT of scalamock-scalatest-support_2.10:

import org.scalatest.FunSpec
import org.scalatest.BeforeAndAfter
import org.scalatest.matchers.ShouldMatchers
import org.scalamock.scalatest.proxy.MockFactory

class TestSpec extends FunSpec 
  with BeforeAndAfter with ShouldMatchers
  with MockFactory{

  trait Turtle {
    def turn(angle: Double)
  }

  val m = mock[Turtle]

  (m.turn _) expects(10.0)
  // How should I do set arguments with this syntax:
  // m expects 'turn ???

  describe("A turtle-tester") {
    it("should test the turtle") {
      m.turn(10.0)
    }
  }
}

This gives a "java.lang.NoSuchMethodException: com.sun.proxy.$Proxy4.mock$turn$0()". And I can't work out how to use the "m expects 'turn" syntax with arguments.

Am I just missing something?

missing implicit Defaultables when constructing some mocks

We are using Akka's dataflow concurrency API which makes a heavy use of delimited continuations. If a class contains a method whose return type is CPS annotated, then ScalaMock fails to mock that class. The compiler error is as follows (in our particular case; hopefully good enough to point at the problem):

[error] /opt/gwt/pdp/test/controllers/MarketingPageControllerSpec.scala:21: could not find implicit value for evidence parameter of type org.scalamock.Defaultable[models.Page @util.continuations.cps[scala.concurrent.Future[Any]]]
[error]             val p = mock[PageService]
[error]                         ^
[error] one error found
[error] (test:compile) Compilation failed

[ cc: @apgeorge, @mushtaq ]

Cannot mock classes that inherit from superclass.

Given the following classes, ScalaMock is unable to create a mock for CompilationAlbum. Assume that annotation have been placed already on the Dummy object.

package com.oreilly.testingscala

import org.joda.time.Period

class Album (val title: String, val year: Int, val tracks: Option[List[Track]], val acts: Act*) {
  require(acts.size > 0)

  def this(title: String, year: Int, acts: Act*) = this(title, year, None, acts:_*)

  def ageFrom(now: Int) = now - year

  def period = tracks.getOrElse(Nil).map(_.period).foldLeft(Period.ZERO)(_.plus(_))

  override def toString = ("Album" + "[" + title + "]")
}
package com.oreilly.testingscala

class CompilationAlbum(override val title: String,
                       override val year: Int,
                       val tracksAndActs: (Track, List[Act])*)
  extends Album(title, year,
                Some(tracksAndActs.map(_._1).toList),
                tracksAndActs.flatMap(_._2).distinct:_*)

The above causes the following messages complaining about override tags that are required:

[info] Compiling 19 Scala sources to /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/mock-classes...
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:57: overriding lazy value mock$0 in class Album of type org.scalamock.MockFunction;
[error]  lazy value mock$0 needs `override' modifier
[error]   protected lazy val mock$0 = new org.scalamock.MockConstructor[com.oreilly.testingscala.CompilationAlbum](factory, Symbol("this"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:58: overriding lazy value mock$1 in class Album of type org.scalamock.MockFunction;
[error]  lazy value mock$1 needs `override' modifier
[error]   protected lazy val mock$1 = new org.scalamock.MockFunction(factory, Symbol("tracksAndActs"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:59: overriding lazy value mock$2 in class Album of type org.scalamock.MockConstructor[com.oreilly.testingscala.Album];
[error]  lazy value mock$2 needs `override' modifier
[error]   protected lazy val mock$2 = new org.scalamock.MockFunction(factory, Symbol("year"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:60: overriding lazy value mock$3 in class Album of type org.scalamock.MockConstructor[com.oreilly.testingscala.Album];
[error]  lazy value mock$3 needs `override' modifier
[error]   protected lazy val mock$3 = new org.scalamock.MockFunction(factory, Symbol("title"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:61: overriding lazy value mock$4 in class Album of type org.scalamock.MockFunction;
[error]  lazy value mock$4 needs `override' modifier
[error]   protected lazy val mock$4 = new org.scalamock.MockFunction(factory, Symbol("period"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:62: overriding lazy value mock$5 in class Album of type org.scalamock.MockFunction;
[error]  lazy value mock$5 needs `override' modifier
[error]   protected lazy val mock$5 = new org.scalamock.MockFunction(factory, Symbol("ageFrom"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:63: overriding lazy value mock$6 in class Album of type org.scalamock.MockFunction;
[error]  lazy value mock$6 needs `override' modifier
[error]   protected lazy val mock$6 = new org.scalamock.MockConstructor[com.oreilly.testingscala.Album](factory, Symbol("this"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:64: overriding lazy value mock$7 in class Album of type org.scalamock.MockFunction;
[error]  lazy value mock$7 needs `override' modifier
[error]   protected lazy val mock$7 = new org.scalamock.MockConstructor[com.oreilly.testingscala.Album](factory, Symbol("this"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:65: overriding lazy value mock$8 in class Album of type org.scalamock.MockConstructor[java.lang.Object];
[error]  lazy value mock$8 needs `override' modifier
[error]   protected lazy val mock$8 = new org.scalamock.MockFunction(factory, Symbol("acts"))
[error]                      ^
[error] /home/danno/testing_scala_book.svn/testingscala/target/scala-2.9.1/src_managed/mock/scala/com/oreilly/testingscala/CompilationAlbum.scala:3: overriding value expects in trait Mock$Album of type java.lang.Object{def period: org.scalamock.TypeSafeExpectation0[org.joda.time.Period]; def ageFrom(now: org.scalamock.MockParameter[Int]): org.scalamock.TypeSafeExpectation1[Int,Int]; def ageFrom(matcher: org.scalamock.MockMatcher1[Int]): org.scalamock.TypeSafeExpectation1[Int,Int]; def newInstance(title: org.scalamock.MockParameter[String],year: org.scalamock.MockParameter[Int],acts: org.scalamock.MockParameter[com.oreilly.testingscala.Act]*): org.scalamock.Expectation; def newInstance(title: org.scalamock.MockParameter[String],year: org.scalamock.MockParameter[Int],tracks: org.scalamock.MockParameter[Option[List[com.oreilly.testingscala.Track]]],acts: org.scalamock.MockParameter[com.oreilly.testingscala.Act]*): org.scalamock.Expectation; def acts: org.scalamock.TypeSafeExpectation0[Seq[com.oreilly.testingscala.Act]]; def tracks: org.scalamock.TypeSafeExpectation0[Option[List[com.oreilly.testingscala.Track]]]; def year: org.scalamock.TypeSafeExpectation0[Int]; def title: org.scalamock.TypeSafeExpectation0[String]; def newInstance(): org.scalamock.Expectation};
[error]  value expects in trait Mock$CompilationAlbum of type java.lang.Object{def newInstance(title: org.scalamock.MockParameter[String],year: org.scalamock.MockParameter[Int],tracksAndActs: org.scalamock.MockParameter[(com.oreilly.testingscala.Track, List[com.oreilly.testingscala.Act])]*): org.scalamock.Expectation; def tracksAndActs: org.scalamock.TypeSafeExpectation0[Seq[(com.oreilly.testingscala.Track, List[com.oreilly.testingscala.Act])]]; def year: org.scalamock.TypeSafeExpectation0[Int]; def title: org.scalamock.TypeSafeExpectation0[String]; def period: org.scalamock.TypeSafeExpectation0[org.joda.time.Period]; def ageFrom(now: org.scalamock.MockParameter[Int]): org.scalamock.TypeSafeExpectation1[Int,Int]; def ageFrom(matcher: org.scalamock.MockMatcher1[Int]): org.scalamock.TypeSafeExpectation1[Int,Int]; def newInstance(title: org.scalamock.MockParameter[String],year: org.scalamock.MockParameter[Int],acts: org.scalamock.MockParameter[com.oreilly.testingscala.Act]*): org.scalamock.Expectation; def newInstance(title: org.scalamock.MockParameter[String],year: org.scalamock.MockParameter[Int],tracks: org.scalamock.MockParameter[Option[List[com.oreilly.testingscala.Track]]],acts: org.scalamock.MockParameter[com.oreilly.testingscala.Act]*): org.scalamock.Expectation; def acts: org.scalamock.TypeSafeExpectation0[Seq[com.oreilly.testingscala.Act]]; def tracks: org.scalamock.TypeSafeExpectation0[Option[List[com.oreilly.testingscala.Track]]]; def newInstance(): org.scalamock.Expectation} needs `override' modifier;
[error]  other members with override errors are: factory
[error] class CompilationAlbum(dummy: org.scalamock.MockConstructorDummy) extends com.oreilly.testingscala.Album with Mock$CompilationAlbum {
[error]       ^
[error] 10 errors found
[error] {file:/home/danno/testing_scala_book.svn/testingscala/}Testing Scala/mock:compile: Compilation failed

ScalaMock doesn't work with Play 2.1-RC2 Specs

Hi.

We are unable to use ScalaMock with the latest RC of Play. We are using Specs2.

The error is:

class MarketingPageControllerSpec needs to be abstract, since method around in trait AroundExample of type [T](t: => T)(implicit evidence$1: org.specs2.execute.AsResult[T])org.specs2.execute.Result is not defined
[error] (Note that => T does not match => T: their type parameters differ)

class MarketingPageControllerSpec extends mutable Specification and MockFactory.

Is ScalaMock 3.0 compiled against the same version of Specs2 as the one that the latest Play RC is using?

[ cc: @apgeorge, @mushtaq ]

How to change the mocks directory using sbt?

Using sbt, how would I change the directory where I put my mocks from src/generate-mocks/scala/ to something else (say, mocks/)? The docs and sbt example don't mention it and my sbt-fu doesn't seem to be great enough to figure it out from the plugin source.

Upgrading to Scala 2.10

I tried upgrading our tests to Scala 2.10 by using

"org.scalamock" %% "scalamock-scalatest-support" % "3.0.1".

We are using org.scalamock.ProxyMockFactory, which now should be proxy.ProxyMockFactory.

However, the compiler reports ProxyMockFactory is an unknown type. Indeed, the latest released jar does not contain ProxyMockFactory.

Any pointers on migrating to Scala 2.10? I see that 3.1-SNAPSHOT contains the ProxyMockFactory. Should we just wait for the release of 3.1?

Thanks!

ScalaTest 2.0 and ScalaMock 3.1-SNAPSHOT don't play nice.

So, it would seem that the 3.1-SNAPSHOT JAR of ScalaMock is missing the compatibility changes that were done a few months ago. While trying to compile ScalaMock with a project I'm working on, I see the following compiler error if I try to use scalatest newer than 2.0.M5b...

[error] /Users/matt/Sites/sbt-resource-management/src/test/scala/com/openstudy/sbt/SassCompilationSpec.scala:6: overriding method withFixture in trait Suite of type (test: SassCompilationSpec.this.NoArgTest)org.scalatest.Outcome;
[error]  method withFixture in trait AbstractMockFactory of type (test: SassCompilationSpec.this.NoArgTest)Unit has incompatible type
[error] class SassCompilationSpec extends FunSpec with MockFactory {
[error]       ^
[error] one error found
[error] (test:compile) Compilation failed
[error] Total time: 15 s, completed Feb 25, 2014 11:22:13 PM

This looks like it's fixed, from what I can tell on GitHub, so I'm not sure why the JAR I'm getting isn't reflecting that, but it's not. :(

Is it possible to use proxy mocks with generated mocks?

My environment is Scala 2.9.1, sbt 0.11.2 and ScalaMock 2.2.

I want to use both of proxy mocks and generated mocks in the single project. So I configured my sbt project to enable compiler plugin. generate-mocks and tests which use generated mocks were successful. However I got the following error for tests which use proxy mocks. They had been successful before configuring my sbt project for generated mocks.

[info]   java.lang.IllegalArgumentException: Unable to create proxy - possible classloader issue? Consider setting proxyClassLoaderStrategy
[info]   at org.scalamock.Proxy$.create(Proxy.scala:40)
[info]   at org.scalamock.ProxyMockFactory$class.mock(ProxyMockFactory.scala:30)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest.mock(ScalaProxyMockTest.scala:6)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest$$anonfun$1.apply$mcV$sp(ScalaProxyMockTest.scala:14)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest$$anonfun$1.apply(ScalaProxyMockTest.scala:12)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest$$anonfun$1.apply(ScalaProxyMockTest.scala:12)
[info]   at org.scalatest.FunSuite$$anon$1.apply(FunSuite.scala:1265)
[info]   at org.scalatest.Suite$class.withFixture(Suite.scala:1968)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest.withFixture(ScalaProxyMockTest.scala:6)
[info]   at org.scalatest.FunSuite$class.invokeWithFixture$1(FunSuite.scala:1262)
[info]   ...
[info]   Cause: java.lang.IllegalArgumentException: interface org.scalamock.Mock is not visible from class loader
[info]   at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353)
[info]   at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581)
[info]   at org.scalamock.Proxy$.create(Proxy.scala:37)
[info]   at org.scalamock.ProxyMockFactory$class.mock(ProxyMockFactory.scala:30)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest.mock(ScalaProxyMockTest.scala:6)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest$$anonfun$1.apply$mcV$sp(ScalaProxyMockTest.scala:14)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest$$anonfun$1.apply(ScalaProxyMockTest.scala:12)
[info]   at jp.sf.amateras.scala.test.scalamock.ScalaProxyMockTest$$anonfun$1.apply(ScalaProxyMockTest.scala:12)
[info]   at org.scalatest.FunSuite$$anon$1.apply(FunSuite.scala:1265)
[info]   at org.scalatest.Suite$class.withFixture(Suite.scala:1968)
[info]   ...

Here is my sbt project configuration:

import sbt._
import Keys._
import ScalaMockPlugin._

object MyProject extends Build {

  override lazy val settings = super.settings ++ Seq(
    organization := "jp.sf.amateras.scala",
    version := "1.0",
    scalaVersion := "2.9.1",
    libraryDependencies += "org.scalamock" %% "scalamock-scalatest-support" % "2.2",
    autoCompilerPlugins := true,
    addCompilerPlugin("org.scalamock" %% "scalamock-compiler-plugin" % "2.2")
  )

  lazy val myproject = Project("MyProject", file(".")) settings(generateMocksSettings: _*) configs(Mock)

}

When I rolled back my project configuration (which has only library dependency to scalamock-scalatest-support), tests which use proxy mocks is successful.

Is it possible to use proxy mocks and generated mocks in the single project?

ScalaMock 3.0.1 problem with a class with constructor arguments

We are using ScalaMock 3.0.1 with Spec2 and Scala 2.10

libraryDependencies +=
"org.scalamock" %% "scalamock-specs2-support" % "3.0.1" % "test"

When we try to mock a class with constructor arguments

i.e

class Test(number:Int)
val arg=Mock[Test]

We get the following error

error: not enough arguments for constructor Test: (number: Int)Test.
Unspecified value parameter number.
val arg= mock[Test]

Could you please let us know if this is an existing issue and if there is any way to overcome it?
Thanks.

ScalaMock 3 has errors while trying to mock a Java class with overloaded methods

Because of "reasons," we (at work) have a Java-only codebase, but since we like using scala, we decided to write our tests using ScalaTest and ScalaMock 3.0.1. Unfortunately when trying to "expect" a method call to an overloaded method, it fails. In Eclipse, I see an "info" listed in the "Problems" view, saying "Unable to resolve overloaded method bar".

This Gist is a minimal example that produces the same problem.

Can't seem to instantiate mocks for Java classes that have no default constructor

Hi,

I'm trying to use a mock (using the compiler plugin) for a Java class that has no default constructor, but I get this when trying to initialize it via mock[MappingEngine]:

[error] NoSuchMethodException: eu.delving.MappingEngine.<init> (org.scalamock.MockConstructorDummy) (Class.java:1657)
[error] org.scalamock.GeneratedMockFactoryBase$class.mock(GeneratedMockFactoryBase.scala:28)
[error] CollectionProcessorSpec.mock(CollectionProcessorSpec.scala:17)
[error] CollectionProcessorSpec$$anonfun$1$$anonfun$apply$4$$anonfun$apply$5.apply(CollectionProcessorSpec.scala:27)

Is there something special that needs to be done in this case?

Thanks,

Manuel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.