Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
We went through online material such as scalatest site. What are advantages of using scala testing framework Specs2? How does it add to the project over JUnit?
I'm a little reluctant to answer this because it's a quite subjective thing.
But I could summarise it as "In the same way Scala gives you new and cleaner ways to solve problems over Java, Specs2 gives you new and cleaner ways to test over JUnit".
Some quick examples:
Mockito is a first-class citizen
Mockito is my favourite JVM mocking library; using it with Specs2 is as simple as mixing in a trait and you get a nice DSL for verification:
class MySpec extends Specification with Mockito {
// Setup:
val mockConnection = mock[Connection]
...
// Verification: (in a test)
there was one(mockConnection).get("www.google.com")
}
ScalaCheck is a first-class citizen
ScalaCheck can save a heap of time "fuzzing" inputs to your functions, and again, a simple trait mixin gets you all of its power within your Specs2 tests.
Run a test in a Scope
Ever had a problem where tests would work on your machine but break elsewhere, because your machine ran them in a certain order? Or got into "mocking hell" due to interactions between stubbed collaborator behaviour? Specs2 lets you put the entire test into a Scope to contain all of that state and stop it from leaking into other tests:
class AnotherSpec extends Specification with Mockito {
class FooScope extends Scope {
val mockResponse = mock[Response]
val mockConnection = mock[Connection]
...
mockConnection.execute returns mockResponse
def frobulate(s:String) = {
// Use mockResponse, mockConnection, etc ...
}
}
"My thing" should {
"Do stuff" in new FooScope {
frobulate("hello")
there was one(mockConnection).post(...)
}
}
Scopes help you DRY up your tests as well as stop state leaks between them.
Plus
"Blocks" to group related tests ("My thing" should)
Readable, space-separated test names ("throw an exception if argument < 0" in)
Readable DSL for matching (result must have length(7))
Matchers for Scala-idiomatic types (result must beNone)
Easily temporarily disable a test with pending
Generate HTML reports/output with a DSL
Downsides
In an attempt to make this answer slightly more objective, I should also point out this article by the esteemed Bill Venners about compile time which points out that a Specs2 mutable.Specification, due to large numbers of implicits and function declarations, is almost an order-of-magnitude slower to compile than a roughly-equivalent JUnit test. It also does not scale well over large numbers of tests. Or at least it didn't when the article was written in early 2013. There are now approaches you can use to address this.
Related
I am going through the coursera functional programming and have an assignment where the scalatest is written using FunSuite and Checkers.
This test framework is new to me but I have some basic idea of using assertion, as I have developed pigunit for an user defined function using assert.
As google didn't give me clear usage of Checkers and how it is different from assert, could anyone clarify where Checkers can be used and why not assert be used.
Thanks
As you know, an assertion is a way of testing that a certain condition holds. These are pretty simple in ScalaTest, as you only need to use assert. For example:
assert(List(1, 2, 3).length == 3)
"Checkers," or, as they are more often called, properties, are a bit different. They are a way to assert that a condition holds for all possible inputs instead of for a single case. For example, here is a property that tests that a list always has a nonnegative length:
check((ls: List[Int]) => ls.length >= 0)
At this point, ScalaTest defers to ScalaCheck to do the heavy lifting. ScalaCheck generates random values for ls in an effort to find one that fails the test. This concept is called property-based testing. You can read more about how to use it in ScalaTest here.
I am learning how to do unit tests with scalatest , but I have some basic questions as I am learning Scala/Scalatest
I wrote one scala script which has one scala object with several methods. My question is as follows: Should I write one unit test for the whole Scala object or should I write a test per function.
For example I wrote the following function :
Do you know how to write a test with scala test for this specific function:
def dataProcessing (input: List[String]) = {
val Data = input.map(_.trim).filter(x => !(x contains "$")).filter(line => Seq("11", "18").exists(s => line.contains(s))).map(elt => elt.replaceAll("""[\t\p{Zs}\.\$]+""", " ")).map(_.split("\\s+")).map(x => (x(1),x(1),x(3),dataLength(x(3)),dataType(x(3))))
return Data
}
Finally I am trying to use the test driven design best practices but still don't know how to proceed to write tests before writing code , Any tips how to proceed to be compliant with these practices.
Many thanks
In general, when you define a class or object, you should write tests for the methods someone using that class should call, and the other methods should be private. If you find yourself wanting to make methods public, just so they can be tested, consider moving them to a separate class or object.
There are a lot of testing styles supported by scala test. Personally, I like WordSpec. A basic test in progress would look like this:
class MyTest extends WordSpec with Matchers {
"My Object" should {
"process descriptors" when {
"there is one input" in {
val input = List("2010 Ford Mustang")
val output = MyObject.descriptorProcessing(input)
output should have length 1
output.head shouldBe()
}
"there are two inputs" in pendingUntilFixed {
val input = List("Abraham Joe Lincoln, 34, President",
"George Ronald Washington, 29, President")
val output = MyObject.descriptorProcessing(input)
output should have length 2
output.head shouldBe()
}
}
"format descriptors" when {
"there is one input" in pending
}
}
}
I've used two features of scalatest that enable TDD, pendingUntilFixed and pending.
pendingUntilFixed lets you write a test for code that hasn't been implemented yet, or isn't working correctly yet. As long an assertion in the test fails, the test is ignored and displayed in yellow output. Once all the assertions pass, the test fails, letting you know that you can turn it on. This enables TDD, while allowing your build to pass before work is completed.
pending is a marker saying "I'm going to write a test for this, but I haven't gotten to it yet". I use this a lot, as it allows me to write an outline for my tests, then go back and fill them in.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Going through various Scala related material, term DSL is used at many places.
Google search tells it is Domain specific language.
What exactly it means, and why is it that this term doesn't comes across while learning other languages like Java?
As others have pointed out, the first part of the question ("what is a DSL?") is essentially answered by What is a DSL and where should I use it?
I'll try to answer instead to the second part: why are DSLs so popular in Scala?
The reason is that Scala (as opposed to other languages like Java) offers many syntactic facilities to provide DSLs.
For example, Scala has infix method applications:
someObject.someMethod(someArgument)
// can be written as
someObject someMethod someArgument
This makes introducing custom "operators" very easy in the language. A notable example is the akka DSL for sending messages to an actor:
actor ! message
which is a DSL mimicking the syntax of Erlang.
Another example of a syntactic facility in Scala is the "trailing block argument" (not sure it has a precise name):
def someMethod(x: Int)(y: String) = ???
// can be invoked as
someMethod(42)("foo")
// but also as
someMethod(42) { "foo" }
which is very interesting when the last parameter is a function:
def someOtherMethod[A, B](x: A)(f: A => B): B = ???
someOtherMethod(42) { a =>
// ...a very long body
}
In other languages, blocks ({ ... }) are usually reserved to built-in control-flow structures (such as if, while, for, etc), but in Scala you can use this syntactic facility to build custom methods that resemble built-in control structures.
Those two features alone are distinctive enough for explaining why DSL are so pervasive in the Scala community.
Digging a bit deeper, we can also mention implicit conversions, which allow to add custom methods to any existing type. For example
implicit class TimesOps(x: Int) {
def times(y: Int): Int = x * y
}
// then use as
2 times 4 // 8
This example combines the use of infix method application and implicit conversions.
I am reading online about cross cutting concerns since I just implemented Log4j into my code. Some people are saying using AspectJ is okay, while others point out that it breaks functional programming. That mixins are Scala's solution for cross cutting concerns.
However, I cringe when I think I will extend a trait to an object/ class that is not related itself.
e.g. new Database with Logger
Here Logger has nothing to do with Database, but its how to mixing to provide logging. I would prefer to do it the Scala way, so I want to find out this is what people mean by mixins.
Can someone please show me a quick example of how to go about this in Scala?
This is a big topic with lots of potential "correct" answers. My personal favourite would be using either "by name parameters" or higher order functions.
A a very simple example of this:
object Logging {
def logCall[T](name: String)(block: => T): T = {
log.info(s"Invoking: $name")
block
}
}
Which would allow you to apply it both in an object that itself knows about the cross cutting concern (something like annotating wrapping a method call with something in java):
class DB {
import Logging._
def insert(item: Something) = logCall("insert") {
???
}
}
Or at the call site:
import Logging._
def businessLogic() {
val user = ???
val result = logCall("insert user")(DB.insert(user))
println(result)
}
The nice thing with this is that it is very explicit and self explanatory (which, again, are things you might value high or not).
Specs2 promotes functional style when dealing with Acceptance specification (even Unit specification if we want).
Risks of using old style (mutable style) are mentioned in the spec Specs2 philosophy and concernes potential unwanted side-effects:
The important things to know are:
side-effects are only used to build the specification fragments, by
mutating a variable they are also used to short-circuit the execution
of an example as soon as there is a failure (by throwing an exception).
If you build fragments in the body of examples or execute the same
specification concurrently, the sky should fall down. "context"
management is to be done with case classes or traits (see
org.specs2.examples.MutableSpec)
I don't figure out how a same specification could be run concurrently since each specification is distinct from the other (separated class's instances), even if we run the same twice or more simultaneously.
Indeed, specFragments (mutable variable):
protected[mutable] var specFragments: Fragments = new Fragments()
is declared in a trait called FragmentBuilder, not in an object(in scala sense => singleton) or other shared thing..., so specFragments is a local variable to each Specification's instance.
So what might a scenario be risking concurrency mechanism?
I don't really figure out a true scenario (non-stupid) proving the benefit of Specs2 functional style.
The issues with mutable specification can only be seen when the specification is being built, not when it is executed. When building a mutable specification it's easy to have unexpected side-effect
import org.specs2._
val spec = new mutable.Specification {
"example" >> ok
}
import spec._
def addTitle {
// WHOOPS, forgot to remove this line!
// test, add also an example
"this is only for testing" >> ok
"new title".title
}
addTitle
And the output is:
new title
+ example
+ this is only for testing
Total for specification new title
Finished in 0 ms
2 examples, 0 failure, 0 error
So, you're right, the highlighted sentence in the guide ("execute the same specification concurrently") is ambiguous. The construction of the specification itself might be unsafe if several threads were building the same specification object but not if they were running it (the whole process being called "execute" in that sentence).
Your other question is: what are the benefits of the "functional style"? The main benefit, from a user point of view, is that it is another style of writing specifications where all the text comes first and all the code is put elsewhere.
In conclusion, do not fear the mutable style of Specification if you like it!