i am trying to run a simple ScalaTest app to understand the scala testing
my code is:
package org.scalatest.examples.flatspec
import org.scalatest.FlatSpec
import collection.mutable.Stack
import org.scalatest._
class ExampleSpec extends FlatSpec with Matchers {
"A Stack" should "pop values in last-in-first-out order" in {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
stack.pop() should be (2)
stack.pop() should be (1)
}
it should "throw NoSuchElementException if an empty stack is popped" in {
val emptyStack = new Stack[Int]
a [NoSuchElementException] should be thrownBy {
emptyStack.pop()
}
}
}
i have also downloaded scalatest_2.11-2.2.4.jar. i am compiling the file using command
scalac -cp scalatest_2.11-2.2.4.jar ExampleSpec.scala
and facing the following error
error while loading package, class file needed by package is missing.
reference value <init>$default$2 of object deprecated refers to nonexisting symbol.
Related
I am running test for this scala code using junit
//Scala Code
package com.sd.proj.executable
object HelloWorld {
def my_message(msg:String):String ={
msg
}
}
//Scala Test
package com.sd.proj.junit_test
import org.junit.runner.RunWith
import org.scalatestplus.junit.JUnitRunner
import com.sd.proj.executable.HelloWorld
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.must.Matchers
#RunWith(classOf[JUnitRunner])
class HelloWorldTest extends AnyFlatSpec with Matchers {
val msg = HelloWorld.my_message("Hello World!!!")
println("testing - " + msg)
msg mustBe "Hello World!!!"
}
The test is executing correctly, however it does not show the green tick for the test, just shows this
this is my build.gradle file
plugins {
id 'scala'
id 'idea'
}
repositories {
mavenCentral()
}
sourceSets{
main{
scala.srcDirs = ['src/main/scala']
resources.srcDirs = ['src/main/resources']
}
test{
scala.srcDirs = ['src/test/scala']
resources.srcDirs = ['src/test/resources']
}
}
dependencies {
//scala
implementation 'org.scala-lang:scala-library:2.12.15'
implementation 'org.scala-lang:scala-reflect:2.12.15'
implementation 'org.scala-lang:scala-compiler:2.12.15'
//junit
testImplementation 'junit:junit:4.12'
testImplementation 'org.scalatestplus:scalatestplus-junit_2.12:1.0.0-M2'
}
Intellij version - IntelliJ IDEA 2021.3.1 (Community Edition)
OS : macOS ventura 13.0
This is the first time I am setting up IntelliJ to run code on my mac.
Can someone please suggest, is it something I am doing incorrectly or is this an issue with Intellij?
I was expecting a green tick for the passed test on intellij
Nevermind, found the solution.
I was writing the test incorrectly, it should be
#RunWith(classOf[JUnitRunner])
class HelloWorldTest extends AnyFlatSpec with Matchers {
"hello world" should "return" in {
val msg = HelloWorld.my_message("Hello World!!!")
println("testing - " + msg)
msg mustBe "Hello World!!!"
}
}
How to get the package of methods or objects in Scala?
For example
import scala.math._
round().getClass // errors
Is there a way to get the desired output: "scala.math.round"? So that I can be sure of round() method doesn't come from any other package I've imported.
PS. Without using Intellij IDE. The IDE shows you this info, hence there has to be a function that IDE calls to get this info.
EDIT:
For example, running these commands in scala shell
With Scala reflection (libraryDependencies += scalaOrganization.value % "scala-reflect" % scalaVersion.value in build.sbt) you can do
import scala.math._
import scala.reflect.runtime.universe._
object App {
def main(args: Array[String]): Unit = {
println(
showRaw(reify {
round(???)
})
)
}
}
Output at runtime will be
Expr(Apply(Select(Ident(scala.math.package), TermName("round")), List(Select(Ident(scala.Predef), TermName("$qmark$qmark$qmark")))))
Or you can add scalacOptions in Compile ++= Seq("-Xprint-types", "-Xprint:typer") to build.sbt.
Then compilation of
package pckg
import scala.math._
object App {
round(???)
}
will produce (at compile time)
Warning:scalac: package pckg{pckg.type} {
import scala.math._;
object App extends scala.AnyRef {
def <init>(): pckg.App.type = {
App.super{pckg.App.type}.<init>{()Object}(){Object};
(){Unit}
}{Unit};
scala.math.`package`.round{(x: Long)Long}(scala.Predef.???{Nothing}){Long}
}
}
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
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)
I trying to send an email from scala Play framework 2.4 while using play-mailer, I have followed the instruction from their sample page but with no success.
I have added the dependency to build.sbt:
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-mailer" % "3.0.1"
)
In application.conf the I have added the following:
play.mailer {
host=smtp.gmail.com
port=465
ssl=true
tls=true
user="testme#gmail.com"
password=abracadabra
}
And finally, the Mailing Class:
package controllers
import java.io.File
import javax.inject.Inject
import org.apache.commons.mail.EmailAttachment
import play.api.Configuration
import play.api.Play.current
import play.api.libs.mailer._
class Mail(mailer: MailerClient) {
def send = {
val cid = "1234"
val email = Email(
"Simple email",
"Mister FROM <from#email.com>",
Seq("Miss TO <to#email.com>"),
bodyText = Some("A text message"),
bodyHtml = Some("some data....")
)
mailer.send(email)
}
}
So far without compilation errors, however I don't understand how to initialize this class.. how should I get the "MailerClient" instance?
In the documentation it is written "Then in your router definition, use the trait MailerComponents", with the following code example:
import play.api._
import play.api.ApplicationLoader.Context
import router.Routes
import play.api.libs.mailer._
class MyApplicationLoader extends ApplicationLoader {
def load(context: Context) = {
new ApplicationComponents(context).application
}
}
class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with MailerComponents {
lazy val myComponent = new MyComponent(mailerClient)
// create your controllers here ...
lazy val router = new Routes(...) // inject your controllers here
}
(I have added "play.application.loader=SimpleApplicationLoader" in application.conf)
but I get the following compilation errors:
D:\myApp\app\SimpleApplicationLoader.scala:12: not found: type MailerComponents
[error] class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with MailerComponents {
[error] ^
[error] D:\myApp\app\SimpleApplicationLoader.scala:13: not found: value mailerClient
[error] lazy val applicationController = new controllers.Mail(mailerClient)
[error] ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed
Any ideas?
You can go with the run-time dependency injection, as the other answer has suggested. But if you want to go with your current approach, read on...
The problem is, the MailerComponents trait doesn't exist in the 3.x branch. it does seem to exist in the master branch, but not in their next branch. I am not sure what they are doing there.
If you want to continue with the example, you'll need to do a bit of fiddling and figure out how to make it compile. For ex. with a bit of looking around, I came up with the following.
import play.api._
import play.api.ApplicationLoader.Context
import router.Routes
import play.api.libs.mailer._
class SimpleApplicationLoader extends ApplicationLoader {
def load(context: Context) = {
new ApplicationComponents(context).application
}
}
class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) {
val mailerClient = new CommonsMailer(configuration)
lazy val applicationController = new controllers.ApplicationScala(mailerClient)
lazy val assets = new controllers.Assets(httpErrorHandler)
lazy val router = new Routes(httpErrorHandler, applicationController)
}
Basically, instead of relying on the non-existent MailerComponent to create a mailerClient for me, I just did it myself.
If you have the following line in controllers.ApplicationScala
val id = mailer.configure(Configuration.from(Map("host" -> "typesafe.org", "port" -> 1234))).send(email)
Replace it with:
val id = mailer.send(email)
And it will compile. Meanwhile, I think I should raise an issue on github about this. And maybe you should.
I believe you could simply let play framework inject the mail client. Setting up the configuration and annotating your constructor with #Inject() should work.
Declaration of your Mail controller would look like this:
class Mail #Inject() (mailer: MailerClient) {