Full download The art of unit testing, third edition: with examples in javascript roy osherove pdf d

Page 1


The Art of Unit Testing, Third Edition: with examples in JavaScript

Visit to download the full and correct content document: https://textbookfull.com/product/the-art-of-unit-testing-third-edition-with-examples-in-ja vascript-roy-osherove/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Automated Unit Testing with ABAP: A Practical Approach

1st Edition James E. Mcdonough

https://textbookfull.com/product/automated-unit-testing-withabap-a-practical-approach-1st-edition-james-e-mcdonough/

Beginning Ethereum Smart Contracts Programming: With Examples in Python, Solidity, and JavaScript Lee

https://textbookfull.com/product/beginning-ethereum-smartcontracts-programming-with-examples-in-python-solidity-andjavascript-lee/

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cookloucas/

Pro iOS Testing: XCTest Framework for UI and Unit Testing Avi Tsadok

https://textbookfull.com/product/pro-ios-testing-xctestframework-for-ui-and-unit-testing-avi-tsadok/

Pro iOS Testing: XCTest Framework for UI and Unit Testing 1st Edition Avi Tsadok

https://textbookfull.com/product/pro-ios-testing-xctestframework-for-ui-and-unit-testing-1st-edition-avi-tsadok/

Unit Testing Principles, Practices, and Patterns 1st Edition Vladimir Khorikov

https://textbookfull.com/product/unit-testing-principlespractices-and-patterns-1st-edition-vladimir-khorikov/

Software Development, Design and Coding: With Patterns, Debugging, Unit Testing, and Refactoring, 2nd Edition

John F. Dooley

https://textbookfull.com/product/software-development-design-andcoding-with-patterns-debugging-unit-testing-and-refactoring-2ndedition-john-f-dooley/

Testing JavaScript Applications MEAP V05 Lucas Da Costa

https://textbookfull.com/product/testing-javascript-applicationsmeap-v05-lucas-da-costa/

Learn With Angular 4 Collected Essays Angular CLI Unit Testing Debugging TypeScript and Angular Build Processes 2nd Edition Jeffry Houser

https://textbookfull.com/product/learn-with-angular-4-collectedessays-angular-cli-unit-testing-debugging-typescript-and-angularbuild-processes-2nd-edition-jeffry-houser/

inside front cover

Test recipes

A test recipe is a test plan, outlining at which level a particular feature should be tested.

Praise for the second edition

This book is something special. The chapters build on each other to a startling accumulation of depth. Get ready for a treat.

—From the foreword of the second edition by Robert C. Martin, cleancoder.com

The best way to learn unit testing from what is now a classic in the field.

—Raphael Faria, LG Electronics

Teaches you the philosophy as well as the nuts and bolts for effective unit testing.

—Pradeep Chellappan, Microsoft

When my team members ask me how to write unit tests the right way, I simply answer: Get this book!

—Alessandro Campeis, Vimar SpA

The single best resource on unit testing.

—Kaleb Pederson, Next IT Corporation

The most useful and up-to-date guide to unit testing I have ever read.

—Francesco Goggi, FIAT

A must for any serious .NET developer wishing to learn or perfect their unit testing knowledge.

The Art of Unit Testing

Third Edition

WITH EXAMPLES IN JAVASCRIPT

To comment go to liveBook

Roy Osherove with Vladimir Khorikov
Manning
Shelter Island

Copyright

For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity.

For more information, please contact

Special Sales Department

Manning Publications Co.

20 Baldwin Road PO Box 761

Shelter Island, NY 11964

Email: orders@manning.com

©2024 by Manning Publications Co. All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning

Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.

♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.

Manning Publications Co. 20 Baldwin Road Technical PO Box 761

Shelter Island, NY 11964

Development editor: Connor O’Brien

Technical development editor: Mike Shepard

Review editors: Adriana Sabo and Dunja Nikitović

Production editor: Kathy Rossland

Copy editor: Andy Carroll

Proofreader: Katie Tennant

Technical proofreader: Jean-François Morin

Typesetter: Dennis Dalinnik

Cover designer: Marija Tudor

ISBN: 9781617297489

dedication

To Tal, Itamar, Aviv, and Ido. My family.

To my wife Nina and son Timothy.

—Roy Osherove
Vladimir Khorikov

contents

Front matter

foreword to the second edition

foreword to the first edition

preface

acknowledgments about this book about the authors about the cover illustration

Part 1 Getting started

1 The basics of unit testing

1.1 The first step

1.2 Defining unit testing, step by step

1.3 Entry points and exit points

1.4 Exit point types

1.5 Different exit points, different techniques

1.6 A test from scratch

1.7 Characteristics of a good unit test What is a good unit test? A unit test checklist

1.8 Integration tests

1.9 Finalizing our definition

1.10 Test-driven development

TDD: Not a substitute for good unit tests

Three core skills needed for successful TDD

2 A first unit test

2.1 Introducing Jest

Preparing our environment

Preparing our working folder

Installing Jest

Creating a test file

Executing Jest

2.2 The library, the assert, the runner, and the reporter

2.3 What unit testing frameworks offer

The xUnit frameworks

xUnit, TAP, and Jest structures

2.4 Introducing the Password Verifier project

2.5 The first Jest test for verifyPassword

The Arrange-Act-Assert pattern

Testing the test

USE naming

String comparisons and maintainability

Using describe()

Structure implying context

The it() function

Two Jest flavors

Refactoring the production code

2.6 Trying the beforeEach() route

beforeEach() and scroll fatigue

2.7 Trying the factory method route

Replacing beforeEach() completely with factory methods

2.8 Going full circle to test()

2.9 Refactoring to parameterized tests

2.10 Checking for expected thrown errors

2.11 Setting test categories

Part 2 Core techniques

3 Breaking dependencies with stubs

3.1 Types of dependencies

3.2 Reasons to use stubs

3.3 Generally accepted design approaches to stubbing

Stubbing out time with parameter injection

Dependencies, injections, and control

3.4 Functional injection techniques

Injecting a function

Dependency injection via partial application

3.5 Modular injection techniques

3.6 Moving toward objects with constructor functions

3.7 Object-oriented injection techniques

Constructor injection

Injecting an object instead of a function

Extracting a common interface

4 Interaction testing using mock objects

4.1 Interaction testing, mocks, and stubs

4.2 Depending on a logger

4.3 Standard style: Introduce parameter refactoring

4.4 The importance of differentiating between mocks and stubs

4.5 Modular-style mocks

Example of production code

Refactoring the production code in a modular injection style

A test example with modular-style injection

4.6 Mocks in a functional style

Working with a currying style

Working with higher-order functions and not currying

4.7 Mocks in an object-oriented style

Refactoring production code for injection

Refactoring production code with interface injection

4.8 Dealing with complicated interfaces

Example of a complicated interface

Writing tests with complicated interfaces

Downsides of using complicated interfaces directly

The interface segregation principle

4.9 Partial mocks

A functional example of a partial mock

An object-oriented partial mock example

5 Isolation frameworks

5.1 Defining isolation frameworks

Choosing a flavor: Loose vs. typed

5.2 Faking modules dynamically

Some things to notice about Jest’s API

Consider abstracting away direct dependencies

5.3 Functional dynamic mocks and stubs

5.4 Object-oriented dynamic mocks and stubs

Using a loosely typed framework

Switching to a type-friendly framework

5.5 Stubbing behavior dynamically

An object-oriented example with a mock and a stub

Stubs and mocks with substitute.js

5.6 Advantages and traps of isolation frameworks

You don’t need mock objects most of the time

Unreadable test code

Verifying the wrong things

Having more than one mock per test

Overspecifying the tests

6 Unit testing asynchronous code

6.1 Dealing with async data fetching

An initial attempt with an integration test

Waiting for the act

Integration testing of async/await

Challenges with integration tests

6.2 Making our code unit-test friendly

Extracting an entry point

The Extract Adapter pattern

6.3 Dealing with timers

Stubbing timers out with monkey-patching

Faking setTimeout with Jest

6.4 Dealing with common events

Dealing with event emitters

Dealing with click events

6.5 Bringing in the DOM testing library

Part 3 The test code

7 Trustworthy tests

7.1 How to know you trust a test

7.2 Why tests fail

A real bug has been uncovered in the production code

A buggy test gives a false failure

The test is out of date due to a change in functionality

The test conflicts with another test

The test is flaky

7.3 Avoiding logic in unit tests

Logic in asserts: Creating dynamic expected values

Other forms of logic

Even more logic

7.4 Smelling a false sense of trust in passing tests

Tests that don’t assert anything

Not understanding the tests

Mixing unit tests and flaky integration tests

Testing multiple exit points

Tests that keep changing

7.5 Dealing with flaky tests

What can you do once you’ve found a flaky test?

Preventing flakiness in higher-level tests

8 Maintainability

8.1 Changes forced by failing tests

The test is not relevant or conflicts with another test

Changes in the production code’s API

Changes in other tests

8.2 Refactoring to increase maintainability

Avoid testing private or protected methods

Keep tests DRY

Avoid setup methods

Use parameterized tests to remove duplication

8.3 Avoid overspecification

Internal behavior overspecification with mocks

Exact outputs and ordering overspecification

Part 4 Design and process

9 Readability

9.1 Naming unit tests

9.2 Magic values and naming variables

9.3 Separating asserts from actions

9.4 Setting up and tearing down

10 Developing a testing strategy

10.1 Common test types and levels

Criteria for judging a test

Unit tests and component tests

Integration tests

API tests

E2E/UI isolated tests

E2E/UI system tests

10.2 Test-level antipatterns

The end-to-end-only antipattern

The low-level-only test antipattern

Disconnected low-level and high-level tests

10.3 Test recipes as a strategy

How to write a test recipe

When do I write and use a test recipe?

Rules for a test recipe

10.4 Managing delivery pipelines

Delivery vs. discovery pipelines

Test layer parallelization

11 Integrating unit testing into the organization

11.1 Steps to becoming an agent of change

Be prepared for the tough questions

Convince insiders: Champions and blockers

Identify possible starting points

11.2 Ways to succeed

Guerrilla implementation (bottom-up)

Convincing management (top-down)

Experiments as door openers

Get an outside champion

Make progress visible

Aim for specific goals, metrics, and KPIs

Realize that there will be hurdles

11.3 Ways to fail

Lack of a driving force

Lack of political support

Ad hoc implementations and first impressions

Lack of team support

11.4 Influence factors

11.5 Tough questions and answers

How much time will unit testing add to the current process?

Will my QA job be at risk because of unit testing?

Is there proof that unit testing helps?

Why is the QA department still finding bugs?

We have lots of code without tests: Where do we start?

What if we develop a combination of software and hardware?

How can we know we don’t have bugs in our tests?

Why do I need tests if my debugger shows that my code works?

What about TDD?

12 Working with legacy code

12.1 Where do you start adding tests?

12.2 Choosing a selection strategy

Pros and cons of the easy-first strategy

Pros and cons of the hard-first strategy

12.3 Writing integration tests before refactoring

Read Michael Feathers’ book on legacy code

Use CodeScene to investigate your production code appendix Monkey-patching functions and modules index

Front matter

foreword to the second edition

The year must have been 2009. I was speaking at the Norwegian Developers Conference in Oslo. (Ah, Oslo in June!) The event was held in a huge sports arena. The conference organizers divided the bleachers into sections, built stages in front of them, and draped them with thick black cloth in order to create eight different session “rooms.” I remember I was just about finished with my talk, which was about TDD, or SOLID, or astronomy, or something, when suddenly, from the stage next to me, came this loud and raucous singing and guitar playing.

The drapes were such that I was able to peer around them and see the fellow on the stage next to mine, who was making all the noise. Of course, it was Roy Osherove.

Now, those of you who know me know that breaking into song in the middle of a technical talk about software is something that I might just do, if the mood struck me. So as I turned back to my audience, I thought to myself that this Osherove fellow was a kindred spirit, and I’d have to get to know him better.

And getting to know him better is just what I did. In fact, he made a significant contribution to my most recent book, The Clean Coder, and spent three days with me co-teaching

a TDD class. My experiences with Roy have all been very positive, and I hope there are many more.

I predict that your experience with Roy, in the reading of this book, will be very positive as well, because this book is something special.

Have you ever read a Michener novel? I haven’t; but I’ve been told that they all start at “the atom.” The book you’re holding isn’t a James Michener novel, but it does start at the atom—the atom of unit testing.

Don’t be misled as you thumb through the early pages. This is not a mere introduction to unit testing. It starts that way, and if you’re experienced you can skim those first chapters. As the book progresses, the chapters start to build on each other into a rather startling accumulation of depth. Indeed, as I read the last chapter (not knowing it was the last chapter), I thought to myself that the next chapter would be dealing with world peace—because, I mean, where else can you go after solving the problem of introducing unit testing into obstinate organizations with old legacy systems?

This book is technical—deeply technical. There’s a lot of code. That’s a good thing. But Roy doesn’t restrict himself to the technical. From time to time he pulls out his guitar and breaks into song as he tells anecdotes from his professional past or waxes philosophical about the meaning of design or the definition of integration. He seems to relish regaling us with stories about some of the things he did really badly in the deep, dark past of 2006.

Oh, and don’t be too concerned that the code is all in C#. I mean, who can tell the difference between C# and Java anyway? Right? And besides, it just doesn’t matter. He may use C# as a vehicle to communicate his intent, but the lessons in this book also apply to Java, C, Ruby, Python, PHP, or any other programming language (except, perhaps COBOL).

If you’re a newcomer to unit testing and test-driven development, or if you’re an old hand at it, you’ll find this book has something for you. So get ready for a treat as Roy sings you the song, “The Art of Unit Testing.”

And Roy, please tune that guitar!

foreword to the first edition

When Roy Osherove told me that he was working on a book about unit testing, I was very happy to hear it. The testing meme has been rising in the industry for years, but there has been a relative dearth of material available about unit testing. When I look at my bookshelf, I see books that are about test-driven development specifically and books about testing in general, but until now there has been no comprehensive reference for unit testing—no book that introduces the topic and guides the reader from first steps to widely accepted best practices. The fact that this is true

is stunning. Unit testing isn’t a new practice. How did we get to this point?

It’s almost a cliché to say that we work in a very young industry, but it’s true. Mathematicians laid the foundations of our work less than 100 years ago, but we’ve only had hardware fast enough to exploit their insights for the last 60 years. There was an initial gap between theory and practice in our industry, and we’re only now discovering how it has impacted our field.

In the early days, machine cycles were expensive. We ran programs in batches. Programmers had a scheduled time slot, and they had to punch their programs into decks of cards and walk them to the machine room. If your program wasn’t right, you lost your time, so you desk-checked your program with pencil and paper, mentally working out all of the scenarios, all of the edge cases. I doubt the notion of automated unit testing was even imaginable. Why use the machine for testing when you could use it to solve the problems it was meant to solve? Scarcity kept us in the dark.

Later, machines became faster and we became intoxicated with interactive computing. We could just type in code and change it on a whim. The idea of desk-checking code faded away, and we lost some of the discipline of the early years. We knew programming was hard, but that just meant that we had to spend more time at the computer, changing lines and symbols until we found the magical incantation that worked.

We went from scarcity to surplus and missed the middle ground, but now we’re regaining it. Automated unit testing marries the discipline of desk-checking with a newfound appreciation for the computer as a development resource. We can write automated tests in the language we develop in to check our work—not just once, but as often as we’re able to run them. I don’t think there is any other practice that’s quite as powerful in software development.

As I write this, in 2009, I’m happy to see Roy’s book come into print. It’s a practical guide that will help you get started and also serve as a great reference as you go about your testing tasks. The Art of Unit Testing isn’t a book about idealized scenarios. It teaches you how to test code as it exists in the field, how to take advantage of widely used frameworks, and, most importantly, how to write code that’s far easier to test.

The Art of Unit Testing is an important title that should have been written years ago, but we weren’t ready then. We are ready now. Enjoy.

One of the biggest failed projects I worked on had unit tests. Or so I thought. I was leading a group of programmers creating a billing application, and we were

doing it in a fully test-driven manner—writing the test, then writing the code, seeing the test fail, making the test pass, refactoring, and starting all over again.

The first few months of the project were great. Things were going well, and we had tests that proved that our code worked. But as time went by, requirements changed. We were forced to change our code to fit those new requirements, and when we did, tests broke and had to be fixed. The code still worked, but the tests we wrote were so brittle that any little change in our code broke them, even though the code was working fine. It became a daunting task to change code in a class or method because we also had to fix all the related unit tests.

Worse yet, some tests became unusable because the people who wrote them left the project, and no one knew how to maintain the tests or what they were testing. The names we gave our unit testing methods weren’t clear enough, and we had tests relying on other tests. We ended up throwing out most of the tests less than six months into the project.

The project was a miserable failure because we let the tests we wrote do more harm than good. They took more time to maintain and understand than they saved us in the long run, so we stopped using them. I moved on to other projects, where we did a better job writing our unit tests, and we had some great successes using them, saving huge amounts of debugging and integration time. Since that first failed project, I’ve been compiling best practices for unit

Another random document with no related content on Scribd:

the death of Charles XII., also before that of Gustav III., the island became visible, and it is even said that a king one time carved his name on a stone on the island, and that stone and name, when, on another occasion the island was visible, were to be seen.

Whether the island was now again visible by some power of the Trolls in unison with the water spirits is not known; it is enough that the island appeared, and that the lord of the manor became possessed with a great desire to go to and inspect it.

He expressed a wish that his wife and boys should accompany him. The mother, who foresaw misfortune, opposed the project with all her energy, and upon her knees begged and prayed her husband to postpone his visit, but without avail.

Finally, the willful man took the boys, leaving his wife at home, and rowed out to the island. Just as the boat touched the enchanted island both boys sprang upon it, and at the same instant both island and boys vanished from the father’s sight to be seen no more.

The poor mother mourned herself to death, and the father departed to foreign lands, where he also died, but the building on Katrineholm has never since been occupied, and there is little probability that any one will in the future prosper in it. [60]

[Contents]

E S.1

Upon a small headland which juts from the north into Lake Bolmen, lies an old mansion, Tiraholm, by the peasantry called Tira.

A long time ago there lived here a knight who had a wife and an only child, a beautiful daughter, named Malfred. In the whole country there was not another so fair, and the fame of her beauty traveled far and wide, alluring many suitors to her feet. But Malfred was unmoved by their attentions and turned them away, one after the other.

One day a stately knight, Ebbe Skamelson by name, who had just returned from foreign lands, where he had won his golden spurs, drew up in the court-yard.

With downcast eyes and blushing cheeks the young lady extended her hand when they met, to greet the stranger, who courteously returned her salutation.

The stranger knight became for a time a guest at Tiraholm, and the report soon went out, to the grief of many swains who had indulged in dreams of sooner or later winning the hand of the beautiful maiden, that Ebbe Skamelson and Malfred were betrothed. But, as both were still young, the Knight expressed a desire to join the Crusades to the Holy Land, where he hoped to [61]add to his honors, and stipulated that he be given seven years, at the end of which time he promised to return and celebrate his nuptials.

Some time after Ebbe departed, the old Knight, Malfred’s father, died, and it became very lonesone for the daughter and mother in Tiraholm. Year after year passed with no word from Ebbe. The roses

of the young maiden’s cheeks faded and the dark eyes lost their lustre. The mother advised a remedy and betrothed her to another.

Under the impression that Ebbe had fallen by the sword of the infidels she prepared a wedding feast, and the newly betrothed couple were duly joined according to the rites of the church.

But just as the wedding guests sat themselves at table a gold-laced Knight rode into the court at great speed. The bride became pale under her crown, but the mother, who recognized in the stranger the Knight Ebbe, hastened to meet him in the yard, and reminded him that the seven years had passed, at the same time informing him that his love now sat in the bridal chair with another

In great anger the Knight sprang to his horse, drew his sword, and after reproaching her for breaking her promise, with one blow he severed her head from her body. His sword still dripping with blood, he sprang from his saddle and into the hall where the festivities were in progress, where the bride sank under his sword, and the bridegroom at another deadly blow fell by her side.

Overtaken by repentance the murderer flung himself [62]upon his horse and rode away into the dark forest, but the pricking of his conscience allowed him no rest. Night and day he saw the apparitions of his victims, and nowhere could he find an escape from them.

Finally he determined to go to Rome, and at the feet of the Holy Father ask absolution from his crimes. A large sum of money procured for him from the Pope the desired indulgence, but absolution from a man did not possess the power to quiet his conscience, still his soul’s pain or quell the storm raging in his heart. He then returned to the home of his love, and asked the authorities to impose upon him the severest punishment.

After a long deliberation he was sentenced by the court to be chained hand and foot, in which condition he must visit and pass a day in each one of the three hundred and sixty-five islands in Lake Bolmen. The condemned man went at once about the execution of his sentence. In order that he might get from one island to the other he was given a small boat with which, like a wounded bird, he laboriously propelled himself on his terrible journey.

When, at the end of the year, his sentence was completed he went ashore on the estate of Anglestadt in the district of Sunnebro. Here he went up to a village and rested over night in a barn. Meantime his sorrowful fate had made a deep impression upon the people. A bard had composed a song reciting the woes of Ebbe, and a soothsayer had predicted that upon hearing the song sung Ebbe’s chains would fall off and his death follow immediately. While he was [63]lying concealed in the barn, a milkmaid came in the morning to milk the cows. She began to sing “Knight Ebbe’s Song,” to which he listened with intense interest. At the conclusion of the last verse he cried out with loud voice: “Some is true and some is false.”

Thoroughly frightened, the girl sprang into the house and related what had happened. In great haste the people gathered around the barn where Ebbe was lying, commanding him to inform them where he came from and who he was. Still cumbered by his chains he crawled from his shelter and gave his name, at the same time requesting them to conduct him to the churchyard.

Between the village and the church of Anglestadt lies a stone sunken in the ground. When he came to this Ebbe mounted it, raised his eyes to heaven and cried out: “If I am worthy to be buried in consecrated ground, so let it be!”

Instantly the fetters fell from his hands and feet and he sank to the earth a corpse.

Those present took his body and carried it to the church where they buried it in the path outside the churchyard wall, so that all who went into the churchyard should tramp upon his grave. But the next night a long section of the wall, right in front of the grave, was miraculously thrown down. The peasants at once relaid it, but the next night it was again leveled. It was then understood that these happenings were signs that the unfortunate man should be allowed a resting place in consecrated ground, whereupon the churchyard was extended so that the grave was enclosed by its [64]walls, and a low stone even to this day marks the resting place of the outcast. From the fetters, which for a long time hung in Anglestadt church, three iron crosses, resembling the small crosses which were in former times set up in memory of the departed, have been made and placed upon the present church. [65]

1

See also J. Allvini’s description of Vestbo Municipality. The same legend is also current in Halland, with the difference that Ebbe’s lady love is said to have resided upon an estate in Tiveden, and that the remains of the exiled Knight now lie under a granite rock near the entrance to Gallinge Church ↑

[Contents]

J T.1

In Ingeltrop, a parish of North Wedbo, there once lived a farmer who had a servant named Johan. [66]

One day a traveler arrived from Myntorp Inn, and the farmer having been notified that it was his turn to furnish a conveyance for him to the next inn, Johan was sent to the pasture to catch a horse. A halter thrown over his shoulder, he set out, whistling the latest love song. Arriving at the pasture, it was soon clear to him that “Bronte” was in no humor to submit to the halter, and though he now and then allowed himself to be approached, no sooner was the attempt made to lay hold on him than he was off, with head and heels in the air, to a safe distance. Johan persevered, perspiration streaming from his forehead, but in vain. Angered at last, he began to swear in a most ungodly manner, still pursuing the horse until his progress was suddenly checked by a high cliff, to the very base of which he had run before discovering it. Naturally casting his glance upward, as he halted, he saw, sitting upon a crag, a beautiful maiden, apparently combing her hair.

“Are you there, my dear boy?” called the maiden.

Johan, not easily frightened, answered her cheerily:

“Yes, my sweetheart.”

“Come here, then,” called the maiden.

“I can’t,” replied Johan.

“Try, Johan.” And he did, to his astonishment finding a foothold on the smooth cliff where before no unevenness was discoverable, and soon he was at the maiden’s side. She looked at him with great, wondering eyes, then, suddenly enveloping him in a mist, clouded his understanding so that he was no longer master of his movements, and was, in fact, transformed completely from the Johan he had been to a being like [67]his companion. He forgot horse, home, relatives and friends. Half unconscious, he was conducted into the mountain, and was gone from the sight and power of those who would seek him.

“Bronte” was in harness many good days thereafter, and the farmer became the driver, for, as his sons were growing up, he did not wish to hire another servant in Johan’s stead.

One day, many years after Johan’s disappearance, it was again the farmer’s turn to furnish a horse to a traveler. Grumbling at the fate of Johan, he went to the pasture.

“It was too bad for the boy,” said he to himself. “I wonder if he has been caught by the Trolls?” At the same time he chanced to look upward at the cliff where the servant had seen the Troll maiden, and there stood Johan, but with lusterless eyes, staring into vacancy.

“Johan, my dear boy, is that you?” shouted the farmer. “Come down.”

“I can not,” answered Johan, with husky, unnatural voice.

Hereupon the farmer threw his cap to Johan, which the latter picked up and put on his head.

“Come down,” cried the farmer, “before the Trolls come. In the name of the saints, come down.”

“I can’t,” said Johan again.

Then the farmer threw his clothes up, garment after garment, and when Johan had clothed himself in them he received power enough that he was able to crawl down the cliff. His master took him by the [68]hand, and without looking back they hastened home, the farmer repeating:

“Pshaw! you cunning black Trolls! As a stone, I’ll quiet your wicked tongues that they may neither evil think nor speak or do ought against me.”

They arrived home, the one dressed the other naked. The traveler was obliged to procure another horse, for in the house of the farmer the joy was so great that none there had a thought of driving him. Johan was never again the same man as before, but remained gloomy and rarely spoke.

His master asked him many times what his occupation was in the mountain, but upon this subject he was silent. It happened that Johan was taken sick and called for a confessor, to whom, when he confessed his sins, he related also his experience in the mountain. His chief employment, he said, had been to steal food for the Trolls. For this purpose the Trolls put a red hat upon him, when he could, in a very short time, fly to Jönköping through locked doors and into the merchants’ stores, where he took corn, salt, fish and whatever he wished. From the Troll cap he received such power that he could take a sack of rye under each arm and a barrel of fish upon his back, and fly as lightly through the air as with no burden whatever.

“It was wrong of me and hard on the merchants,” said Johan, “but it was the fault of the Trolls. If there were no Trolls in the world the merchants would become rich, but now they must pay tribute, and so are kept on the verge of bankruptcy.” And Johan was done. [69]

1 Before the days of railroads and regularly equipped stage lines, it was the duty, established by law, of the farmers and others owning horses to, in their turn, furnish travelers with means of conveyance from the inn of their neighborhood to the next Upon the arrival of a traveler at an inn a servant was dispatched to the neighbor whose turn it was, and he was expected to promptly furnish horse, wagon and driver. ↑

[Contents]

T L T.

Many hundreds of years ago, at a time when Sweden was invaded by enemies, the people of Stenbrohult gathered their money and jewelry together and concealed them in a large copper kettle, which they sunk to the bottom of Lake Möckeln.

There it lies to-day and will lie for all time, though many have touched it with poles when driving fish into their nets. Meantime, at each touch, it has moved further away until it now lies near the outlet of the lake, where it is so deep that it can not be reached.

When the other residents of the place hid their treasures in the lake there was a rich farmer who buried his silver at Kalfhagsberg in two cans. Shortly after he died so suddenly that no opportunity was given to dig them up. Immediately following his death, two lights were seen every evening over the place where the treasures lay hidden, a sure sign that an evil spirit or dragon had appropriated the treasure.

A poor cottager heard of it, and knowing that man may acquire undisputed possession of the treasures of the earth, if dug upon a Thursday evening and carried away without looking back or uttering a word to any one, he already regarded himself as good as the owner of the wealth. Betaking himself to the place, he succeeded in getting the cans out of the mountain, but on the way home he met one after another of his neighbors [70]who asked where he had been. The old man knew well that the evil spirits had a hand in this, and that what appeared to be his neighbors was nothing less than the spirits transformed, and he was, therefore, stubbornly quiet. But finally he met the priest, who stood by the wayside and greeted him as he was passing with a “good evening, neighbor.” Hereupon the

old man dared keep quiet no longer, but took his hat off and saluted, “good evening, father,” in return, at the same instant he tripped against a root and dropped the cans. When he stopped to pick them up there lay in their stead only a pair of little old birch-bark boxes, and the old man was compelled to go home, his mission fruitless. [71]

[Contents]

T T F S.1

Many years ago there lived in Gullbjers a family of peasants, who had a daughter, Elsa. As she was the only child she was [72]much adored, and her parents sought in every way to anticipate her slightest wish. As soon as she had been confirmed she was sent to the city to learn how to sew, and also city manners and customs. But in the city she acquired little other knowledge than how to adorn herself, and to scorn housework and manual labor.

When she was twenty years old she won the love of an industrious and honorable young farmer, named Gunner, and before many months had gone by they were man and wife.

In the beginning all was pleasure, but she soon began to weary with her many household duties. Early one morning, shortly before Christmas, there was life and activity in Gunner’s yard. Elsa had hardly risen from bed when the servant, Olle, sprang in and said:

“Dear mistress, get ready our haversacks, for we are going to the woods, and we must be off if we are to get back before evening.”

“Dear mother, the leaven is working,” called one of the servant girls, “and if you will come out now we will have more than usually good bread.”

The butcher, Zarkis, who had already stuck a large hog and several small pigs, had just stepped in to get the accustomed dram, when old Brita came rushing after material for candle wicks. Lastly came Gunner, out of patience because the servant had not yet started for the woods.

“My departed mother,” said he, with kindly earnestness, “always prepared everything the night before when people were expected to go to work early in the [73]morning, and I have requested you to do likewise, Elsa. But do not forget the loom, my dear; there are now only a few yards of cloth remaining to be woven, and it will not do to allow it to lie in the way over the holidays.”

Now, wholly out of patience, Elsa rushed in a rage out of the kitchen to the house in which the loom stood, slammed the door furiously behind her and cast herself weeping upon a sofa.

“No!” shrieked she. “I will no longer endure this drudgery. Who could have thought that Gunner would make a common housewife of me, to wear my life out thus? Oh, unhappy me! Is there no one who can help and comfort a poor creature?”

“I can,” replied a solemn voice, and before her stood a white-haired man with a broad-brimmed hat upon his head. “Do not be alarmed,” continued he, “I came to proffer you the help for which you have just wished. I am called Old Man Hoberg. I know your family to the tenth and eleventh generations. Your first ancestor bade me stand godfather to his first born. I could not be present at the christening, but I gave a suitable godfather’s present, for I would by no means be the meanest. The silver I then gave was unfortunately a blessing for no one, for it begot only pride and laziness. Your family long ago lost the riches, but the pride and laziness remain; nevertheless I will help you, for you are at heart good and honest.

“You complain at the life of drudgery you are compelled to lead,” continued he, after a short silence; “this comes from your being unaccustomed to work, [74]but I shall give you ten obedient servants, who shall be at your bidding and faithfully serve you in all your undertakings.” Whereupon he shook his cloak, and ten comical little creatures hopped out and began to put the room in order.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
Full download The art of unit testing, third edition: with examples in javascript roy osherove pdf d by Ebook Home - Issuu