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
  }
}

Continue reading

Advertisements
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) );

Continue reading

Tags: , ,