EzDevInfo.com

ScalaMock

Native Scala mocking framework ScalaMock - Home

Can ScalaMock3 mock java.lang.Thread.sleep

Is there a way to mock sleep and set an expectation on it?

class Foo {
  def func = {
    Thread.sleep(100)
  } 
}

For example, in Ruby, I'd just add the stub to Thread. But with Scalamock, I'm not sure how to inject that mock into the class.


Source: (StackOverflow)

How can I use scalamock to stub WSRequestHolder.post() in Play

I'm having trouble using scalamock to stub the post() method in WSRequestHolder in the Play WS library.

Here's what I'm trying:

(request.post[Results.EmptyContent](_ : Results.EmptyContent)(_ : Writeable[Results.EmptyContent], _: ContentTypeOf[Results.EmptyContent])) when(Results.EmptyContent(), *,*) returns Future.successful(response)

The aim is to return Future.successful(response) when a post() is called with Results.EmptyContent.

The compiler error I'm getting is:

value when is not a member of (play.api.mvc.Results.EmptyContent, play.api.http.Writeable[play.api.mvc.Results.EmptyContent], play.api.http.ContentTypeOf[play.api.mvc.Results.EmptyContent]) => scala.concurrent.Future[play.api.libs.ws.WSResponse] (request.post[Results.EmptyContent](_ : Results.EmptyContent)(_ : Writeable[Results.EmptyContent], _: ContentTypeOf[Results.EmptyContent])).when(Results.EmptyContent(), ,) returns Future.successful(response)

Any idea what I'm doing wrong?


UPDATE

There is something going on here that I don't really understand. If I define the following trait:

  trait TestTrait {
    def post[T](data: T)(implicit wrt: Writeable[T], ct: ContentTypeOf[T]): Future[WSResponse]
  }

which has a post() method with the same signature as WSRequestHolder.post(), I can successfully stub it. So, there is some weirdness specific to WSRequestHolder.post() that is manifesting in this problem. Some nuance with regard to type inference maybe?


UPDATE 2

So, I've found a workaround. In my test, I define a new trait that extends WSRequestHolder:

trait StubbableWSRequestHolder extends WSRequestHolder {
  override def post[T](data: T)(implicit wrt: Writeable[T], ct: ContentTypeOf[T]): Future[WSResponse] =
    withMethod("POST").withBody(body).execute()
}

In my test, I create my stub from this trait. As you can see, unlike in WSRequestHolder, my overriden signature for post() is explicit about the return type of Future[WSResponse].

The question remains, though, as to what exactly is going on here? Is this some kind of limitation with scalamock with regard to type inference?


Source: (StackOverflow)

Advertisements

How to inject stubbed DAOs into a FakeApplication when testing a Play2 controller with Specs2?

Workaround in the edit below

I have a simple controller like:

class FooController @Inject()(dao: SomeDAO) extends Controller {

  def foo = Action({
    // implicitly converted to JsObject
    Ok(dao.querySomething(): JsObject).withHeaders(CONTENT_TYPE -> "application/json")
  })
}

My route is setup correctly:

GET /foo @com.example.something.controllers.FooController.foo

The test is setup the following:

object FooControllerTest extends PlaySpecification with Results with MockContext {

  val dao: SomeDAO = {
    val temp: SomeDAO = stub[SomeDAO]
    (temp.querySomething _).when returns SomeTestdata() // is an object whose apply method creates dummy data
    temp
  }

  val app: Application = new GuiceApplicationBuilder().overrides(bind[SomeDAO].to(dao)).build()

  "The controller" should {
    "respond with OK" in new WithApplication(app) {
      status(route(FakeRequest(GET, "/foo")).get) must equalTo(OK)
    }
  }
}

When I try to run this, I get an NPE as soon as dao.querySomething() is called.

The strange thing is, when I call temp.querySomething() in the block where the mock is setup (i.e., val dao: SomeDAO = ...) I get the expected testdata, but inside the test, I get an NPE.

The Scalamock user guide says that the MockContext should be used at the stage where the new WithApplication is in my test, however I cannot put it there because the WithApplication needs my application with the mock DAO bound.

How do I achieve this?

Workaround:

Since I could not find a solution by myself and until now apparently nobody else could, I went with a workaround: I did not use Scalamock, but implemented a simple dummy version of the DAO. I then created a WithDummyDaoApplication which creates an instance of the DummyDao, creates an Application with the GuiceApplicationBuilder and injects the DummyDao there. Apart from this, it works the same as WithApplication instead it does not use FakeApplication but the one created with the dummy DAO.

Not the best solution IMHO, but does what I want.


Source: (StackOverflow)

Scalamock scalatest - Not able to stub

I have created a Workflow Processor Trait similar to the one mentioned below:

import org.scalatestplus.play._
import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._
import org.scalatest.Matchers._
import org.scalamock.scalatest.MockFactory
import utils.OAuthUtils._
import utils.OAuthUtils
import utils.OAuthProcess
import play.api.Application
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import play.api.libs.json.JsResult
import play.api.libs.json.Json
import play.api.libs.json.JsSuccess
import play.api.libs.json.JsError
import play.api.libs.ws.WS



trait MyProcess[A] {
  type B
  type C
  type D
  def stage1(s: String): B
  def stage2(b: B)(implicit e: ExecutionContext, app: Application, a: A):       Future[C]
  def stage3(c: C)(implicit e: ExecutionContext, app: Application, a: A): Future[JsResult[D]]
  def process(s: String)(implicit e: ExecutionContext, app: Application, a: A): Future[JsResult[D]] = {
   val b = stage1(s)
   val f_d = for {
      c <- stage2(b)
      d <- stage3(c)
   } yield d
   f_d
 }
}

Now I would like to Unit test this code. So I created a nicer little scalatest scalamock test suite:

class TestController extends PlaySpec with Results with MockFactory {
  "MyController" must {
    " testing for method process" in {
  running(FakeApplication()) {

    implicit val context = scala.concurrent.ExecutionContext.Implicits.global
    implicit val s = "implicit String"
    implicit val currentApp = play.api.Play.current

  case class TestParms(s: String)
  abstract class TestProcessor extends MyProcess[TestParms] {
      type B = String
      type C = String
      type D = String
    }

    implicit val t = stub[TestProcessor]
    t.stage1(_: String).when(token).returns(testToken)

    (t.stage2(_: String)(_: ExecutionContext, _: Application, _: TestParms)).when(token, context, currentApp, tp).returns({
      Future.successful(stage2String)
    })
    (t.stage3(_: String)(_: ExecutionContext, _: Application, _: TestParms)).when(token, context, currentApp, tp).returns({
      Future.successful(Json.fromJson[String](Json.parse(stage3String)))
     })
   }
 }
}
}

My expectation is to set this stub on a different class and test the class. Stubs (t.stage2 and t.stage3) compile fine but the following statement doesn't compile.

 t.stage1(_: String).when(token).returns(testToken)

Compiler reports the following issue:

overloaded method value when with alternatives:   (resultOfAfterWordApplication: org.scalatest.words.ResultOfAfterWordApplication)Unit <and>   (f: => Unit)Unit  cannot be applied to (String)  TestController.scala  /play-scala/test/controllers

Could someone help? I am finding it very difficult to write Unit tests for Scala classes as well as mocking them.

Scalatest versions from Build.sbt:

 "org.scalatestplus" %% "play" % "1.2.0" % "test",
 "org.scalamock" %% "scalamock-scalatest-support" % "3.2" % "test",

Source: (StackOverflow)

How to use scala mock to provide an alternative implementation of a class as stub for test?

I found in a project i'm about to contribute with some external lib, that for testing purpose they set up a mock database manager. However what this database manager does, is creating an in-memory database and working with it. This is for testing purpose.

The framework used is Jmockit.

I try to find out how i could reproduce that in scalamock, but could not figure out.

Here how this is set up in jmockit:

/**
 * Mocks a DatabaseManager so unit tests can be run without a real DB connection
 * The code is basically the same as the original DatabaseManager but it
 * establishes a connection to an in-memory database.
 *
 * @author pvillega
 */
@MockClass(realClass = DatabaseManager.class)
public class MockDatabaseManager {...}

Is there anything that could support that in scalamock. I know this is related to how the all application has been developed. Especially how they used or did not used dependency injection. But nevertheless we have to deal with legacy code sometime :) (most of the time)

The only thing i see is writing all the function of a stub. A - However that is just not nice. B - Also it is not a full class that can retain state. So everything would have to be manage in the enclosing class that is creating the stub. c - Again, legacy code do a lot of funny things inside the class, so i would have to recreate all the code and etc... d - I would appreciate to reuse what they MockDatabaseManager.

Any advise?


Source: (StackOverflow)

ScalaMock a method with two parameter groups

How exactly should I mock something like this (the post method of Play's WSRequest from the WS library):

def post[T](body: T)(implicit wrt: Writeable[T], ct: ContentTypeOf[T]): Future[WSResponse]

I've read through the ScalaMock page about this and I'm not having any success.

Can it also be stubbed? I'm trying this with no luck:

(mockRequest.post[String] (_ : String)(_ : Writeable[String], _: ContentTypeOf[String])).when(*,*,*).returns(Future.successful(mockResponse))

Source: (StackOverflow)

Using a mocked object as an implicit in scala using scalamock

I am using a trait definition with various concrete derivatives and implicit to inject dependancies into objects and also to mock out parts of the system when unit testing. The problem is that when a mocked version of a type is used as an implicit declaration, it is not matched by scala in the consuming object.

Here is a simplified version of my setup. Is there a way to make Test1 work using a mock. Test2 works fine but it hard to maintain and requires too much setup.

A model:

case class User (first: String, last: String, enabled: Boolean)

Component Definition:

trait DataProviderComponent {
  def find[T](id: Int): Try[T]
  def update[T](data: T): Try[T]
}

One of the concrete component implementations:

class DbProvider extends DataProviderComponent {
  override def find[T](id: Int): Try[T] = { ... }
  override def update[T](data: T): Try[T] = { ... }
}

Implicit usage of component impl somewhere in system:

implicit val provider = new DbProvider()

class UserRepsitory(implicit provider: DataProviderComponent) {
  def userEnabled(id: Int): Boolean = {
    val user = provider.find[User](id)
    user.isSuccess && user.get.enabled
  }
}

Unit Test1, trying to mock out provider in order to isolate repository test. This does not work, the repository class does not match the implicit even though it is based on DataProviderComponent:

class UserRepository$Test1 extends FunSuite with Matchers with MockFactory {
  test("invalid data request should return false") {
    implicit val  mockProvider = mock[DataProviderComponent]
    (mockProvider.find[User] _).expects(13).returns(Failure[User](new Exception("Failed!")))

    val repo = new UserRepsitory()
    repo.userEnabled(13) should be (false)
  }
}

This version does work but is hard to maintain and requires more code:

class UserRepository$Test2 extends FunSuite with Matchers with MockFactory {
  test("invalid data request should return false") {
    class FakeProvider extends DataProviderComponent {
      override def find[T](id: Int): Try[T] = ???
      override def update[T](data: T): Try[T] = Failure[T](new Exception("Failed!"))
    }

    implicit val provider = new FakeProvider()
    val repo = new UserRepsitory()
    repo.userEnabled(13) should be (false)
  }
}

Is there a way to use a mocked type as an injected implicit - or is there another scala-thonic a pattern I should use to solve this problem?


Source: (StackOverflow)

How to write Expectations with ScalaMock?

This question seems pretty obvious I know, but i've tried everything that is written on the documentation and I cant't mock a single method on any classes.

For this test, I am using scalaMock 3 for Scala 2.10 and ScalaTest 2

DateServiceTest.scala

@RunWith(classOf[JUnitRunner])
class DateServiceTest extends FunSuite with MockFactory{
  val conf = new SparkConf().setAppName("Simple Application").setMaster("local")

  val sc = new SparkContext(conf)

  implicit val sqlc = new SQLContext(sc)

  val m = mock[DateService]
  (m.getDate _).expects().returning(Some(new DateTime)) // Error here
}

DateService.scala

class DateService extends Serializable {

  def getDate(implicit sqlc: SQLContext): Option[DateTime] = {
    Some(new DateTime(loadDateFromDatabase(sqlc)))
  }
}

This seems pretty simple for me, but the expectation is Throwing me this error

type mismatch; found : Option[org.joda.time.DateTime] required: ? ⇒ ?

Am I doing something wrong here? Is there another way to set the expectations of a method ?


Source: (StackOverflow)

Mocking a val of a trait with scala-mock

I'd like to mock a val of a trait. for example, in this code, to mock the val baz:

trait Foo {
  def bar(): Int
  val baz: Int
}

val fooMock = mock[Foo]
(fooMock.bar _).expects().returning(5)
(fooMock.baz _).expects().returning(6) //doesn't compile

doSomeThing(fooMock)

To solve this in my test, I've extended Foo, and implemented baz in the following manner:

trait FooTest extends Foo {
  override val baz: Int = 5
}

val fooMock = mock[FooTest]
(fooMock.bar _).expects().returning(6)

doSomeThing(fooMock)

But this is ugly, and I was hoping that there is a more standard way of doing this with scala mock.

I've seen the answer to this question, but it requires changing the val to def in the trait, and I'd like to keep baz a val


Source: (StackOverflow)

Why don't specs2 + scalamock tests run in IntelliJ? Multiple suite traits detected

I'm trying to run Specs2 tests from IDEA from both Windows and Mac versions of Intellij IDEA 14. I generated the idea project files using both gen-idea and the built in SBT plugin and get the same results...

When I try to run them, I get

Error running Specs2 in 'scala': Test class not found

I've added packages and switched "search for tests" to in single module but still no avail. I also get the message below on the run config.

Multiple suite traits detected: List(ScTrait: SpecificationStructure, ScTrait: SpecificationStructure,)

The similar post How to run all Specs2 tests under IntelliJ IDEA? doesn't help and it all runs fine from SBT, BTW. I can't run individual tests via the short-cut either :'(

I'm suspecting it's a combination of scalamock and specs2, as if I remove the following from my build.sbt, I can run them again.

"org.scalamock" %% "scalamock-specs2-support" % "3.2" % "test"

Here's the run config.

enter image description here


Source: (StackOverflow)

Does ScalaMock support mocking of (companion) objects and constructors?

There are somewhat contradictory statements about the abilities of ScalaMock to mock (companion) objects and constructors. The page ScalaMock step-by-step states

it can also mock:

  • Classes *Singleton and companion objects (static methods)
  • Object creation (constructor invocation)
  • Classes with private constructors
  • Final classes and classes with final methods
  • Operators (methods with symbolic names)
  • Overloaded methods

On the other hand the roadmap tells me:

First Quarter 2016 - ScalaMock 4 As soon as scala.meta is available, we plan to start working on ScalaMock 4. If scala.meta delivers on its promise, ScalaMock 4 should be able to mock any trait, no matter how complex its type.

In addition, we expect that it will also support:

  • improved syntax: mockObject.expects.method(arguments) instead of: (mockObject.method _) expects (arguments)
  • mocking object creation (constructors)
  • mocking singleton and companion objects (static methods)
  • mocking final classes and classes with final methods or private constructors

So, what is correct? Is the current version (ScalaMock 3.2) able to mock objects and constructors, or not?


Source: (StackOverflow)

mocking methods which use ClassTag in scala using scalamock

My first question, question, was answered but it uncovered another issue I am having. Here is the scenario.

Example code (expanded from previous question)

A Model:

case class User (first: String, last: String, enabled: Boolean)

Component Definition:

trait DataProviderComponent {
  def find[T: ClassTag](id: Int): Try[T]
  def update[T](data: T): Try[T]
}

One of the concrete component implementations (updated implementation):

class DbProvider extends DataProviderComponent {
  override def find[T: ClassTag](id: Int): Try[T] = {
    Try {
      val gson = new Gson()
      val testJson = """{"first": "doe", "last": "jane", "enabled": false}"""

      gson.fromJson(testJson, implicitly[ClassTag[T]].runtimeClass).asInstanceOf[T]
    }
  }

  override def update[T](data: T): Try[T] = ???
}

Implicit usage of component impl somewhere in system:

implicit val provider = new DbProvider()

class UserRepsitory(implicit provider: DataProviderComponent) {
  def userEnabled(id: Int): Boolean = {
    val user = provider.find[User](id)
    user.isSuccess && user.get.enabled
  }
}

Unit Test1, trying to mock out provider in order to isolate repository test. This does not work, the following execption is thrown when test is run. I expect it is because of ClassTag usage because when I create another sample which does not use ClassTag, it works fine.

org.scalamock.MockFunction2 cannot be cast to org.scalamock.MockFunction1 java.lang.ClassCastException: org.scalamock.MockFunction2 cannot be cast to org.scalamock.MockFunction1

class UserRepository$Test1 extends FunSuite with Matchers with MockFactory {
  test("invalid data request should return false") {
    implicit val mockProvider: DataProviderComponent = mock[DataProviderComponent]
    (mockProvider.find[User] _).expects(13).returns(Failure[User](new Exception("Failed!")))

    val repo = new UserRepsitory()
    repo.userEnabled(13) should be (false)
  }
}

Unit Test2 does work but is hard to maintain and requires more code:

class UserRepository$Test2 extends FunSuite with Matchers with MockFactory {
  test("invalid data request should return false") {
    class FakeProvider extends DataProviderComponent {
      override def find[T:ClassTag](id: Int): Try[T] = Failure[T](new Exception("Failed!"))
      override def update[T](data: T): Try[T] = ???
    }

    implicit val provider = new FakeProvider()
    val repo = new UserRepsitory()
    repo.userEnabled(13) should be (false)
  }
}

Unit Test3 does work but - used just to test ClassTag implemenation:

class UserRepository$Test3 extends FunSuite with Matchers with MockFactory {
  test("prove sut works") {
    implicit val provider = new DbProvider()
    val repo = new UserRepsitory()
    val user = repo.userEnabled(13)
    println(user.toString)
  }
}

Am I using ClassTag wrong or is the mock not able to properly mock it?


Source: (StackOverflow)

scalamock: Wildcard argument match on subtype

In my class, I have two versions of a method. One takes an Exception, the other a String.

class Foo {
  def method(e: Exception) = ???
  def method(s: String) = ???
}

In JMock, I can mock a call to a method based on its type. Notice, I'm using a subtype of Exception to be specific about what I'm expecting in my test.

context.checking(new Expectations() {{              
    oneOf(mock).method(with(any(SubTypedException.class)));
}}

and in Scalamock, I can use a wildcard to match

(mock.method(_: Exception)).expects(*).once

The following doesn't compile when I try to match on a specific subtype (I realise this doesn't make sense in Scala).

// doesn't compile    
(mock.method(_: SubTypedException)).expects(*).once

How can I convert the with(any(SubTypesException.class)) in JMock to Scalamock? I can imagine using a predicate match (where), is that the way to go?

Edit: Thinking about it, the JMock with(any(SubTypedException)) is more about keeping the compiler happy and expressing intent. As I understand it, the Matcher is an IsAnything matcher so won't actually fail a test if a different type of exception is thrown.

So, it may be asking a bit much of Scalamock to both capture the intent and fail the test under the right circumstance. Bonus points in explaining how to do something like instanceOf in Scalamock.


Source: (StackOverflow)

Scalamock: How to get "expects" for Proxy mocks?

I am using Scalamock with ScalaTest, and am trying to mock a Java interface. I currently have:

private val _iface = mock [MyInterface]

now I want to do

_iface expects `someMethod returning "foo" once

But the compiler does not find expects.

I imported org.scalatest._ and org.scalamock.scalatest._. What else am I missing?


Source: (StackOverflow)

In ScalaMock, how to return a mockClass whenever someone new an instance of a class?

In PowerMockito, we can use the pattern "whenNew(MyClass).thenReturn(mockMyClass)" when someone wants to new an instance of MyClass, it will receive mockMyClass instead of the real instance.

Can we do similar things in ScalaMock or EasyMock? I spent whole day for this issue.

This is my scenario, I have two classes A and B. Inside class A, it will new an instance of class B.

Now I want to test class A, and when class A creates a new instance of class B, what I want is to return a mock object of class B (not the real class B).

In Java, I can handle this issue easily with PowerMock and JUnit, but I cannot do it in Scala.


Source: (StackOverflow)