EzDevInfo.com

scalatest

A testing tool for Scala and Java developers

What’s the difference between ScalaTest and Scala Specs unit test frameworks?

Both are BDD (Behavior Driven Development) capable unit test frameworks for Scala written in Scala. And Specs is built upon may also involve the ScalaTest framework. But what does Specs offer ScalaTest doesn't? What are the differences?


Source: (StackOverflow)

How to do an instanceof check with Scala(Test)

I'm trying to incorporate ScalaTest into my Java project, replacing all JUnit tests by ScalaTests. At one point, I want to check if Guice's Injector injects the correct type. In Java, I have a test like this:

public class InjectorBehaviour {
    @Test
    public void shouldInjectCorrectTypes() {
        Injector injector = Guice.createInjector(new ModuleImpl());
        House house = injector.getInstance(House.class);

        assertTrue(house.door() instanceof WoodenDoor);
        assertTrue(house.window() instanceof BambooWindow);
        assertTrue(house.roof() instanceof SlateRoof);
    }
}

But I have a problem doing the same with ScalaTest:

class InjectorSpec extends Spec {
    describe("An injector") {
        it("should inject the correct types") {
            val injector = Guice.createInjector(new ModuleImpl)
            val house = injector.getInstance(classOf[House])

            assert(house.door instanceof WoodenDoor)
            assert(house.window instanceof BambooWindow)
            assert(house.roof instanceof SlateRoof)
        }
    }
}

It complaints that the value instanceof is not a member of Door/Window/Roof. Can't I use instanceof that way in Scala?


Source: (StackOverflow)

Advertisements

How to show custom failure messages in ScalaTest?

Does anyone know how to show a custom failure message in ScalaTest?

For example:

NumberOfElements() should equal (5)

Shows the following message when it fails:

10 did not equal 5

But i want more descriptive message like:

NumberOfElements should be 5.


Source: (StackOverflow)

ScalaTest in sbt: is there a way to run a single test without tags?

I know that a single test can be ran by running, in sbt,

test-only *class -- -n Tag

Is there a way of telling sbt/scalatest to run a single test without tags? For example:

test-only *class -- -X 2

it would mean "run the second test in the class. Whatever it is". We have a bunch of tests and no one bothered to tag them, so is there a way to run a single test without it having a tag?

Thanks!


Source: (StackOverflow)

Testing Actors in Akka

When i run base example for testing actors:

class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpec with MustMatchers with BeforeAndAfterAll {

I got error:

class WordSpec needs to be a trait to be mixed in

what am I doing wrong?


Source: (StackOverflow)

Doing something before or after all Scalatest tests

I have a suite of scalatest tests that test different endpoints of a RESTful API. I really want them separated into different files for best organization.

My problem is how to start something (an HTTP server in my case, but it doesn't matter what it is) before all the tests and shut it down after all the tests are done.

I know about BeforeAndAfterAll, but that only accomplishes before/after inside one test file. I need something like that, but for all tests, for example:

-- start http server before tests
-- run all test suites
-- shut down http server


Source: (StackOverflow)

scala === operator in scala koans

I started working my way through the Scala Koans, which is organized around a suite of unit tests with blanks that one needs to fill in. (This idea was modeled after a similar Ruby Koans project.) You start the sbt tool running a test, and it admonishes:

[info]   + ***************************************** 
[info]   +  
[info]   +  
[info]   +  
[info]   + Please meditate on koan "None equals None" of suite "AboutEmptyValues" 
[info]   +  
[info]   +  
[info]   +  
[info]   + ***************************************** 

...and so you go look at this unit test and it says:

  test("None equals None") {
    assert(None === __)
  }

...and, after meditation, you realize that you should fill in the blank like this:

  test("None equals None") {
    assert(None === None)
  }

...and then it moves on to the next unit test.

My question, though is what is this === operator? I can't seem to find it anywhere. Is this a DSL operator defined in the Scala Koans project itself? Or is it part of the ScalaTest framework? Or in Scala proper?


Source: (StackOverflow)

How to get scalatest to populate test runtimes in the xml report

We use ScalaTest to run tests and display the results in Jenkins. It works great, but for some reason Scalatest does not populate the test runtime.

I'm adding test options like this:

    Tests.Argument("-oD", "-u", "target/test-reports")

But the XML file does not have timings (see time is always 0):

<testcase classname="beekeeper.warehouse.jdbc.JDBCWarehouseTest" name="testListTables" time="0.0">
</testcase>
<testcase classname="beekeeper.warehouse.jdbc.JDBCWarehouseTest" name="testGetDatabases" time="0.0">
</testcase>
<testcase classname="beekeeper.warehouse.jdbc.JDBCWarehouseTest" name="testSchema" time="0.0">
</testcase>

Do I need to do something else to have it report this, or is it not supported?

Thanks for any help


Source: (StackOverflow)

Comparing collection contents with ScalaTest

I'm trying to unit-test some Scala that is very collection-heavy. These collections are returned as Iterable[T], so I am interested in the contents of the collection, even if the underlying types differ. This is actually two related problems:

  1. How do I assert that two ordered collections contain the same sequence of elements?
  2. How do I assert that two unordered collections contain the same set of elements?

In summary, I'm looking the Scala-equivalent of NUnit's CollectionAssert.AreEqual (ordered) and CollectionAssert.AreEquivalent (unordered) in ScalaTest:

Set(1, 2) should equal (List(1, 2))          // ordered, pass
Iterable(2, 1) should equal (Iterable(1, 2)) // unordered, pass

Source: (StackOverflow)

ScalaTest: Assert exceptions in failed futures (non-blocking)

import org.scalatest.{ FlatSpec, Matchers, ParallelTestExecution }
import org.scalatest.concurrent.ScalaFutures
import org.apache.thrift.TApplicationException

class Test extends FlatSpec with Matchers with ScalaFutures with ParallelTestExecution {
  it should "throw org.apache.thrift.TApplicationException for invalid Ids" in {
    val future: Future[Response] = ThriftClient.thriftRequest
    whenReady(future) {
      res => {
       intercept[TApplicationException] {
       }
      }
    }
  }
}

Question: How do you assert expected failures in Futures without blocking? The above doesn't work, the exception is thrown before the intercept block.


Source: (StackOverflow)

Unit testing several implementation of the same trait/interface

I program mostly in scala and java, using scalatest in scala and junit for unit testing. I would like to apply the very same tests to several implementations of the same interface/trait. The idea is to verify that the interface contract is enforced and to check Liskov substitution principle.

For instance, when testing implementations of lists, tests could include:

  • An instance should be empty, if and only if and only if it has zero size.
  • After calling clear, the size sould be zero.
  • Adding an element in the middle of a list, will increment by one the index of rhs elements.
  • etc.

What are the best practices ?


Source: (StackOverflow)

How do I get Scalatest into Eclipse?

I have the Typesafe stack installed, including ScalaTest for Scala IDE 0.9.3. I cannot figure out how to attach it to a new project. I have other projects (from the Coursera Scala course that I just took) that use it, but I cannot use it in a new project. Importing org.scalatest._ just tells me that "object scalatest is not a member of package org." The Coursera projects have a "Referenced Libraries" element that I don't know how to reproduce. I could copy the "lib_managed" folder into a new project, but that doesn't help.

There must be an easier way to start a new project that uses Scalatest?


Source: (StackOverflow)

How to configure sbt test / ScalaTest to only show failures?

Is there a way to truncate the test results to only show result text for unit tests only when the unit test has failed? I'm working on a Scala project that has 850 unit tests, and the green text from the successful unit tests makes it difficult to focus on just the failures.

Example of what I'm talking about:

[info] - should have colors
[info] - should not be dead
//.... x 100
[info] - animals should not be rainbows *** FAILED *** 
[info] -"[rainbow]s" was not equal to "[ponie]s" (HappinessSpec.scala:31)

What I would like is something that just shows the failure(s):

[info] - animals should not be rainbows *** FAILED *** 
[info] -"[rainbow]s" was not equal to "[ponie]s" (HappinessSpec.scala:31)

I realize there is the test-quick sbt command, but it's still running 300 successful unit tests in my case when there are only 30 failures.

Something along the lines of this in terms of usage is what I'm looking for:

sbt> ~ test -showOnlyFailures

I would also be happy with something that shows all of the failures at the end of running the unit tests. IIRC, this is how RSpec works in Ruby...


Source: (StackOverflow)

Run ScalaTest tests in parallel

Given the following test suite:

class ParallelizeMe extends FunSuite with BeforeAndAfterAll {

  override def beforeAll() = println("before")              
  override def afterAll()  = println("after")               

  test("test 1") {                                          
    println("1a")
    Thread.sleep(3000)                                      
    println("1b")                                           
  }

  test("test 2") {                                          
    println("2a")
    Thread.sleep(1000)                                      
    println("2b")
  }

} 

How can I run the tests (via sbt) in parallel? Ideally, I want the order of execution to produce the following on stdout:

before
1a
2a
2b
1b
after

Source: (StackOverflow)

How can a private class method be tested in Scala?

I have a companion object with a private method, like so:

package com.example.people

class Person(val age: Int)

object Person {
  private def transform(p: Person): Person = new Person(p.age + 1)
}

I would like to test this method, with something like:

class PersonSpec extends FlatSpec {

  "A Person" should "transform correctly" in {
    val p1 = new Person(1)
    val p2 = Person.transform(p1) // doesn't compile, because transform is private!
    assert( p2 === new Person(2) )
  }

}

Any help on having test code access private methods?

Actually, as it is written, I might be able to create a subclass of Person, but what if Person is declared as final or sealed?

Thanks!


Source: (StackOverflow)