ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 02.01.2026

Просмотров: 3436

Скачиваний: 0

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

Section 14.2

Chapter 14 · Assertions and Unit Testing

297

Assertions (and ensuring checks) can be enabled and disabled using the JVM’s -ea and -da command-line flags. When enabled, each assertion serves as a little test that uses the actual data encountered as the software runs. In the remainder of this chapter, we’ll focus on the writing of external unit tests, which provide their own test data and run independently from the application.

14.2 Unit testing in Scala

You have many options for unit testing in Scala, from established Java tools, such as JUnit and TestNG, to new tools written in Scala, such as ScalaTest, specs, and ScalaCheck. In the remainder of this chapter, we’ll give you a quick tour of these tools. We’ll start with ScalaTest.

ScalaTest provides several ways to write tests, the simplest of which is to create classes that extend org.scalatest.Suite and define test methods in those classes. A Suite represents a suite of tests. Test methods start with "test". Listing 14.3 shows an example:

import org.scalatest.Suite import Element.elem

class ElementSuite extends Suite {

def testUniformElement() { val ele = elem('x', 2, 3) assert(ele.width == 2)

}

}

Listing 14.3 · Writing a test method with Suite.

Although ScalaTest includes a Runner application, you can also run a Suite directly from the Scala interpreter by invoking execute on it. Trait Suite’s execute method uses reflection to discover its test methods and invokes them. Here’s an example:

scala> (new ElementSuite).execute()

Test Starting - ElementSuite.testUniformElement Test Succeeded - ElementSuite.testUniformElement

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index

Section 14.3

Chapter 14 · Assertions and Unit Testing

298

ScalaTest facilitates different styles of testing, because execute can be overridden in Suite subtypes. For example, ScalaTest offers a trait called FunSuite, which overrides execute so that you can define tests as function values rather than methods. Listing 14.4 shows an example:

import org.scalatest.FunSuite import Element.elem

class ElementSuite extends FunSuite {

test("elem result should have passed width") { val ele = elem('x', 2, 3)

assert(ele.width == 2)

}

}

Listing 14.4 · Writing a test function with FunSuite.

The “Fun” in FunSuite stands for function. “test” is a method defined in FunSuite, which will be invoked by the primary constructor of ElementSuite. You specify the name of the test as a string between the parentheses, and the test code itself between curly braces. The test code is a function passed as a by-name parameter to test, which registers it for later execution. One benefit of FunSuite is you need not name all your tests starting with “test”. In addition, you can more easily give long names to your tests, because you need not encode them in camel case, as you must do with test methods.2

14.3 Informative failure reports

The tests in the previous two examples attempt to create an element of width 2 and assert that the width of the resulting element is indeed 2. Were this assertion to fail, you would see a message that indicated an assertion failed. You’d be given a line number, but wouldn’t know the two values that were unequal. You could find out by placing a string message in the assertion that includes both values, but a more concise approach is to use the triple-equals operator, which ScalaTest provides for this purpose:

2You can download ScalaTest from http://www.scalatest.org/.

Cover · Overview · Contents · Discuss · Suggest · Glossary · Index


Section 14.3

Chapter 14 · Assertions and Unit Testing

299

assert(ele.width === 2)

Were this assertion to fail, you would see a message such as “3 did not equal 2” in the failure report. This would tell you that ele.width wrongly returned 3. The triple-equals operator does not differentiate between the actual and expected result. It just indicates that the left operand did not equal the right operand. If you wish to emphasize this distinction, you could alternatively use ScalaTest’s expect method, like this:

expect(2) { ele.width

}

With this expression you indicate that you expect the code between the curly braces to result in 2. Were the code between the braces to result in 3, you’d see the message, “Expected 2, but got 3” in the test failure report.

If you want to check that a method throws an expected exception, you can use ScalaTest’s intercept method, like this:

intercept[IllegalArgumentException] { elem('x', -2, 3)

}

If the code between the curly braces completes abruptly with an instance of the passed exception class, intercept will return the caught exception, in case you want to inspect it further. Most often, you’ll probably only care that the expected exception was thrown, and ignore the result of intercept, as is done in this example. On the other hand, if the code does not throw an exception, or throws a different exception, the intercept method will throw a TestFailedException, and you’ll get a helpful error message in the failure report, such as:

Expected IllegalArgumentException to be thrown, but NegativeArraySizeException was thrown.

The goal of ScalaTest’s === operator and its expect and intercept methods is to help you write assertion-based tests that are clear and concise. In the next section, we’ll show you how to use this syntax in JUnit and TestNG tests written in Scala.

Cover · Overview · Contents · Discuss · Suggest · Glossary · 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