Effective Unit Testing
eBook - ePub

Effective Unit Testing

A guide for Java developers

Lasse Koskela

Compartir libro
  1. 258 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Effective Unit Testing

A guide for Java developers

Lasse Koskela

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Summary Effective Unit Testing is written to show how to write good tests—tests that are concise and to the point, expressive, useful, and maintainable. Inspired by Roy Osherove's bestselling The Art of Unit Testing, this book focuses on tools and practices specific to the Java world. It introduces you to emerging techniques like behavior-driven development and specification by example, and shows you how to add robust practices into your toolkit. About Testing Test the components before you assemble them into a full application, and you'll get better software. For Java developers, there's now a decade of experience with well-crafted tests that anticipate problems, identify known and unknown dependencies in the code, and allow you to test components both in isolation and in the context of a full application. About this Book Effective Unit Testing teaches Java developers how to write unit tests that are concise, expressive, useful, and maintainable. Offering crisp explanations and easy-to-absorb examples, it introduces emerging techniques like behavior-driven development and specification by example.Programmers who are already unit testing will learn the current state of the art. Those who are new to the game will learn practices that will serve them well for the rest of their career. Purchase of the print book comes with an offer of a free PDF, ePub, and Kindle eBook from Manning. Also available is all code from the book. About the Author Lasse Koskela is a coach, trainer, consultant, and programmer. He hacks on open source projects, helps companies improve their productivity, and speaks frequently at conferences around the world. Lasse is the author of Test Driven, also published by Manning.
What's Inside

  • A thorough introduction to unit testing
  • Choosing best-of-breed tools
  • Writing tests using dynamic languages
  • Efficient test automation

Table of Contents

PART 1 FOUNDATIONS

  • The promise of good tests
  • In search of good
  • Test doubles
  • PART 2 CATALOG
  • Readability
  • Maintainability
  • Trustworthiness
  • PART 3 DIVERSIONS
  • Testable design
  • Writing tests in other JVM languages
  • Speeding up test execution

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Effective Unit Testing un PDF/ePUB en línea?
Sí, puedes acceder a Effective Unit Testing de Lasse Koskela en formato PDF o ePUB, así como a otros libros populares de Informatik y Softwareentwicklung. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Editorial
Manning
Año
2013
ISBN
9781638353881
Categoría
Informatik

Part 1. Foundations

This first part of the book aims to give you, the reader, and me, the author, a shared context to build upon throughout the chapters. With the ultimate purpose of this book being to help you improve your ability to write good tests, chapter 1 begins with an overview of what kind of value we can extract from writing tests in the first place. Once we’ve discussed the dynamics of programmer productivity and the kind of impact that our tests—and the quality of our tests—can have on it, we’ll conclude the chapter with a brief introduction to two methods that are closely related to automated tests: test-driven development (TDD) and behavior-driven development (BDD).
Chapter 2 takes on the challenge of defining what makes for a good test. In short, we’d like to write tests that are readable, maintainable, and reliable. Part 2 will go deeper into this rabbit hole by turning the question around and reviewing a collection of examples of what we don’t want to get.
Part 1 concludes with chapter 3, which tackles one of the most essential tools in the modern programmer’s tool belt—test doubles. We’ll establish the legitimate uses of test doubles, such as isolating code so that it can be tested properly, and we’ll make a distinction between the types of test doubles we might reach out to. Finally, we’ll throw in guidelines for making good use of test doubles to help you get the benefits without stumbling on common pitfalls.
After reading these first three chapters you should have a good idea of what kind of tests you want to write and why. You should also have a clear understanding of test doubles as a useful vehicle for getting there. The rest of this book will then build on this foundation and give you more ammunition for your journey in the real world.

Chapter 1. The promise of good tests

In this chapter
  • The value of having unit tests
  • How tests contribute to a programmer’s productivity
  • Using tests as a design tool
When I started getting paid for programming, the world looked a lot different. This was more than 10 years ago and people used simple text editors like Vim and Emacs instead of today’s integrated development environments like Eclipse, Net-Beans, and IDEA. I vividly remember a senior colleague wielding his Emacs macros to generate tons of calls to System.out.println as he was debugging our software. Even more vivid are my memories of deciphering the logs those printouts ended up in after a major customer had reported that their orders weren’t going through like they should.
That was a time when “testing” for most programmers meant one of two things—the stuff that somebody else does after I’m done coding, or the way you run and poke your code before you say you’re done coding. And when a bug did slip through, you’d find yourself poking and prodding your code again—this time adding a few more logging statements to see if you could figure out where things went wrong.
Automation was a state-of-the-art concept for us. We had makefiles to compile and package our code in a repeatable manner, but running automated tests as part of the build wasn’t quite in place. We did have various shell scripts that launched one or two “test classes”—small applications that operated our production code and printed what was happening and what our code was returning for what kind of input. We were far from the kind of standard testing frameworks and self-verifying tests that report all failures in our assertions.
We’ve come a long way since those days.

1.1. State of the union: writing better tests

Today, it’s widely recommended that developers write automated tests that fail the build when there are regressions. Furthermore, an increasing number of professionals is leaning on a test-first style of programming, using automated tests not for protecting against regression but for aiding them in design, specifying the behavior they expect from code before writing that code, thereby validating a design before verifying its implementation.
Being a consultant, I get to see a lot of teams, organizations, products, and code bases. Looking at where we are today, it’s clear that automated tests have made their way into the mainstream. This is good because without such automated tests, most software projects would be in a far worse situation than they are today. Automated tests improve your productivity and enable you to gain and sustain development speed.
Help! I’m new to unit testing
If you aren’t that familiar with writing automated tests, this would be a good time to get acquainted with that practice. Manning has released several books on JUnit, the de facto standard library for writing unit tests for Java, and the second edition of JUnit in Action (written by Petar Tahchiev, et al. and published in July 2010) is a good primer for writing tests for all kinds of Java code, from plain old Java objects to Enterprise JavaBeans.
In case you’re at home with writing unit tests but you’re new to Java or JUnit, perhaps all you need to get the most out of this book is to first check out appendix A, so that you won’t have trouble reading the examples.
Automated tests being mainstream doesn’t mean that our test coverage is as high as it should be or that our productivity couldn’t improve. In fact, a significant part of my work in the last five years or so has revolved around helping people write tests, write tests before code, and especially write better tests.
Why is it so important to write better tests? What’ll happen if we don’t pay attention to the quality of our tests? Let’s talk about what kind of value tests give us and why the quality of those tests matters.

1.2. The value of having tests

Meet Marcus. Marcus is a prominent programming wiz who graduated two years ago and joined the IT group of a local investment bank, where he’s been developing the bank’s online self-service web application. Being the youngest member of the team, he kept a low profile at first and focused his energy on learning about the banking domain and getting to know “the way things are done here.”
A few months on, Marcus started noticing that a lot of the team’s work was rework: fixing programmer mistakes.[1] He started paying attention to the types of mistakes the team was fixing and noticed that most of them would’ve been caught fairly easily by unit tests. Marcus started writing unit tests here and there when he felt that the code was particularly prone to having mistakes in it.
1 For some reason, people referred to them as errors, defects, bugs, or issues.
Tests help us catch mistakes.
Time went on and the rest of the team was writing unit tests, too, here and there. Marcus had become test-infected and rarely left a piece of code that he touched without fairly good coverage from automated tests.[2] They weren’t spending any more time fixing errors than they had before, but for the first time, their total number of open defects was on the decline. The tests started having a clearly visible impact on the quality of the team’s work.
2 The term test-infected was coined by Erich Gamma and Kent Beck in their 1998 Java Report article, “Test-Infected: Programmers Love Writing Tests.”
Almost a year had passed since Marcus wrote the first test in their code base. On his way to the company Christmas party, Marcus realized how time had flown and started thinking back to the changes they’d seen. The team’s test coverage had grown quickly and had started stabilizing in the recent weeks and months, peaking at 98% branch coverage.
For a while Marcus had thought that they should push that number all the way to 100%. But in the last couple of weeks, he’d more or less made up his mind—those missing tests wouldn’t give them much more value, and putting any more effort into writing tests wouldn’t yield additional benefit. A lot of the code that wasn’t covered with tests was there only because the APIs they used mandated the implementation of certain interfaces that Marcus’s team wasn’t using, so why test those empty method stubs?
100% Code Co...

Índice