Scala Test-Driven Development - Gaurav Sood - E-Book

Scala Test-Driven Development E-Book

Gaurav Sood

0,0
33,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build robust Scala applications by implementing the fundamentals of test-driven development in your workflow

About This Book

  • Get a deep understanding of various testing concepts such as test-driven development (TDD) and BDD
  • Efficient usage of the built-in Scala features such as ScalaTest, specs2, and Scala check
  • Change your approach towards problem solving by thinking about the boundaries of the problem and its definition rather than focusing on the solution

Who This Book Is For

This book is for Scala developers who are looking to write better quality and easily maintainable code. No previous knowledge of TDD/BDD is required.

What You Will Learn

  • Understand the basics of TDD and its significance
  • Refactoring tests to build APIs in order to increase test coverage
  • How to leverage the inbuilt Scala testing modules like ScalaTest, specs2 and Scala Check
  • Writing test fixtures and apply the concepts of BDD
  • How to divide tests to run at different points in continuous delivery cycle
  • Benefits of refactoring and how it affects the final quality of code produced
  • Understanding of SBT based build environment and how to use it to run tests
  • The fundamentals of mocking and stubbing in Scala and how to use it efficiently

In Detail

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.

Style and approach

This step-by-step guide explains the significance of TDD in Scala through various practical examples. You will learn to write a complete test-driven application throughout the course of the book.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 187

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Scala Test-Driven Development
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Hello, TDD!
What is TDD?
Why TDD?
Changing our approach to problem solving
Iteratively writing failing tests
Baby steps
Brief introduction to Scala and SBT
What is Scala?
Why Scala?
Scala Build Tool
Why SBT?
Resources for learning Scala
Resources for SBT
Setting up a build environment
Steps for downloading and installing Scala
Steps for downloading and installing SBT
Creating a project directory structure
Build definition files
Hello World!
Creating a directory structure
Creating a build definition
Test first!
Summary
2. First Test-Driven Application
Testing frameworks
ScalaTest
A quick tutorial
Adding ScalaTest to the project
Choose your testing style
FunSuite
FlatSpec
FunSpec
WordSpec
FreeSpec
Spec
PropSpec
FeatureSpec
Resources for ScalaTest
Problem statements
IDE
Project structure
Write a failing test – RED
Writing application code to fix the test – GREEN
More tests – REPEAT
Intercepting exceptions
Summary
3. Clean Code Using ScalaTest
Assertions
Deliberately failing tests
Assumptions
Canceling tests
Failure messages and clues
Matchers
Matchers for equality
Matchers for instance and identity checks of objects
Matchers for size and length
Matching strings
Matching greater and less than
Matching Boolean properties
Matching number within ranges
Matching emptiness
Writing your own BeMatchers
Some more Matchers
Matchers for containers
Combining Matchers with logical expressions
Matching options
Matching properties
Checking that a snippet of code does not compile
Base test classes
Test fixtures
Calling get-fixture methods
Instantiating fixture-context objects
Overriding withFixture(NoArgTest)
Calling loan-fixture methods
Overriding withFixture(OneArgTest)
Mixing in BeforeAndAfter
Composing fixtures by stacking traits
Problem statement
Feature – decimal to hexadecimal conversion
BinaryToDecimalSpec.scala
HexadecimalToDecimalSpec.scala
DecimalHexadecimalSpec.scala
BeanSpec.scala
package.scala.packt
BaseConversion.scala
Summary
4. Refactor Mercilessly
Clean code
Red-Green-Refactor
Code smell
Expendable
Couplers
Modification thwarters
Bloaters
Object-oriented abusers
Obsolete libraries
To refactor or not to refactor
Doing it thrice (rule of three)
Adding new feature
Bug fixing
Code reviews
Refactoring techniques
Composing methods
Moving features between objects
Organizing data
Summary
5. Another Level of Testing
Integration testing
Functional testing
Acceptance testing
Need for user acceptance testing
Behavior-driven development
Introduction
Three amigos
Bird's-eye view of BDD
Gherkin
Executable specification
Don't repeat yourself
Talk is cheap
Adding Cucumber dependency
Directory structure
The feature file
Running the feature
Step definition
Summary
6. Mock Objects and Stubs
History
Coupling
Stubs
Mock objects
Expectations
Verifications
Fakes
Spy
Mocking frameworks
JMock
Advantages of JMock
EasyMock
Mockito
ScalaMock
Advantages of ScalaMock
mockFunction
Proxy mocks
Generated mocks
Let's dig a little deeper
Specifying expectations
Summary
7. Property-Based Testing
Introduction to property-based testing
Table-driven properties
Generator-driven properties
ScalaCheck
Generators
Generating case classes
Conditional Generators
Generating containers
Arbitrary Generator
Generation statistics
Executing property checks
Our own Generator-driven property checks
Summary
8. Scala TDD with Specs2
Introduction to Specs2
Differences between Specs2 and ScalaTest
Setting up Specs2
Styles
Unit specifications
Acceptance specification
Matchers
Simple Matchers
Matchers for strings
Matchers for relational operators
Matchers for floating point
Matchers for references
Matchers for Option/Either
Matchers for the try monad
Matching exception
Iterable Matchers
Matchers for sequences and traversables
Matchers for maps
Matchers for XML
Matchers for files
Matchers for partial functions
Other Matchers
Specs2 data tables
Running Specs2 tests
Summary
9. Miscellaneous and Emerging Trends in Scala TDD
Scala Futures and Promises
ExecutionContext
Futures
The Inside trait
The OptionValue trait
The EitherValue trait
Eventually
How to configure eventually
Simple backoff algorithm
Integration patience
Consumer-Driven Contracts
How services interface with each other
The gigantic way
Microservices
Using CDC to integrate microservices
Traditional way
Using CDC
Benefits of CDC
Summary

Scala Test-Driven Development

Scala Test-Driven Development

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2016

Production reference: 1211016

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-467-5

www.packtpub.com

Credits

Author

Gaurav Sood

Copy Editors

Charlotte Carneiro

Safis Editing

Reviewer

Román García

Project Coordinator

Sheejal Shah

Commissioning Editor

Kunal Parikh

Proofreader

Safis Editing

Acquisition Editor

Chaitanya Nair

Indexer

Rekha Nair 

Content Development Editor

Parshva Sheth

Graphics

Kirk D'Penha

Technical Editor

Prajakta Mhatre

Production Coordinator

Aparna Bhagat

About the Author

Gaurav Sood is a Scala and XQuery consultant who consults through his own company Omkaar Technologies Limited. He started playing with computers at a very early age and eventually went onto complete his post-graduate degree in computer sciences. 

After working for an Indian software service house for a couple of years, he decided to start his own consultancy business. Since then, his company has provided services to a few Tier 1 Investment banks, the government of the United Kingdom, and publishing houses. He has gained an irrefutable reputation and distinction in the industry. Gaurav has previously worked with HSBC, Deutsche Bank, Reed Elsevier, Lexis Nexis, John Wiley & Sons, HMRC, and Associated News, amongst other smaller names in the industry.

When he is not consulting or writing, Gaurav can be seen making a fuss of his family. He likes spending time with his beautiful wife and two sons. He also loves volunteering for charity fund raising through sponsored runs. Gaurav also runs a small charitable trust in Shimla, India (New Life), which helps provide education to under-privileged children.

Acknowledgments

I would like to start by thanking God for the courage and determination to write this book. There are many people I would like to express my gratitude to, for helping me with this book. These people have seen me through this book, provided support, offered comments, proofread my work, and been a critic when I needed one.

I want to thank my family for being my strength, my parents, Satish and Brij, wife, Khushboo, and two little boys, Johan and Jairus, who have been my strength. They have supported and encouraged me in spite of all the time it took me away from them. It was a lingering and arduous voyage for them. I would also like to thank my in-laws, Hardeep and Kawaljit, along with my siblings and friends for encouraging me to consider writing this book. They have always believed in me.

I would also like to thank Packt Publishing, their extremely helpful editorial staff and technical reviewers for enabling me to publish this book and encouraging me every step of the way. I would also like to thank Artima Inc, for their permission to refer to their work.

Special thanks once again to my lovely wife Khushboo. Without you, this book wouldn’t have been possible.

Last but not the least: I beg forgiveness to all those who have been with me over the years and whose names I have failed to mention.

About the Reviewer

Román García has been a self-taught software engineer for the last two decades, and is currently CTO at Fravega.com, one of the biggest retail companies in Argentina where he resides. Previously, he worked as a software architect for Despegar.com, ZonaJobs.com, DeRemate.com, and others. An avid cowboy programmer, he is passionate about software development, clean code, test-driven development, and madly in love with the Scala programming language.

I’d like to thank my parents for all their support during the early years, when I found my passion for programming, and, last but not least, to my loving wife, Elisabeth, and my two kids, Manuela and Joaquin, for all the love they brought to my life.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

Test-Driven Development (TDD) goes hand-in-hand with Agile practices, which is gradually becoming the undisputed standard process or delivering quality software on time. The TDD process originated from the need to better understand and refine the requirements for a system.

Scala has gradually, despite all apprehensions, made a niche for itself as the language of choice for delivering modern versatile systems and microservices. It is slowly and steadily replacing the conventional object-oriented models with more robust and immutable functional constructs. The popularity of Scala emanates from the fact that it provides a bridge for developers to make a transition from the object-oriented to the functional world.

Scala, like all other languages, can allow developers to get so engrossed in its intricacies and magic that the real purpose of the application can easily get lost in over-engineering. Therefore, TDD is required to keep the application code tightly tied to the requirements.

What this book covers

Chapter 1, Hello, TDD!, contains a brief introduction of TDD and Agile process. We discussed the benefits of TDD and how and why it needs to be used.

Chapter 2, First Test-Driven Application, creates our very first working application using TDD. The purpose of this chapter is to provide a quick win and give a taste of what lies ahead.

Chapter 3, Clean Code Using ScalaTest, discusses some of the principles of clean code and delves into the ScalaTest framework.

Chapter 4, Refactor Mercilessly, discusses various refactoring techniques and their benefits. The idea is to build a gradual appreciation of the refactoring process.

Chapter 5, Another Level of Testing, discusses the concepts of functional testing and behaviour-driven development.

Chapter 6, Mock Objects and Stubs, takes an in-depth look into the mocking frameworks that can be used with ScalaTest and Specs2 to enable mocking out the dependencies during testing.

Chapter 7, Property-Based Testing, discusses the techniques of writing tests that are driven from inputs provided in the form of tabular data or that is randomly generated.

Chapter 8, Scala TDD with Specs2, looks at an alternative testing framework for test-driving Scala code. We also compare ScalaTest and Specs2 so the reader can make an informed choice.

Chapter 9, Miscellaneous and Emerging Trends in Scala TDD, explores some new techniques, features, and processes that may soon become incorporated into the mainstream application development process.

What you need for this book

The following software is recommended for use with this book:

ScalaSBTIntelliJ or Eclipse IDE

Who this book is for

This book is for Scala developers who are looking to write better quality and easily maintainable code. No previous knowledge of TDD/BDD is required.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Scala-Test-Driven-Development. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Hello, TDD!

Let's begin this chapter with a brief introduction to Test-Driven Development (or TDD, as it's colloquially known), covering some of its basic concepts. The main goal of this chapter is to give you an appreciation of TDD practices and for you to ascertain what technological niche it fulfills.

This chapter will explore:

What is TDD?What is the need for TDD?Changing approach to problem solvingIteratively writing failing tests and fixing themSignificance of baby stepsScalaBrief introduction to Scala and SBTSetting up the build environmentTDD with Scala"Hello World" application

What is TDD?

TDD is the practice of writing your tests before writing any application code.

TDD is a practice that is most frequently and strongly advocated by Agile practitioners and theorists. It is one of the major pillars of the Agile methodology. There have been various studies over the years and many white papers published, which clearly state that the use of TDD has resulted in a more successful and robust application code.

TDD consists of the following iterative steps:

This process is also referred to as Red-Green-Refactor-Repeat.

TDD became more prevalent with the use of the Agile software development process, though it can be used as easily with any of the Agile development process's predecessors, such as Waterfall, Iterative, and so on.

At the height of the software revolution in the 1990s, it became evident that the draconian processes and practices developed mostly in the 1980s were slow, officious, likely to fail, and rigid. The Agile development process was created at the Snowbird ski resort in the Wasatch Mountains of Utah. Here, 17 industry thought-leaders met to discuss the problems of the development processes being used with the common goal of creating an adaptive development process that has people at its core rather than requirements. This resulted in the Agile manifesto:

Though TDD is not specifically mentioned in the Agile manifesto (http://agilemanifesto.org), it has become a standard methodology used with Agile. Saying this, you can still use Agile without using TDD.

Why TDD?

The need for TDD arises from the fact that there can be constant changes to the application code. This becomes more of a problem when we are using the Agile development process, as it is inherently an iterative development process.

Here are some of the advantages, which underpin the need for TDD:

Code quality: Tests on TDD make the programmer more confident of their code. Programmers can be sure of syntactic and semantic correctness of their code.Evolving architecture: A purely test-driven application code gives way to an evolving architecture. This means that we do not have to predefine our architectural boundaries and the design patterns. As the application grows, so does the architecture. This results in an application that is flexible towards future changes.Documenting the code: These tests also document the requirements and application code. Agile purists normally regard comments inside the code as a "smell". According to them your tests should document your code.Avoiding over engineering: Tests that are written before the application code define and document the boundaries. Since all the boundaries are predefined in the tests, it is hard to write application code that breaches these boundaries. This, however, assumes that TDD is being followed religiously.Paradigm shift: When I started with TDD, I noticed that the first question I asked myself after looking at the problem was "How can I solve it?" This, however, is counterproductive. TDD forces the programmer to think about the testability of the solution before its implementation. This would result in solutions, which are testable in nature as we had used tests to derive these solutions. To understand how to test a problem would mean a better understanding of the problem and its edge cases. This in turn can result in the refinement of the requirements or the discovery of some new requirements. Now it has become impossible for me not to think about testability of the problem before the solution. Now the first question I ask myself is; "How can I test it?" This can be done by translating the requirements into tests.Maintainable code: I have always found it easier to work on an application that has historically been test-driven rather than on one that has not. Why? Only because when I make changes to the existing code, the existing tests make sure that I do not break any existing functionality. This results in highly maintainable code, where many programmers can collaborate simultaneously.Refactoring freely: Having a good test coverage over the application code allows the programmer to continuously refactor and improve the code while maintaining an idempotent nature of the application code.

Changing our approach to problem solving

Everything we have discussed thus far makes perfect sense in theory, but we need to look at what needs to change in our approach to problem solving if we are to practice the TDD ethos.

I will be more biased towards "me", and will discuss how I made the transition into "TDD land". When I was first asked to build an application using test-driven principles my natural reaction was to doubt every aspect of it. My client at that time had hired a reputable external Agile enablement company to hand-hold developers to learn these new age shenanigans.

My first few questions were "Is it not more time consuming?", "Isn't it QA's job to test?", "Why do we need to test-drive even a very trivial bit of code?", and many more (mostly whiney) questions.