Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Scala Test-Driven Development
Scala Test-Driven Development
Scala Test-Driven Development
Ebook420 pages3 hours

Scala Test-Driven Development

Rating: 0 out of 5 stars

()

Read preview

About this ebook

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.
LanguageEnglish
PublisherPackt Publishing
Release dateOct 27, 2016
ISBN9781786463029
Scala Test-Driven Development

Related to Scala Test-Driven Development

Related ebooks

Internet & Web For You

View More

Reviews for Scala Test-Driven Development

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Scala Test-Driven Development - Gaurav Sood

    (missing alt)

    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

    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.

    www.PacktPub.com

    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 Packt

    Copy and paste, print, and bookmark content

    On 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:

    Scala

    SBT

    IntelliJ 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.

    Conventions

    In this

    Enjoying the preview?
    Page 1 of 1