Spock: Up and Running: Writing Expressive Tests in Java and Groovy / Edition 1

Spock: Up and Running: Writing Expressive Tests in Java and Groovy / Edition 1

by Rob Fletcher
ISBN-10:
1491923296
ISBN-13:
9781491923290
Pub. Date:
06/02/2017
Publisher:
O'Reilly Media, Incorporated
ISBN-10:
1491923296
ISBN-13:
9781491923290
Pub. Date:
06/02/2017
Publisher:
O'Reilly Media, Incorporated
Spock: Up and Running: Writing Expressive Tests in Java and Groovy / Edition 1

Spock: Up and Running: Writing Expressive Tests in Java and Groovy / Edition 1

by Rob Fletcher
$59.99
Current price is , Original price is $59.99. You
$59.99 
  • SHIP THIS ITEM
    Qualifies for Free Shipping
  • PICK UP IN STORE
    Check Availability at Nearby Stores

Overview

Most developers would agree that writing automated tests is a good idea, but writing good, well-structured tests is still an elusive skill for many. For Java and Groovy developers, however, there’s good news. This practical guide shows you how to write concise and highly readable tests with Spock, the most innovative testing and specification framework for the JVM since JUnit.

Author Rob Fletcher takes you from Spock basics to advanced topics, using fully worked integration examples. Through the course of this book, you’ll build a simple web application—Squawker—that allows users to post short messages. You’ll discover how much easier it is to write automated tests with Spock’s straightforward and expressive language.

  • Start by learning how to write simple unit tests
  • Understand the lifecycle of Spock specifications and feature methods
  • Dive into interaction testing, using Spock’s intuitive syntax for dealing with mocks and stubs
  • Learn about parameterized tests—writing feature methods that run for multiple sets of data
  • Move into advanced topics, such as writing idiomatic Spock code and driving parameterized tests with file or database input
  • Learn how everything works together in a standalone, fully-worked, test-driven development example

Product Details

ISBN-13: 9781491923290
Publisher: O'Reilly Media, Incorporated
Publication date: 06/02/2017
Pages: 370
Product dimensions: 6.90(w) x 9.30(h) x 0.90(d)

About the Author

Rob Fletcher is a Senior Software Engineer at Netflix, where he focuses on using automated testing as design tool. He has over 15 years of experience in the software industry, and has contributed to several open source projects including Groovy, Geb, Ratpack, and Grails.

Table of Contents

Introduction xi

Part I Spock 101

1 The "Up and Running" Part 3

Installation 3

Running with the JUnit Runner 3

Running with Gradle 3

When Groovy Is Used in the Project 4

Synchronizing Groovy Versions Between Main and Test Classpaths 4

Running with Maven 5

2 Specification Basics 7

Anatomy of a Specification 7

Why Use Quoted Strings for Feature Method Names? 9

An Introduction to Spock's Blocks 10

Block Taxonomy 12

Basic Block Usage 13

The Specification Lifecycle 15

Fixture methods: setup and cleanup 15

Block Descriptions 17

And: blocks 18

A Note on Comprehensibility 18

Summary 19

Comparison with JUnit 19

3 Spock Assertions 21

The Importance of Good Diagnostics 22

The Power Assert 22

Type Information in Power Asserts 24

Using Groovy for Effective Assertions 25

Using List Comprehensions and List Literals 25

Asserting Something About Every Item in a Collection 27

Expressive Assertions with Groovy Operators 29

Expecting Exceptions 31

Interrogating the Exception 31

Grouping Assertions on the Same Object 32

Summary 33

4 Managing Resources 39

How (Not) to Approach Persistence Testing 39

Testing a Persistence Layer 40

Managing Resources with the Spock Lifecycle 42

Specifications and Inheritance 47

Execution Order of Lifecycle Methods in an Inheritance Hierarchy 51

Summary 53

5 Interaction Testing 55

Asserting that a Method Is Called 56

Specifying Invocation Cardinality 58

Declaring the Return Value from a Mocked Method 59

Parameter Predicates 59

Disallowing Unexpected Calls or "Strict Mocking" 60

Looser Matching with Wildcard Parameters 61

Wildcard Shortcuts 61

Defining Behavior for Mocked Methods 62

Removing Invocation Constraints with Stubs 63

When Should I Use a Mock and When Should I Use a Stub? 64

Mixing Mocks and Stubs 65

Summary 66

6 Parameterized Specifications 67

Parameterization in JUnit 71

Spock's where: block 73

Separating Iteration Reporting by Using @Unroll 75

Adding @Unroll Descriptions 75

@Unroll Tokens in Feature Method Names 76

Class Level @Unroll Annotations 76

Multiple Data Pipes 77

Data Tables 77

Fields and Methods as Data Providers 79

Derived Values 80

Clarifying @Unroll Expressions 82

Summary 83

Part II Advanced Spock

7 Idiomatic Spock 87

Organizing Tests 87

The "Test-per-Method" Antipattern 88

Well-Factored Specifications 89

Sharing Helper Methods 90

Sharing Methods by Using import static 93

Sharing Methods with Groovy Traits 94

Sharing Methods with Delegation 95

Helper Methods and Assertions 97

Helper Methods and Mock Interactions 97

Comparing "Before" and "After" Values 98

The Grammar of Blocks 100

Separation of Logic and Data with where: Blocks 101

Using when/then or given/expect 103

Separating Preconditions 105

Separating Preconditions from Actions 105

Method Parameter Capture with Mocks 107

Using a Closure as a Parameter Predicate 109

Using Hamcrest for Parameter Predicates 110

Parameter Capture Using a Mock Responder 111

@Stepwise Specifications 114

How to Use @Stepwise 115

Disadvantages of @Stepwise 117

Conditional Specifications 118

Marking Pending Features 118

Selectively Executing Tests 119

Automatically Cleaning Up Resources 120

Documenting Specifications 121

Summary 122

8 Advanced where: Blocks 123

A Primary Key Verifier 123

A Static Site Link Checker 125

JBake Configuration 126

A Data Pipe Driven by a File 127

A Filtered Data Pipe 129

Relative Filepaths 130

Summary 132

9 Asynchronous Testing 135

Blocking Constructs 135

Blocking Variable 136

Blocking Variables 136

Testing Nonblocking APIs by Using Callbacks 136

Using BlockingVariable in a Callback 139

Using a Reference to BlockingVariable.set as a Callback 140

Awaiting Multiple Values with Blocking Variables 140

Polling for Eventual State 143

Using PollingConditions as a Delegate 144

Asynchronous Interaction Testing 144

Asynchronous Parameter Capture 146

Extending BlockingVariable 148

Summary 149

10 Extending Spock 151

The Message Timeline 151

Hamcrest Matchers 154

Hamcrest Support in Spock 155

JUnit Rules 156

Reusable Data Cleanup 157

Simplifying the Rule by Using ExternalResource 161

Making the Cleanup Logic Generic 162

Spock Extensions 163

Data Cleanup as a Spock Extension 163

Further Steps 166

Global Extensions 166

Taking it Further 172

Summary 172

11 Test-Driven Development: The Diamond Kata 175

The Diamond Kata 175

Implementation 176

First Step: The Pathological Case 176

The Simplest Valid Diamond 177

Enforcing Invariants 178

Matrix Content 180

Symmetry 183

Eliminating the Assertion Loop 186

Adding Padding to the Rows 187

Refinement 189

Summary 190

Part III Integrating Spock

12 Spock and Spring 193

What Do We Mean by "Integration Tests"? 193

Container Tests 193

Spring Compatibility 194

@SpringBootTest 195

Testing Annotation-Driven Transactions 195

Tracking Who Is Mentioned in a Message 196

Non-Spring-Dependent Tests 198

Testing a Transaction Rollback 199

Setting Up the Spring Application 200

A First Integration Test 201

Convenience and Cost 203

Unexpected Side Effects 204

Forcing Spring to Re-Create the Application Context 204

A Better Way to Force Errors 206

Mock and Stub Beans 207

Mention Events 207

Mock Beans Before Spock 1.1 208

Mock Bean Delegates 210

Detached Mocks in the Spring Context 211

Spring Autoconfiguration and Test Configuration Classes 212

Mock Beans in XML Configuration 212

Replacing Application Beans with Mocks 213

Declarative Test Data

Using the @Sql Annotation for Data Fixtures 216

Global Fixture Data 217

Cleaning Up Test Data Spring-Style 218

Tests in Transactions 219

Propagated Transactions 220

Summary 222

13 Testing REST APIs 223

Defining the Application URL 223

A First Specification 224

Web Application Lifecycle 226

Creating Data for End-to-End Tests 226

Bleeding Data Between Tests 227

Creating Test Data on Demand 227

Cleaning Up Test Data 228

Requests with Data 229

Fixture Methods 230

Testing for HTTP Errors 230

Verifying Response Data 232

Typed Response Entities 233

Multiple HTTP Requests in a Feature Method 235

Backdoors or "Pure" API Testing? 236

Handling Redirect Responses 238

Verifying Redirect Details 239

REST API Security 240

Authentication versus Authorization 243

Summary 246

14 End-to-End Web Testing 247

Geb 247

Getting Started with Geb 248

A First Frontend Test 249

Introducing Page Models 252

Setting the Base URL 255

Geb's Automatic Delegation 256

Authentication 256

Encapsulating Interactions by Using Methods 257

Modules 259

Parameterized Pages 263

Interacting with Forms 264

Accessing Form Elements by Name 267

Encapsulating Interactions with Methods 268

Form Validation 269

15 Testing JavaScript Using Spock 271

Why Test JavaScript from the JVM? 272

Setting Up Nashorn for Tests 272

Calling JavaScript Functions 272

JavaScript Functions as Objects 273

Specifying this in a JavaScript Function 274

Testing an Isomorphic View Component 275

An Invocable Script Engine as a Delegate 277

Passing Mocks to JavaScript 277

Rendering a View with the Handlebars Library 279

Compiling Handlebars Templates 280

Testing Template Rendering 282

Handling Properties That Don't Convert to JavaScript 283

Registering Handlebars Helper Functions 285

Composing Templates with Handlebars Partials 287

Passing Iterable Values to JavaScript 288

Summary 290

16 Test Driving an RxJava Application 291

Tests, Behaviors, and Properties 292

The Skeleton Implementation 292

Test Driving the Implementation 293

Defining the Behavior 293

A First Test 294

Polling at Regular Intervals 295

No Sleep 'Til the Test Goes Green 295

Testing Subscription to the Stream 298

Unchunking the Message Stream 299

Requesting Messages Since the Last Received 302

Recovering from Polling Errors 303

Recovering from Downstream Errors 305

Final Implementation 307

A. Groovy Primer 309

Bibliography 337

Index 339

From the B&N Reads Blog

Customer Reviews