Verify order of sequence calls with Mockito - scala

I want to verify the order of sequence calls, but it didn't work as I expected.
import akka.actor.ActorSystem
import akka.testkit.TestKit
import org.scalatest._
import org.specs2.mock.Mockito
class Test extends TestKit(ActorSystem("testSystem"))
with WordSpecLike
with BeforeAndAfterAll
with PrivateMethodTester
with `enter code here`Mockito
{
val m = mock[java.util.List[String]]
m.get(0) returns "one"
there was two(m).get(2) //do not throw any error, why???
}
I'm using
scala 2.11.7,
specs2-core 3.6.6,
specs2-mock 3.6.6,
scalatest 2.2.4
thx

I don't think you can mix Specs2 and ScalaTest.
You shuld remove import org.scalatest._ and use import org.specs2.mutable.SpecificationLike instead.
import akka.testkit.TestKit
import akka.actor.ActorSystem
import org.specs2.mock.Mockito
import org.specs2.mutable.SpecificationLike
class Test extends TestKit(ActorSystem("testSystem"))
with Mockito
with SpecificationLike
{
"it" should{
"raise error" in {
val m = mock[java.util.List[String]]
m.get(0) returns "one"
there was two(m).get(2)
}
}
}
Now you can see that sbt test returns something like.
[error] The mock was not called as expected:
[error] Wanted but not invoked:
[error] list.get(2);
[error] -> at Test$$anonfun$1$$anonfun$apply$1$$anonfun$apply$3.apply(Test.scala:14)
[error] Actually, there were zero interactions with this mock. (Test.scala:14)

Related

Error: "package test is not a value" using scalatest FunSpec

I changed a test from WordMatchers to FunSpec and now can not rid the tests of the following compilation error:
class SangriaDnbIACDataPipelineTest extends FunSpec {
test("SangriaDnbIACDataPipeline") {
val args =
error: package test is not a value
[ERROR] test("SangriaDnbIACDataPipeline") {
This is on scala 2.11 with scalatest 3.0.1.
I think you're looking for the FunSuite extension:
import org.scalatest.FunSuite
class SangriaDnbIACDataPipelineTest extends FunSuite {
test("SangriaDnbIACDataPipeline") {
val args =
See the testing styles

injection error when running test with sbt

In a play 2.6.7 scala project with reactivemongo, I am having an issue.
When I run a test case through IntelliJ idea (CE)'s test runner, it runs without problems. But when I try to run the same test case from command line using sbt it fails. This means I have to run tests manually, which is a burden.
When the tests are run on sbt, the following errors are being received:
[info] controllers.SomeControllerSpec *** ABORTED ***
[info] com.google.inject.ProvisionException: Unable to provision, see the following errors:
[info]
[info] 1) No implementation for play.modules.reactivemongo.ReactiveMongoApi annotated with #play.modules.reactivemongo.NamedDatabase(value=somedatabase) was bound.
[info] while locating play.modules.reactivemongo.ReactiveMongoApi annotated with #play.modules.reactivemongo.NamedDatabase(value=somedatabase)
and 72 of the same message gets repeated. Now the question is,
i. Why does it work on IDEA?
ii. What can I do to make it work through sbt?
(I used name dependency stuff already but did not help. Anyway, the test does work on idea already!!)
Thanks.
UPDATE
Here is how the test case looks like:
package controllers
import models.Some.SomeRequest
import org.scalatestplus.play._
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.libs.json.{JsObject, JsValue, Json}
import play.api.libs.ws.WSResponse
import play.api.mvc._
import play.api.test.FakeRequest
import play.api.test.Helpers.contentAsJson
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
class SomeControllerTest extends PlaySpec with GuiceOneAppPerSuite{
implicit val timeout: akka.util.Timeout = 5.seconds
val controller = app.injector.instanceOf(classOf[SomeController])
"Some test" should {
"be successful for valid request" in {
val someValidReq:JsValue = Json.toJson(
SomeRequest(param1 = "value1",
param2 = "value2")
).as[JsValue]
val result: Future[Result] = controller.someMethod.apply(FakeRequest("POST", "/endpoint")
.withJsonBody(someValidReq))
println("test req: "+someValidReq)
val respJson = contentAsJson(result)
respJson.as[JsObject].value("msg").as[String] mustBe ("Successfully completed")
}
}
}
I can run the above test through the Run menu of IntelliJ IDEA.
However, I can't run the test by using sbt, as the following fails:
sbt testOnly controllers.SomeControllerTest

Failed assertion with automated initialisation of database in Cassandra

Completely new to Cassandra. Tried to initialize a database in Cassandra using phantom-dsl. I received this error message.
*** RUN ABORTED ***
java.lang.AssertionError: assertion failed: no symbol could be loaded from class com.datastax.driver.core.Cluster in package core with name Cluster and classloader sun.misc.Launcher$AppClassLoader#279f2327
at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$classToScala1(JavaMirrors.scala:1021)
at scala.reflect.runtime.JavaMirrors$JavaMirror$$anonfun$classToScala$1.apply(JavaMirrors.scala:980)
at scala.reflect.runtime.JavaMirrors$JavaMirror$$anonfun$classToScala$1.apply(JavaMirrors.scala:980)
at scala.reflect.runtime.JavaMirrors$JavaMirror$$anonfun$toScala$1.apply(JavaMirrors.scala:97)
at scala.reflect.runtime.TwoWayCaches$TwoWayCache$$anonfun$toScala$1.apply(TwoWayCaches.scala:39)
at scala.reflect.runtime.Gil$class.gilSynchronized(Gil.scala:19)
at scala.reflect.runtime.JavaUniverse.gilSynchronized(JavaUniverse.scala:16)
at scala.reflect.runtime.TwoWayCaches$TwoWayCache.toScala(TwoWayCaches.scala:34)
at scala.reflect.runtime.JavaMirrors$JavaMirror.toScala(JavaMirrors.scala:95)
at scala.reflect.runtime.JavaMirrors$JavaMirror.classToScala(JavaMirrors.scala:980)
I am not really sure whether it is an issue with the Connector in phantom-dsl or the ClusterBuilder in datastax-driver.
Connector.scala
package com.neruti.db
import com.neruti.db.models._
import com.websudos.phantom.database.Database
import com.websudos.phantom.connectors.ContactPoints
import com.websudos.phantom.dsl.KeySpaceDef
object Connector {
val host= Seq("localhost")
val port = 9160
val keySpace: String = "nrt_entities"
// val inet = InetAddress.getByName
lazy val connector = ContactPoints(host,port).withClusterBuilder(
_.withCredentials("cassandra", "cassandra")
).keySpace(keySpace)
}
CassandraSpec.scala
package com.neruti.db
import com.neruti.User
import com.neruti.db.models._
import com.neruti.db.databases._
import com.neruti.db.services._
import com.neruti.db.Connector._
import java.util.UUID
import com.datastax.driver.core.ResultSet
import org.scalatest._
import org.scalatest.{BeforeAndAfterAll,FlatSpec,Matchers,ShouldMatchers}
import org.scalatest.concurrent.ScalaFutures
import org.scalamock.scalatest.MockFactory
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
abstract class BaseCassandraSpec extends FlatSpec
with BeforeAndAfterAll
with Inspectors
with Matchers
with OptionValues
with ScalaFutures
class CassandraTest extends BaseCassandraSpec
with ProductionDatabase
with UserService
with Connector.connector.Connector{
val user = User(
Some("foobar"),
Some("foo#foobar.com"),
Some(UUID.randomUUID()),
)
override protected def beforeAll(): Unit = {
Await.result(database.userModel.create(user),10.seconds)
}
}
Looks there may be multiple issues you are looking at:
The latest version of phantom is 2.1.3, I'd strongly recommend using that, especially if you are just starting out. The migration guide is here in case you need it.
The entire reflection mechanism has been replaced in the latest version, so that error should magically go away. With respect to testing and generating objects, I would also look to include com.outworkers.util.testing, which is freely available on Maven Central
libraryDependencies ++= Seq(
//..,
"com.outworkers" %% "phantom-dsl" % "2.1.3",
"com.outworkers" %% "util-testing" % "0.30.1" % Test
)
This will offer you automated case class generation:
import com.outworkers.util.testing._
val sample = gen[User]

`eventually` not found in scala.rx

Here is an example from the scala.rx doc:
package tutorial.webapp
import rx.core.{Rx, Var}
import rx._
import rx.ops._
import scala.concurrent.Promise
import scala.concurrent.duration._
import scala.scalajs.js.JSApp
import scala.scalajs.js.annotation.JSExport
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Created by IDEA on 29/10/15.
*/
object RxAddtionalOps extends JSApp {
#JSExport
override def main(): Unit = {
mapDemo
filterDemo
asyncDemo
async2
timer1
}
def delay1: Unit = {
val a = Var(10)
val b = a.delay(250 millis)
a() = 5
println(b())
eventually{
println(b)
}
}
}
I got this error on sbt when compiling:
[error] /Users/kaiyin/personal_config_bin_files/workspace/scalajsHandson/src/main/scala/tutorial/webapp/RxAddtionalOps.scala:43: not found: value eventually
[error] eventually{
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed 30 oct. 2015 11:15:07
Where does the eventually function come from? Am I missing any imports?
It's defined in utest, which is a author's framework for tests. Since it's a test dependency it doesn't come bundled with scalarx. BTW, the very same functionality presented in scalatest.

value not found in akka Producer-Consumer with actor

i am following a tutorial to create a Producer Consumer with actors
i made three files i.e Master.scala, Counter.scala and Parser.scala
i am getting not found value in two of my files(Counter.scala and Parser.scala)
Parser.scala
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor._
case object Processed
class Parser(counter: ActorRef) extends Actor {
val pages=Pages(100000, "enwiki.xml")
override def preStart{
for(page<-pages.take(10))
counter ! page
}
def receive={
case Processed if pages.hasNext => counter ! pages.next
case _ => context.stop(self)
}
}
Counter.scala
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor._
class Counter extends Actor {
val counts = HashMap[String,Int]().withDefaultValue(0)
def receive={
case Page(title, text)=>
for (word<-Words(text))
counts(word) += 1
sender ! Processed
}
}
Errors
[error] /home/ahsen/SbtPrctc/ProducerConsumer/src/main/scala/Counter.scala:6: not found: value HashMap
[error] val counts = HashMapString,Int.withDefaultValue(0)
[error] ^
[error] /home/ahsen/SbtPrctc/ProducerConsumer/src/main/scala/Counter.scala:8: not found: value Page
[error] case Page(title, text)=>
[error] ^
[error] /home/ahsen/SbtPrctc/ProducerConsumer/src/main/scala/Counter.scala:9: not found: value Words
[error] for (word<-Words(text))
[error] ^
[error] /home/ahsen/SbtPrctc/ProducerConsumer/src/main/scala/Parser.scala:7: not found: value Pages
[error] val pages=Pages(100000, "enwiki.xml")
[error] ^
i am sure i am doing some stupid mistake bt please help me out
If you want to use the Java HashMap you need to import java.util.HashMap. However, I believe in your case you want to use the Scala scala.collections.mutable.Map (which you also need to import, and change HashMap to Map).
Also, please properly indent your code in your questions, and also mark the stack traces as code. It makes it much easier for respondents to read your questions.