Book Image

Scala Test-Driven Development

By : Gaurav Sood
Book Image

Scala Test-Driven Development

By: Gaurav Sood

Overview of this book

Test-driven development (TDD) produces high-quality applications in less time than is possible with traditional methods. Due to the systematic nature of TDD, the application is tested in individual units as well as cumulatively, right from the design stage, to ensure optimum performance and reduced debugging costs. This step-by-step guide shows you how to use the principles of TDD and built-in Scala testing modules to write clean and fully tested Scala code and give your workflow the change it needs to let you create better applications than ever before. After an introduction to TDD, you will learn the basics of ScalaTest, one of the most flexible and most popular testing tools around for Scala, by building your first fully test-driven application. Building on from that you will learn about the ScalaTest API and how to refactor code to produce high-quality applications. We’ll teach you the concepts of BDD (Behavior-driven development) and you’ll see how to add functional tests to the existing suite of tests. You’ll be introduced to the concepts of Mocks and Stubs and will learn to increase test coverage using properties. With a concluding chapter on miscellaneous tools, this book will enable you to write better quality code that is easily maintainable and watch your apps change for the better.
Table of Contents (16 chapters)
Scala Test-Driven Development
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Preface

The EitherValue trait


By including the EitherValue trait in our mixin, we get an implicit conversion of the Either monad. This implicit conversion adds a value method to both left and right of Either. This allows us to do a left.value and right.value. The value method either returns the selected value from a defined Either or alternatively throws a TestFailedException in case the Either is not defined.

Using this, we are able to test in a single expression, both that the Either should be left or right (that is, it is defined) and also that it has a certain expected value. Let's look at an example:

firstEither.right.value should be < 5
secondEither.left.value should be ("Big Ploblemo!")

The same can be done using assertions:

assert(firstEither.right.value should be < 5)
assert(secondEither.left.value === "Big Ploblemo!")

If we were using a standard right.get and left.get method on the Either to get the value, we would get a NoSuchElementException. Therefore, using the EitherValue...