Book Review: xUnit Test Patterns

Well, as I related in a post on my personal blog before this shared blog came into being, I was going to read a book every two weeks and give a review of it. I should have said that I’d read 200-300 pages per week instead. My latest book is 800+ pages, and it took me three weeks, even when I skimmed several pieces of it. It was, however, an outstanding book.

If you write software, this book is an absolute must-read. If you’ve never written an automated test, it will convince you why you should. If you’re test-infected, it will give you advice and principles to follow that guide you toward more effective testing and, ultimately, more effective software. For anyone in between, this book has something for you, too. It’s written in a language-agnostic way and has advice applicable to testing with any of the “xUnit” family: any test framework that works along the same lines as Java’s JUnit.

xUnit Test Patterns
Refactoring Test Code
by Gerard Meszaros

As its name suggests, it’s a patterns book, which means that Mike would like it because a large part of it is a catalog of various test-related patterns that the author has collected. Another chunk of the book is taken up by a catalog of test smells. This still leaves plenty of room, though, for Meszaros to provide a thorough introduction to software testing–primarily unit testing, but with plenty of consideration for other test scopes as well–and to give a detailed overview of best practices in testing.

Part One of the book is the narrative, non-catalog part and could be a book all by itself. It covers a lot of theoretical ground with topics like goals of automated testing, guiding principles to consider when writing tests, and various philosophies of testing along with their pros and cons. On the more “practical application” front, there’s a basic introduction to the internal workings of the xUnit family frameworks, which is foundational knowledge for many patterns, and a ton of practical advice revolving around real-world examples of difficult testing situations and methods of dealing with them. You could read just this part of the book–under 200 pages–and come away a better developer for it.

Part Two is the catalog of test smells. Each smell is the formalization of a testing problem that was discussed in Part One. A statement of the problem, its symptoms and possible causes, and various suggested solutions are all collected into a neat, tidy package for easy access. The smells cover a wide variety of things from the seemingly trivial difficult-to-read tests to major systemic problems like unreliable test suites due to sporadic test failures.

Part Three is the pattern catalog, where the solutions to aforementioned problems and best practices are formalized. Each pattern has a brief summary up front, a description of how and when to use it appropriately, examples of how the pattern looks in code (in various languages), and examples of how to refactor problem code to solve the problem effectively with the pattern. The initial summary is highly useful in that you can read through the summaries of all 60 or so of the patterns in a very short time and have a feel for which ones you should look into more deeply for a particular situation.

I have to say one more time that you must read this book! It pulls patterns, practices, and more from many other sources and organizes them all in a well-written, easy-to-read reference that will provide a strong foundation for testing efforts in any xUnit framework. Beyond that, I’ve yet to mention the author’s efforts to establish a common vocabulary of test patterns by assembling them all in one place with a strict system of names. While this may seem trivial in comparison to the content of the patterns, the lack of such a vocabulary can lead to real difficulties in communication when four people use a name like “Test Stub” in four very different ways. Learn a better way.

Get this book. Read it. Use it. Live it.

  • Share/Bookmark

Configuring NHibernate in a Multiple Project Layout

I recently had to setup NHibernate in a multiple project c#, asp.net MVC solution. Since most of the tutorials and books only show a basic single project layout I thought I would post an example of how to configure NHiberate with a multi-project solution.

The main problem I had was that my model objects or entity objects were in a separate project than my database access code which contained the .hbm.xml mapping files. When I tried to configure NHibernate with the basic examples I was getting an “NHibernate.MappingException : No persister for: YourClass” exception. I was still getting that exception even after changing the .hbm.xml files to be an “Embedded Resource”. I finally figured out that my .hbm.xml files needed to reference the ModelLayer assebmly and my NHibernate.Cfg.Configuration.AddAssembly() needed to reference the DataAccessLayer assebmly. See screen shots and code examples below for more details.

Solution layout

  • DataAccessLayer
    • Duh. Database code
      • References
        • ModelLayer
  • ModelLayer
    • Model objects
  • MvcAgain (web layer)
    • ASP.Net project
    • References
      • ModelLayer
      • ServiceLayer
  • ServiceLayer
    • Business logic
    • Reusable logic
    • References
      • ModelLayer
      • DataAccessLayer

Model objects Car.cs and CarLot.cs

using System.ComponentModel.DataAnnotations;
namespace MvcAgain.Models {
    public class Car {
        [Required]
        public virtual int Id {get; set;}
        [StringLength(35), Required]
        public virtual string Manufacturer {get; set;}
        [StringLength(35), Required]
        public virtual string Model {get; set;}
        public virtual CarLot Lot {get; set;}
    }
}//end of Car.cs

using Iesi.Collections;
using System.ComponentModel.DataAnnotations;
namespace MvcAgain.Models {
    public class CarLot {
        [Required]
        public virtual int Id { get; protected set; }
        [StringLength(35), Required]
        public virtual string Name { get; protected set; }
        public virtual ISet Cars { get; protected set; }
    }
}//end of CarLot.cs


Car.hbm.xml and CarLot.hbm.xml

These .hbm.xml files are in the DataAccessLayer project, but they reference the ModelLayer assembly.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="ModelLayer"
                   namespace="MvcAgain.Models">
  <class name="MvcAgain.Models.Car" lazy="false" table="cars">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="Model"/>
    <property name="Manufacturer"/>
    <many-to-one name="Lot" class="CarLot" column="lotid" not-null="true">
    </many-to-one>
  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="ModelLayer"
                   namespace="MvcAgain.Models">
  <class name="MvcAgain.Models.CarLot" lazy="false" table="carlots">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="Name"/>
    <set name="Cars" inverse="true">
        <key column="lotid"/>
        <one-to-many class="Car"/>
    </set>
  </class>
</hibernate-mapping>


NHibernateSessionFactory.cs (NHibernate configuration code)

using NHibernate.Cfg;
using NHibernate;
namespace MvcAgain.DataAccessLayer {

    public class NHibernateSessionFactory {

        private static ISessionFactory sessionFactory = null;

        private static ISessionFactory SessionFactory {
            get {
                if(sessionFactory == null) {
                    Configuration configuration = new Configuration();
                    configuration.Configure();
                    //note: you must use the name of the assembly
                    //that contains the .hbm.xml mapping files.
                    //For this example NHibernate will load all .hbm.xml files it
                    //finds in the DataAccessLayer assembly
                    configuration.AddAssembly("DataAccessLayer");
                    sessionFactory = configuration.BuildSessionFactory();
                }
                return sessionFactory;
            }
        }

        public static ISession OpenSession() {
            return SessionFactory.OpenSession();
        }
    }//end of class
}//end of namespace


ModelLayer assembly name in the properties pane.



  • Share/Bookmark

Spring Patterns: Best Practices and Design Strategies Book Review

This is a book review of Pro Java™ EE Spring Patterns: Best Practices and Design Strategies Implementing Java EE Patterns with the Spring Framework

About the Book

Apress describes this book as

Pro Java™ EE Spring Patterns focuses on enterprise patterns, best practices, design strategies, and proven solutions using key Java EE technologies including JSP™, servlets, EJB™, and JMS APIs.

This Java EE patterns resource, catalog, and guide, with it’s patterns and numerous strategies, documents and promotes best practices for these technologies, implemented in a very pragmatic way using the Spring Framework and it’s counters.

The book was written by Dhrubojyoti Kayal. Dhrubojyoti works as a senior consultant with Capgemini Consulting. He has more than five years of experience developing and designing applications and products leveraging Enterprise Java technologies. His areas of interest include the Spring Framework, ORM, SOA, refactoring, prefactoring, and performance engineering.

In this book the author takes us through the process of refactoring a legacy system built without using patterns or the Spring Framework into a shiny new system leveraging Spring and design patterns. Throughout the book he takes us through this practical, real-word example.

Introduction to the MVC Pattern

The first chapter introduces you to the MVC pattern. I think that this book is for a well versed J2EE professional developer, who would probably be familiar with the pattern, so this chapter may have been overkill. However, the basis of this book is to refactor an antiquated web application to use Spring and the Spring MVC, so a clear and thorough understanding of the MVC pattern is necessary. Most readers of this book can probably skip this chapter. On the other hand it is written well enough that it would serve a good resource for any rookie developers that you might be working with who need to learn this pattern.

Patterns

Each chapter of this book takes you through the concepts of a common pattern, describes how the Spring Framework is used to implement that pattern, and then replaces the legacy insurance system code with new spring code. Once you get into the patterns, the book is divided into four major sections. These sections are

This division helps to keep the conversation between the author and the reader focused and also makes it easy to find later when you come back to reference this information.

The Best Part

My favorite part about this book is that it is a patterns book. I like to read books based on patterns more than any other type of book. Patterns books are naturally broken down into small, manageable chunks of information. When written, patterns are usually described using a common, easy to follow template and are small enough to read an entire pattern in one sitting, whether that sitting be while you are eating your lunch or a quick read before hitting the pillow. Because they are written this way, it is easy to read this book very quickly and easy to find what you are looking for when you come back later for specific information. Pattern-based books are great.

I also liked this book because it takes you through all the layers of a real-world system. As developers we all have to work with legacy code. If you don’t your very lucky. Because this is real world it is very easy to follow along with the author and the project and see the benefits of Spring and refactoring to patterns.

Needs Refactoring

It’s a good, well-written book, but there are some things that I think need to be changed.

First, as with any book with code examples, there is some odd code that should be rewritten or removed. For example, there is a business bean that has a DAO injected into it via a setter. However, this bean also contains a getter for that DAO. This is not common practice and, in my opinion, not recommended.

And second, all of the presentation patterns are in a single chapter, and all of the business and integration patterns are in their own chapters. I think each pattern should have had its own chapter. I just prefer the clearer boundaries between patterns and I think it would make finding these patterns later, when I come to reference the book, a little easier.

You Should Read this Book

You should read this book if you are a developer who uses Spring, and especially if you use Spring MVC. This is a great resource and a great way to learn about how Spring utilizes patterns internally to implement its services. Of course it also shows you how to use Spring to add patterns to your current code base. You should read this book if you use an MVC framework that is not Spring MVC and are considering Spring MVC for  your next project or are considering adapting Spring MVC to your current project. While this book deals with more than just the Spring MVC, the entire presentation tier section is based on it.

Or Not…

I do recommend this book to most developers, however you should not read Spring Patterns if you are not well versed with J2EE/JEE and the Spring framework. If you are looking to learn Spring, there are other books that might be more suitable.

Here are some last notes, straight from Apress, about this book:

Table of Contents

Finally, here is the table of contents:

  • Share/Bookmark

Next Page →