Archive for ‘TDD’

October 25, 2012

2k Unit Tests in One Year – Lessons Learned

by Stefan

I was in the lucky position to work on a green field project during the last two years. At the time the project started someone pointed me to the clean code books by Robert C. Martin. The proposed approach to professional software development seemed to be refreshingly different to the approach I was used to before. So the direction was clear: most of the code that has been created during the last two years was written test driven. I found myself writing an amount of tests in a way I never did before. I actually wrote something between 1k and 2k tests in the first year which is more than 5 tests per day. Today, the whole test suite is more than twice the size and provides a code coverage of more than 90 percent. (footnote: the UI code is actually split using an MVC like approach. The view code is not tested at all, as it doesn’t make sense IMHO to test the composition and labeling of widgets with unit tests.)

The Debugger was my best friend

When I started developing software in my first job, the debugger was my best friend. I used it to understand existing code, and even more important, to verify that my logics work. I was really proud that I was able to watch and inspect several variables simultaneously. Debugging code was one of the great insights I gained and I considered it to be the key to mastering software complexity.

read more »

Advertisements
June 27, 2012

Eclipse JUnit Editor Templates

by Stefan

I recently had to set up a new Eclipse (STS) workspace and one of the first things I do is configuring some templates for JUnit Tests. Most of the tests have a skelleton like this:

import org.junit.Before;
import org.junit.Test;

public class SocialNetworkGeneratorTest {
  private SocialNetworkGenerator generator;

  @Before
  public void setUp() {
    generator = new SocialNetworkGenerator();
  }

  @Test
  public void testSth() {
    // do sth with "generator" field
  }
}

The following Eclipse Editor Template creates the setup method and stores an instance of the class under test in a field. It also handles all necessary imports.

${:import(org.junit.Before)}

  private ${type} ${name};

  @Before
  public void setUp() {
    ${name} = new ${type}();
    ${cursor}
  }

Simply assign a catchy name for the template like setup and I’m sure you will have even more fun when writing JUnit Tests.

Adding a Java Editor Template in Eclipse

For the sake of completeness the template for test cleanup:

${:import(org.junit.After)}
  @After
  public void tearDown() {
    ${cursor}
  }

June 29, 2011

Eclipse: Running all JUnit tests at once

by Stefan

When developing test driven it is essential to be able to run all existing unit tests over and over again as fast as possible. When the application gets larger the natural way to modularize is to distribute the code among multiple projects. I am not aware of tooling that ships with Eclipse and that allows you to run all JUnit tests based on a multi-project selection or on a selected working set.

I’ve used several workarounds in the past (Ant script, TestSuites, Maven build), but none was really satisfying. I recently stumbled upon the ClassPathSuite by Johannes Link which offers exactly what I was looking for. The library internally scans the classpath for classes with JUnit4 annotated methods and then executes all found tests. Sounds simple. This classpath-based solution also has the advantage that any Eclipse classpath container can be used so this works with OSGi-based bundles as well as with Maven projects, for instance.

Setup a ClassPathSuite test project

All you need to do is to create a new project and add a single class:

import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
public class RunAllTests {
}

If you’re with Maven, the library can be referenced like this (if not follow this link):

 <repositories>
    <repository>
      <id>http://maven.xwiki.org</id>
      <url>http://maven.xwiki.org/externals</url>
    </repository>
  </repositories>
  
  <dependencies>
    <dependency>
      <groupId>cpsuite</groupId>
      <artifactId>cpsuite</artifactId>
      <version>1.2.5</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

read more »

June 18, 2011

Tutorial GWT Request Factory – Part II

by Stefan

In the first part of the tutorial we set up EntityProxy classes for our back-end entities pizza and ingredient. A PizzaRequestContext was introduced that represents the client-side facade for the PizzaDao in the back-end.

Now, a natural next step is to write some kind of controller logic that uses the PizzaRequestContext to communicate with the back-end. Let’s call this controller PizzaManager:

package cleancodematters.client;

import com.google.web.bindery.requestfactory.shared.Receiver;

public class PizzaManager {

  private final PizzaRequestFactory factory;

  public PizzaManager( PizzaRequestFactory factory ) {
    this.factory = factory;
  }

  public void findById( Long id, Receiver<PizzaProxy> receiver ) {
    factory.context().findById( id ).with( "ingredients" ).fire( receiver );
  }
}

The manager gets a RequestFactory instance passed into the constructor. This is a good idea as creating the RequestFactory requires a GWT#create() call which doesn’t work in plain JUnit tests. See my previous post on how to use GIN get the instance injected automatically.

How can we test the implementation of findById() with plain JUnit tests? One approach is to use a mocked PizzaRequestFactory instance. In our test we then have to ensure that the method chain factory.context().findById( id ).with( "ingredients" ).fire( receiver ) is called correctly. This test code is hard to write and also tied very closely with implementation details. In general, fluent interfaces are nice to read (but often violate the Law of Demeter, btw) but testing this code with mocks can be really cumbersome.

A better approach in my view is to use GWT’s RequestFactory infrastructure and replace the transport layer with some “in memory” processing that is independent of the browser infrastructure. Fortunately, GWT already provides a class for this: InProcessRequestTransport. This approach has another advantage: We also test the error-prone reference of nested entities (with( "ingredients" ) in the example).

read more »

May 19, 2011

GWT RequestFactory with GIN

by Stefan

Creating GWT RequestFactory instances requires a GWT.create() call. These calls should be outside of your classes under test, as GWT.create() internally invokes native JavaScript code. This causes a ExceptionInInitializerError when run as a plain JUnit test.

A very elegant solution is to use Dependency Injection with GIN and let the framework create and assemble both the RequestFactory and corresponding RequestContext instances. In general, using DI is a good idea for all layers of business application, and GIN brings the well-known concepts of Guice into the GWT world.

read more »

May 12, 2011

Testing asynchronous services with Mockito

by Stefan

Programming asynchronous services can be really challenging. Examples are asynchronous webservices, GWT server calls or event-based systems like widget toolkits. Usually, clients have to pass a callback to the service on which a method is called on success or error containing the data to proceed or an error message.
A typical asynchronous system is your local pizza service:

package cleancodematters;

public class PizzaService {

  public interface PizzaEvent {
    void pizzaAvailable( Pizza pizza );
  }

  public void orderPizza( String name, PizzaEvent event ) {
    // some async processing, calls event on finish
  }
}

read more »

May 9, 2011

Having fun with GWT EntityProxies in JUnit tests

by Stefan

GWT comes with a nice feature called RequestFactory that provides a high level abstraction of client-server communication. This includes a mechanism for entity conversion which allows you to have, for instance, JPA-mapped entities in the backend and independent DataTransferObjects (called Entity Proxy)  in the presentation layer. The definition of the Entity Proxies looks like this:

package cleancodematters;

import com.google.gwt.requestfactory.shared.EntityProxy;
import com.google.gwt.requestfactory.shared.ProxyFor;

@ProxyFor(Pizza.class)
public interface PizzaProxy extends EntityProxy {
  void setName( String name );
  String getName();

  void setPrice( Double price );
  Double getPrice();

  boolean isOrdered();
  void setOrdered( boolean ordered );
}

Entity + Interface + Tests = Trouble

As you can see, the entities are in fact interfaces (and created and populated by the framework for you). This has some advantages. For example, GWT can internally track changes and only send deltas over the wire. However, things get complicated when it comes to testing. If you want to create an entity and populate it with two parameters you find yourself writing code like this for every test case:

	PizzaProxy pizza = mock( PizzaProxy.class );
	when( pizza.getName() ).thenReturn( "Funghi" );
	when( pizza.getPrice() ).thenReturn( Double.valueOf(6.99) );

read more »

Tags: , ,