- •Contents
- •List of Figures
- •List of Tables
- •List of Listings
- •Foreword
- •Foreword to the First Edition
- •Acknowledgments
- •Introduction
- •A Scalable Language
- •A language that grows on you
- •What makes Scala scalable?
- •Why Scala?
- •Conclusion
- •First Steps in Scala
- •Conclusion
- •Next Steps in Scala
- •Conclusion
- •Classes and Objects
- •Semicolon inference
- •Singleton objects
- •A Scala application
- •Conclusion
- •Basic Types and Operations
- •Some basic types
- •Literals
- •Operators are methods
- •Arithmetic operations
- •Relational and logical operations
- •Bitwise operations
- •Object equality
- •Operator precedence and associativity
- •Rich wrappers
- •Conclusion
- •Functional Objects
- •Checking preconditions
- •Self references
- •Auxiliary constructors
- •Method overloading
- •Implicit conversions
- •A word of caution
- •Conclusion
- •Built-in Control Structures
- •If expressions
- •While loops
- •For expressions
- •Match expressions
- •Variable scope
- •Conclusion
- •Functions and Closures
- •Methods
- •Local functions
- •Short forms of function literals
- •Placeholder syntax
- •Partially applied functions
- •Closures
- •Special function call forms
- •Tail recursion
- •Conclusion
- •Control Abstraction
- •Reducing code duplication
- •Simplifying client code
- •Currying
- •Writing new control structures
- •Conclusion
- •Composition and Inheritance
- •A two-dimensional layout library
- •Abstract classes
- •Extending classes
- •Invoking superclass constructors
- •Polymorphism and dynamic binding
- •Using composition and inheritance
- •Heighten and widen
- •Putting it all together
- •Conclusion
- •How primitives are implemented
- •Bottom types
- •Conclusion
- •Traits
- •How traits work
- •Thin versus rich interfaces
- •Example: Rectangular objects
- •The Ordered trait
- •Why not multiple inheritance?
- •To trait, or not to trait?
- •Conclusion
- •Packages and Imports
- •Putting code in packages
- •Concise access to related code
- •Imports
- •Implicit imports
- •Package objects
- •Conclusion
- •Assertions and Unit Testing
- •Assertions
- •Unit testing in Scala
- •Informative failure reports
- •Using JUnit and TestNG
- •Property-based testing
- •Organizing and running tests
- •Conclusion
- •Case Classes and Pattern Matching
- •A simple example
- •Kinds of patterns
- •Pattern guards
- •Pattern overlaps
- •Sealed classes
- •The Option type
- •Patterns everywhere
- •A larger example
- •Conclusion
- •Working with Lists
- •List literals
- •The List type
- •Constructing lists
- •Basic operations on lists
- •List patterns
- •First-order methods on class List
- •Methods of the List object
- •Processing multiple lists together
- •Conclusion
- •Collections
- •Sequences
- •Sets and maps
- •Selecting mutable versus immutable collections
- •Initializing collections
- •Tuples
- •Conclusion
- •Stateful Objects
- •What makes an object stateful?
- •Reassignable variables and properties
- •Case study: Discrete event simulation
- •A language for digital circuits
- •The Simulation API
- •Circuit Simulation
- •Conclusion
- •Type Parameterization
- •Functional queues
- •Information hiding
- •Variance annotations
- •Checking variance annotations
- •Lower bounds
- •Contravariance
- •Object private data
- •Upper bounds
- •Conclusion
- •Abstract Members
- •A quick tour of abstract members
- •Type members
- •Abstract vals
- •Abstract vars
- •Initializing abstract vals
- •Abstract types
- •Path-dependent types
- •Structural subtyping
- •Enumerations
- •Case study: Currencies
- •Conclusion
- •Implicit Conversions and Parameters
- •Implicit conversions
- •Rules for implicits
- •Implicit conversion to an expected type
- •Converting the receiver
- •Implicit parameters
- •View bounds
- •When multiple conversions apply
- •Debugging implicits
- •Conclusion
- •Implementing Lists
- •The List class in principle
- •The ListBuffer class
- •The List class in practice
- •Functional on the outside
- •Conclusion
- •For Expressions Revisited
- •For expressions
- •The n-queens problem
- •Querying with for expressions
- •Translation of for expressions
- •Going the other way
- •Conclusion
- •The Scala Collections API
- •Mutable and immutable collections
- •Collections consistency
- •Trait Traversable
- •Trait Iterable
- •Sets
- •Maps
- •Synchronized sets and maps
- •Concrete immutable collection classes
- •Concrete mutable collection classes
- •Arrays
- •Strings
- •Performance characteristics
- •Equality
- •Views
- •Iterators
- •Creating collections from scratch
- •Conversions between Java and Scala collections
- •Migrating from Scala 2.7
- •Conclusion
- •The Architecture of Scala Collections
- •Builders
- •Factoring out common operations
- •Integrating new collections
- •Conclusion
- •Extractors
- •An example: extracting email addresses
- •Extractors
- •Patterns with zero or one variables
- •Variable argument extractors
- •Extractors and sequence patterns
- •Extractors versus case classes
- •Regular expressions
- •Conclusion
- •Annotations
- •Why have annotations?
- •Syntax of annotations
- •Standard annotations
- •Conclusion
- •Working with XML
- •Semi-structured data
- •XML overview
- •XML literals
- •Serialization
- •Taking XML apart
- •Deserialization
- •Loading and saving
- •Pattern matching on XML
- •Conclusion
- •Modular Programming Using Objects
- •The problem
- •A recipe application
- •Abstraction
- •Splitting modules into traits
- •Runtime linking
- •Tracking module instances
- •Conclusion
- •Object Equality
- •Equality in Scala
- •Writing an equality method
- •Recipes for equals and hashCode
- •Conclusion
- •Combining Scala and Java
- •Using Scala from Java
- •Annotations
- •Existential types
- •Using synchronized
- •Compiling Scala and Java together
- •Conclusion
- •Actors and Concurrency
- •Trouble in paradise
- •Actors and message passing
- •Treating native threads as actors
- •Better performance through thread reuse
- •Good actors style
- •A longer example: Parallel discrete event simulation
- •Conclusion
- •Combinator Parsing
- •Example: Arithmetic expressions
- •Running your parser
- •Basic regular expression parsers
- •Another example: JSON
- •Parser output
- •Implementing combinator parsers
- •String literals and regular expressions
- •Lexing and parsing
- •Error reporting
- •Backtracking versus LL(1)
- •Conclusion
- •GUI Programming
- •Panels and layouts
- •Handling events
- •Example: Celsius/Fahrenheit converter
- •Conclusion
- •The SCells Spreadsheet
- •The visual framework
- •Disconnecting data entry and display
- •Formulas
- •Parsing formulas
- •Evaluation
- •Operation libraries
- •Change propagation
- •Conclusion
- •Scala Scripts on Unix and Windows
- •Glossary
- •Bibliography
- •About the Authors
- •Index
Section 14.4 |
Chapter 14 · Assertions and Unit Testing |
300 |
14.4 Using JUnit and TestNG
The most popular unit testing framework on the Java platform is JUnit, an open source tool written by Kent Beck and Erich Gamma. You can write JUnit tests in Scala quite easily. Here’s an example using JUnit 3.8.1:
import junit.framework.TestCase
import junit.framework.Assert.assertEquals import junit.framework.Assert.fail
import Element.elem
class ElementTestCase extends TestCase {
def testUniformElement() { val ele = elem('x', 2, 3) assertEquals(2, ele.width) assertEquals(3, ele.height) try {
elem('x', -2, 3) fail()
}
catch {
case e: IllegalArgumentException => // expected
}
}
}
Once you compile this class, JUnit will run it like any other TestCase. JUnit doesn’t care that it was written in Scala. If you wish to use ScalaTest’s assertion syntax in your JUnit 3 test, however, you can instead subclass JUnit3Suite, as shown Listing 14.5.
Trait JUnit3Suite extends TestCase, so once you compile this class, JUnit will run it just fine, even though it uses ScalaTest’s more concise assertion syntax. Moreover, because JUnit3Suite mixes in ScalaTest’s trait Suite, you can alternatively run this test class with ScalaTest’s runner. The goal is to provide a gentle migration path to enable JUnit users to start writing JUnit tests in Scala that take advantage of the conciseness afforded by Scala. ScalaTest also has a JUnitWrapperSuite, which enables you to run existing JUnit tests written in Java with ScalaTest’s runner.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 14.4 |
Chapter 14 · Assertions and Unit Testing |
301 |
import org.scalatest.junit.JUnit3Suite import Element.elem
class ElementSuite extends JUnit3Suite {
def testUniformElement() { val ele = elem('x', 2, 3) assert(ele.width === 2) expect(3) { ele.height }
intercept[IllegalArgumentException] { elem('x', -2, 3)
}
}
}
Listing 14.5 · Writing a JUnit test with JUnit3Suite.
ScalaTest offers similar integration classes for JUnit 4 and TestNG, both of which make heavy use of annotations. We’ll show an example using TestNG, an open source framework written by Cédric Beust and Alexandru Popescu. As with JUnit, you can simply write TestNG tests in Scala, compile them, and run them with TestNG’s runner. Here’s an example:
import org.testng.annotations.Test import org.testng.Assert.assertEquals import Element.elem
class ElementTests {
@Test def verifyUniformElement() { val ele = elem('x', 2, 3) assertEquals(ele.width, 2) assertEquals(ele.height, 3)
}
@Test( expectedExceptions =
Array(classOf[IllegalArgumentException])
)
def elemShouldThrowIAE() { elem('x', -2, 3) }
}
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 14.5 |
Chapter 14 · Assertions and Unit Testing |
302 |
If you prefer to use ScalaTest’s assertion syntax in your TestNG tests, however, you can extend trait TestNGSuite, as shown in Listing 14.6:
import org.scalatest.testng.TestNGSuite import org.testng.annotations.Test import Element.elem
class ElementSuite extends TestNGSuite {
@Test def verifyUniformElement() { val ele = elem('x', 2, 3) assert(ele.width === 2) expect(3) { ele.height }
intercept[IllegalArgumentException] { elem('x', -2, 3)
}
}
}
Listing 14.6 · Writing a TestNG test with TestNGSuite.
As with JUnit3Suite, you can run a TestNGSuite with either TestNG or ScalaTest, and ScalaTest also provides a TestNGWrapperSuite that enables you to run existing TestNG tests written in Java with ScalaTest. To see an example of JUnit 4 tests written in Scala, see Section 31.2.
14.5 Tests as specifications
In the behavior-driven development (BDD) testing style, the emphasis is on writing human-readable specifications of the expected behavior of code, and accompanying tests that verify the code has the specified behavior. ScalaTest includes several traits—Spec, WordSpec, FlatSpec, and FeatureSpec— which facilitate this style of testing. An example of a FlatSpec is shown in Listing 14.7.
In a FlatSpec, you write tests as specifier clauses. You start by writing a name for the subject under test as a string ("A UniformElement" in Listing 14.7), then should (or must or can), then a string that specifies a bit of behavior required of the subject, then in. In the curly braces following in, you write code that tests the specified behavior. In subsequent clauses you
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 14.5 |
Chapter 14 · Assertions and Unit Testing |
303 |
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers import Element.elem
class ElementSpec extends FlatSpec with ShouldMatchers {
"A UniformElement" should
"have a width equal to the passed value" in { val ele = elem('x', 2, 3)
ele.width should be (2)
}
it should "have a height equal to the passed value" in { val ele = elem('x', 2, 3)
ele.height should be (3)
}
it should "throw an IAE if passed a negative width" in { evaluating {
elem('x', -2, 3)
} should produce [IllegalArgumentException]
}
}
Listing 14.7 · Specifying and testing behavior with a ScalaTest FlatSpec.
can write it to refer to the most recently given subject. When a FlatSpec is executed, it will run each specifier clause as a ScalaTest test. FlatSpec (and ScalaTest’s other specification traits) generate output that reads more like a specification when run. For example, here’s what the output will look like if you run ElementSpec from Listing 14.7 in the interpreter:
scala> (new ElementSpec).execute() A UniformElement
-should have a width equal to the passed value
-should have a height equal to the passed value
-should throw an IAE if passed a negative width
Listing 14.7 also illustrates ScalaTest’s matchers DSL. By mixing in trait ShouldMatchers, you can write assertions that read more like natural language and generate more descriptive failure messages. ScalaTest pro-
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index
Section 14.5 |
Chapter 14 · Assertions and Unit Testing |
304 |
vides many matchers in its DSL, and also enables you to create your own matchers. The matchers shown in Listing 14.7 include the “should be” and “evaluating { . . . } should produce” syntax. You can alternatively mix in MustMatchers if you prefer must to should. For example, mixing in MustMatchers would allow you to write expressions such as:
result must be >= 0 array must have length 3 map must contain key 'c'
If the last assertion failed, you’d see an error message similar to:
Map('a' -> 1, 'b' -> 2) did not contain key 'c'
The specs testing framework, an open source tool written in Scala by Eric Torreborre, also supports the BDD style of testing but with a different syntax. For example, you could use specs to write the test shown in Listing 14.8:
import org.specs._ import Element.elem
object ElementSpecification extends Specification { "A UniformElement" should {
"have a width equal to the passed value" in { val ele = elem('x', 2, 3)
ele.width must be_==(2)
}
"have a height equal to the passed value" in { val ele = elem('x', 2, 3)
ele.height must be_==(3)
}
"throw an IAE if passed a negative width" in { elem('x', -2, 3) must
throwA[IllegalArgumentException]
}
}
}
Listing 14.8 · Specifying and testing behavior with the specs framework.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index