Using any() to stubbing before calling .thenReturn failing - scala

My first question in StackOverflow. Tried to search for answer, but I could not find any related to my problem.
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatra.test.scalatest.ScalatraFunSuite
import org.mockito.Mockito.when
import org.mockito.Matchers.any
#RunWith(classOf[JUnitRunner])
#Category(Array(classOf[DatabaseTest]))
class Test extends ScalatraFunSuite {
test("Test") {
when(pre.findProduct(any[Seq[Sone]]))
.thenReturn(Util.createProduct())
when(ft.findProduct(any()))
.thenReturn(Util.createFT())
when(interval.findSones(any()))
.thenReturn(Util.createInterval())
//The rest is code to utilise the above
}
I have the test code above written in Scala and using Mockito. Here is the error I get when I run it:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
-> at org.Test.$anonfun$new$1(Test.scala:23)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
Also, this error might show up because you use argument matchers with
methods that cannot be mocked. Following methods cannot be
stubbed/verified: final/private/equals()/hashCode(). Mocking methods
declared on non-public parent classes is not supported.
That is, both ft.findProduct(any()) and interval.findSones(any()) get the same error. A temporarily fixed has been to use a fixed integer, that is:
test("Test") {
when(pre.findProduct(any[Seq[Sone]]))
.thenReturn(Util.createProduct())
when(ft.findProduct(1)) //any() => 1
.thenReturn(Util.createFT())
when(interval.findSones(3)) //any() => 3
.thenReturn(Util.createInterval())
//The rest is code to utilise the above
}
NOTE: Also tried to use anyInt(), which gave the same error.
My question is: Is there anything wrong with my code? Hope I was able to clarify my problem.

Related

Can't create ArmeriaCatsBackend in IOApp with Cats effects?

I want to use ArmeriaCatsBackend as sttp backend with Cats effects.
The following code does not compile:
object Main extends IOApp {
val backend = ArmeriaCatsBackend[IO]()
// ...
}
could not find implicit value for evidence parameter of type cats.effect.kernel.Async[cats.effect.IO]
Error occurred in an application involving default arguments.
Documentation
What am I missing?
Dang. I was using scala-effects v2.x and sttp-ameria for v3.
After upgrading to scala-effects v3.x everything is ok.

How do make a `CustomExecutionContext` available for dependency injection in a Play 2.6 controller?

I'm following along with Play 2.6's Scala documentation and sample code for creating non-blocking actions, and am running into some runtime issues. I have created a new Play application using the Scala template (sbt new playframework/play-scala-seed.g8).
The code that the Play documentation suggests should work in a new controller is (this code is taken verbatim from the Play documentation page, with some extra imports from me):
// some imports added by me to get the code to compile
import javax.inject.Inject
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import akka.actor.ActorSystem
import play.api.libs.concurrent.CustomExecutionContext
import play.api.mvc._
import play.api.mvc.ControllerComponents
// end imports added by me
import play.api.libs.concurrent.CustomExecutionContext
trait MyExecutionContext extends ExecutionContext
class MyExecutionContextImpl #Inject()(system: ActorSystem)
extends CustomExecutionContext(system, "my.executor") with MyExecutionContext
class HomeController #Inject()(myExecutionContext: MyExecutionContext, val controllerComponents: ControllerComponents) extends BaseController {
def index = Action.async {
Future {
// Call some blocking API
Ok("result of blocking call")
}(myExecutionContext)
}
}
Then, according to the documentation for using other thread pools, I've defined the my.executor thread pool in the application.conf file of my application:
my.executor {
fork-join-executor {
parallelism-factor = 20.0
parallelism-max = 200
}
}
I should note that I do not want to use the default execution context as I want to prepare for running futures in a separate context that may be used for a limited resource like a database connection pool.
All of this compiles just fine with sbt compile. However, when I run this with sbt run and access my app in a web browser, I get this error:
CreationException: Unable to create injector, see the following errors:
1) No implementation for controllers.MyExecutionContext was bound.
while locating controllers.MyExecutionContext
for the 1st parameter of controllers.NewController.(NewController.scala:17)
while locating controllers.NewController
for the 2nd parameter of router.Routes.(Routes.scala:29)
at play.api.inject.RoutesProvider$.bindingsFromConfiguration(BuiltinModule.scala:121):
Binding(class router.Routes to self) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1)
I've used Play 2.3 in the past, and know that dependency injection works when you define an instance of an object (via #Singleton or in a module); however, Play 2.6's documentation on DI indicates that "Guice is able to automatically instantiate any class with an #Inject on its constructor without having to explicitly bind it. This feature is called just in time bindings is described in more detail in the Guice documentation."
My question is: what specific lines of code or configuration do I need to add to Play's own sample to make this work, and why?
I found one possible solution when reading further in the Binding Annotations section of the Scala Dependency Injection documentation page. In particular, it states:
The simplest way to bind an implementation to an interface is to use the Guice #ImplementedBy annotation.
So, by adding that to the my MyExecutionContext trait, like so:
import com.google.inject.ImplementedBy
#ImplementedBy(classOf[MyExecutionContextImpl])
trait MyExecutionContext extends ExecutionContext
an instance of the MyExecutionContextImpl is instantiated and properly injected into the controller.
Too bad that this #ImplementedBy annotation isn't listed in the sample code for the non-blocking action documentation!

PLAY Framework Integrating with Akka

I'm trying to get this tutorial to work but they seem to have an issue. I get an error in this piece of code:
(helloActor ? SayHello(name)).mapTo[String].map { message => Ok(message) }
not found: value SayHello
It seems that SayHello(name) is not in the scope of the Application class.
You need to import the SayHello class. Since the class is defined in the companion object of HelloActor, it is not visible by default outside that object.

lift error, method not found

I am calling this snippet
package org.palantir.snippet
import net.liftweb._
import util._
import Helpers._
import scala.xml._
object Kitchens
{
def render(html: NodeSeq) : NodeSeq = <p>test</p>
}
With this xml
<lift:Kitchens>
</lift:Kitchens>
And getting this error:
Error processing snippet: kitchens
Reason: Method Not Found
What am I missing?
This occurs because the HTML5 parser Lift uses converts all tag and attribute names to lowercase. It is recommended to use either: class="lift:Snippet" or data-lift="Snippet" to avoid that. This was not an issue with the older XHTML parser as that was case sensitive, so you will find some older documentation that invokes snippets as a tag.
You can find more information here.

Play exception: '{' expected but 'import' found

It throws me the exception for line 3. The thing is i have just these lines:
package controllers
import play.api._
import play.api.mvc._
import views._
import models._
object Application extends Controller {
def index = Ok(views.html.index("grrr", "blabla"))
}
EDIT: index.scala.html
#import helper._
#main("Todo") {
<h1>Hello World</h1>
}
I'm using play 2.2.0 on windows xp (with sbt)
I think that problem is with yours line separator in IDE. I once change LF(Linux) to CR(Mac)(by mistake, not knowing that this has an impact on compilation) and struggle with the same problem. After changing to default sperator everything back to normal.
The first line in Play! template is reserved for the signature definition. This is also mentioned in the Welcome screen when you create a new Play Application.
Beside the question why you import the helper._, I would do the following:
Make the first line empty, or at least NO import statements.
Run play clean
After this it should work, I hope :-)
Further information:
Play framework template automatically imports models._ among other things
https://github.com/playframework/playframework/blob/1acfd1dc4264e7589876fb1f4ebf37e584ab8bc6/framework/src/play/src/main/scala/views/play20/welcome.scala.html#L81
If you know a bit scala (I don't yet): https://github.com/playframework/playframework/blob/9206bea8c9c88acdc6786ebb2554f081396e8f6a/framework/src/templates-compiler/src/main/scala/play/templates/ScalaTemplateCompiler.scala
EDIT: 2013.09.24 at 22:15
You are passing two arguments to your view template (views.html.index("grrr", "blabla")), (views are compiled to functions). So in your function (`index view') the first line SHOULD define the function signature (arguments). I think that you should write your template as:
#(firstString : String, secondString : String)
#import helper._
#main("Todo") {
<h1>Hello World</h1>
}