Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Programming_in_Scala,_2nd_edition.pdf
Скачиваний:
25
Добавлен:
24.03.2015
Размер:
22.09 Mб
Скачать

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

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]