Mittwoch, 2. Dezember 2009

JUnit 4.8 is released

JUnit News

http://www.junit.org/node/581

and here a the release notes

http://kentbeck.github.com/junit/doc/ReleaseNotes4.8.html

Example JUnit Test With Test Steps

Some times in a tests we want to have separate test steps that means to ensure the run of more then one statement e.g. assert statements.

Here a simple JUnit test, this tests show how such tests steps can look in a JUnit 4.X tests:

public class StackTest {

 Stack stack;

 @Before public void createStack() {
  stack = new Stack();
 }

 @Test public void push() {
  new Steps() {
   
   @Step public void setupPushElementsInStack() {
    stack.push("Element One");
    stack.push("Element Three");
    stack.push("Element X");
   }
   
   @Step public void verifyStackSizeIsThree() {
    assertEquals(2, stack.size());
   }
   
   @Step public void verifyStackElementOne() {
    assertElementIs(0, "Element One");
   }
   
   @Step public void verifyStackElementTwo() {
    assertElementIs(1, "XY");
   }
   
  };
 }

 private void assertElementIs(int position, String expected) {
  String element = stack.get(position);
  assertEquals(expected, element);
 }
}

And here the test result:


And here the code of the Steps class:

public class Steps {

 private List testStepFailures = new ArrayList();
 
 {
  run();
 }
 
 public final void run() {
  Method[] methods = getClass().getMethods();
  for (Method method : methods) {
   try 
   {
    Step step = method.getAnnotation(Step.class);
    if(step != null){
     method.invoke(this);
    }
   } 
   catch (Exception e) 
   {
    TestFailure failure = new TestFailure();
    failure.method = method;
    failure.exception = e;
    testStepFailures.add(failure);
   } 
  }
  if(testStepFailures.size() > 0){
   throw new TestStepsFailureException(testStepFailures);
  }
 }

}

Sonntag, 29. November 2009

Create a EMF Model Instance with JAVA internal DSL

Sometimes a Java internal DSL is engough for creating a model instance (ok Eclipse xText is a cool tool :-)) a good example for Java DSL is the JMock DSL for creating mock objects. Here in my Blog I will show a small example for a Java internal DSL to get a EMF model instance. Here is the EMF ECore model (meta model) for my running example:


A small example model to describe components of an application and which services this components provides, only example stuff not a good model anyway.

Here a model instance with plain EMF Java code:

ComponentFactory factory = ComponentFactory.eINSTANCE;
   
Interface orderServiceInterface = factory.createInterface();
orderServiceInterface.setName("dsl.OrderService");

Port orderServicePort = factory.createPort();
orderServicePort.setProvides(orderServiceInterface);
  
Component order = factory.createComponent();
order.setName("order");
order.getPorts().add(orderServicePort);
  
Interface loggerServiceInterface = factory.createInterface();
loggerServiceInterface.setName("dsl.LoggerService");
 
Port loggerServicePort = factory.createPort();
loggerServicePort.setProvides(loggerServiceInterface);
  
Component logger = factory.createComponent();
logger.setName("logger");
logger.getPorts().add(loggerServicePort);
 
Application shop = factory.createApplication();
shop.setName("shop");
shop.getComponents().add(order);
shop.getComponents().add(logger);

And here the same model instance created with a Java internal DSL (Gof Builder Pattern):

Application shop = ApplicationBuilder.create("shop", new Components() {{

 component("order", new Ports() {{

  provides( OrderService.class );

 }});
 
 component("logger", new Ports() {{
  
  provides( LoggerService.class );
  
 }});

}});


Links:
In one of my next posts I will show the results of a Eclipse xText generated text DSL for the example model.

Dienstag, 24. November 2009

yUML - cool UML tool

yUML is a web based small UML tool and it makes a lot of fun to create diagrams with it, here my first use case example diagram made with yUML

No real use cases only a diagram for test yUML...

Links:

Sonntag, 22. November 2009

JUnit Rule for jMock instead of the JMock Runner

In JUnit 4.7 there is new feature called "Rules" see my previous posts...

The jMock framework comes with a JUnit 4.X runner for verifying the mock object  states after each test run. Now with rules all the stuff of the runner can be done in one rule. I have implemented an example rule based on the JMock runner (see also jMock JIRA http://jira.codehaus.org/browse/JMOCK-237), here is the code of my example implementation:
 
import org.jmock.Mockery;
import org.jmock.lib.AssertionErrorTranslator;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

public class JUnitRuleMockery extends Mockery implements MethodRule {

 public JUnitRuleMockery() {
    setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE);
 }
 
 public Statement apply(final Statement base, final FrameworkMethod method,
   Object target) {
  return new Statement() {
   @Override
   public void evaluate() throws Throwable {
    try {
     base.evaluate();
    } catch(Throwable exp) {
     if(!isExceptionExpectedByTestMethod(exp, method)) {
      throw exp;
     }
    }
    assertIsSatisfied();
   }
  };
 }

 protected boolean isExceptionExpectedByTestMethod(Throwable exp, FrameworkMethod method) {
  Test test = method.getAnnotation(Test.class);
  return test.expected().equals(exp.getClass());
 }

}

Example Test which use the rule:
import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

// No jMock specific Runner needed only the default JUnit runner
public class FrameworkCommandProviderTest { 
 
@Rule
    public JUnitRuleMockery context = new JUnitRuleMockery() {{
       setImposteriser(ClassImposteriser.INSTANCE);
    }};
  
 InternalSystemBundle mockInternalSystemBundle;
 
 Framework mockFramework;
 
 CommandInterpreter mockCommandInterpreter;
 
 FrameworkCommandProvider mockFrameworkCommandProvider;
 
 FrameworkCommandProvider frameworkCommandProvider;
 
 @Before 
 public void setUp(){
  
  // Create mock object for system bundle
  mockInternalSystemBundle = context.mock(InternalSystemBundle.class);
  // Mocking the getContext Method, returns always null
  context.checking(new Expectations() {{
   allowing (mockInternalSystemBundle).getContext(); will(returnValue(null));
  }});
  
  // Create mock object for framework
  mockFramework = context.mock(Framework.class);
  // Set the mock object system bundle into the framework mock
  mockFramework.systemBundle = mockInternalSystemBundle;
  
  // Create mock object for command interpreter
  mockCommandInterpreter = context.mock(CommandInterpreter.class);
  
  // Create mock object for the SUT class, this mock will be used to mock methods in the SUT
  mockFrameworkCommandProvider = context.mock(FrameworkCommandProvider.class);
  
  // Create the SUT object of type FrameworkCommandProvider
  frameworkCommandProvider = new FrameworkCommandProvider(mockFramework) {
   
   /** 
    * Mock the SUT Method getBundleFromToken(...)
    * All method calls will delegate to a mock 
    * of the same type then the SUT object 
    */
   @Override
   protected AbstractBundle getBundleFromToken(CommandInterpreter intp, String token, boolean error) {
    // delegate the call to a mock object.
    return mockFrameworkCommandProvider.getBundleFromToken(intp, token, error);
   }
  };
  
 }
 
 @Test(expected=RuntimeException.class) 
 public void _bundle_OneArgumentsAndBundleNotFoundByToken() throws Exception { 
  final String firstToken = "myBundleName[1.0.0]";
  // Setup mock context
  context.checking(new Expectations() {{
   // one argument
   one (mockCommandInterpreter).nextArgument(); will(returnValue(firstToken));
   // next calles return null
   allowing (mockCommandInterpreter).nextArgument(); will(returnValue(null));
   
   // getBundleFromToken returns null
   one (mockFrameworkCommandProvider).getBundleFromToken(mockCommandInterpreter, firstToken, true);
   will(returnValue(null));
   
  }});
  
  // invoke the _bundle() method
  frameworkCommandProvider._bundle(mockCommandInterpreter);
  
  throw new RuntimeException();
 }

}

xUnit test implementation pattern for mocking methods in a SUT object

Simple test implementation pattern for mock a method in the SUT object. The pattern is interesting when  you would refactor a method in legacy system. Before you can start with the refactoring stuff you must write a test for the method with a high coverage (Refactoring details see Martin Fowlers great book "Refactoring - Improving the Design of Existing Code").

The idea is to test only the legacy method you would like to refactor (to get quick a high coverage),  there for we want mock all method calls which will be invoked from this method. Normal mocking frameworks like EasyMock or JMock for Java can create mock objects for interfaces and classes. This pattern shows how this tools can be used for mock an internal method in the SUT object.

The idea, overwrite all method which should be mocked in the SUT object and delegate the calls to a mock object of the same type as the SUT object.

Example setup code with JMock as mocking framework:
...
@Before 
public void setUp(){
   ...
   // Create mock object for the SUT class, this mock will be used to mock methods in the SUT
   mockFrameworkCommandProvider = context.mock(FrameworkCommandProvider.class);
  
   // Create the SUT object of type FrameworkCommandProvider
   frameworkCommandProvider = new FrameworkCommandProvider(mockFramework) {
   
    /** 
     * Mock the SUT Method getBundleFromToken(...)
     * All method calls will delegate to a mock 
     * of the same type then the SUT object 
     */
     @Override
     protected AbstractBundle getBundleFromToken(CommandInterpreter intp, String token, boolean error) {
         // delegate the call to a mock object.
         return mockFrameworkCommandProvider.getBundleFromToken(intp, token, error);
     }
   };
}
...

The code with a example test which expected a mock method call:
...
@Test 
public void _bundle_OneArgumentsAndBundleNotFoundByToken() throws Exception { 
 final String firstToken = "myBundleName[1.0.0]";
 // Setup mock context
 context.checking(new Expectations() {{
  // one argument
  one (mockCommandInterpreter).nextArgument(); will(returnValue(firstToken));
  // next calles return null
  allowing (mockCommandInterpreter).nextArgument(); will(returnValue(null));
   
  // getBundleFromToken returns null
  one (mockFrameworkCommandProvider).getBundleFromToken(mockCommandInterpreter, firstToken, true);
  will(returnValue(null));
 }});
 
 // invoke the _bundle() method
 frameworkCommandProvider._bundle(mockCommandInterpreter);
}
... 

Downsides:
  • Much code for the test setup to overwrite all the methods which should be mocked in the SUT object
  • Only protected, package and public methods can be mocked by this approach
  • Private methods can't be mock with this pattern
  • In the test code it's not clear which SUT methods are mocked and which not

Here the whole example test code:
package org.eclipse.osgi.framework.internal.core;

import static org.junit.Assert.*;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMock.class)
public class FrameworkCommandProviderTest {

 // Create mock context and activate mocking for java classes.
 Mockery context = new JUnit4Mockery() {{
     setImposteriser(ClassImposteriser.INSTANCE);
    }};
 
    InternalSystemBundle mockInternalSystemBundle;
 
 Framework mockFramework;
 
 CommandInterpreter mockCommandInterpreter;
 
 FrameworkCommandProvider mockFrameworkCommandProvider;
 
 FrameworkCommandProvider frameworkCommandProvider;
 
 @Before 
 public void setUp(){
  
  // Create mock object for system bundle
  mockInternalSystemBundle = context.mock(InternalSystemBundle.class);
  // Mocking the getContext Method, returns always null
  context.checking(new Expectations() {{
   allowing (mockInternalSystemBundle).getContext(); will(returnValue(null));
  }});
  
  // Create mock object for framework
  mockFramework = context.mock(Framework.class);
  // Set the mock object system bundle into the framework mock
  mockFramework.systemBundle = mockInternalSystemBundle;
  
  // Create mock object for command interpreter
  mockCommandInterpreter = context.mock(CommandInterpreter.class);
  
  // Create mock object for the SUT class, this mock will be used to mock methods in the SUT
  mockFrameworkCommandProvider = context.mock(FrameworkCommandProvider.class);
  
  // Create the SUT object of type FrameworkCommandProvider
  frameworkCommandProvider = new FrameworkCommandProvider(mockFramework) {
   
   /** 
    * Mock the SUT Method getBundleFromToken(...)
    * All method calls will delegate to a mock 
    * of the same type then the SUT object 
    */
   @Override
   protected AbstractBundle getBundleFromToken(CommandInterpreter intp, String token, boolean error) {
    // delegate the call to a mock object.
    return mockFrameworkCommandProvider.getBundleFromToken(intp, token, error);
   }
  };
  
 }
 
 @Test 
 public void _bundle_OneArgumentsAndBundleNotFoundByToken() throws Exception { 
  final String firstToken = "myBundleName[1.0.0]";
  // Setup mock context
  context.checking(new Expectations() {{
   // one argument
   one (mockCommandInterpreter).nextArgument(); will(returnValue(firstToken));
   // next calles return null
   allowing (mockCommandInterpreter).nextArgument(); will(returnValue(null));
   
   // getBundleFromToken returns null
   one (mockFrameworkCommandProvider).getBundleFromToken(mockCommandInterpreter, firstToken, true);
   will(returnValue(null));
  }});
  
  // invoke the _bundle() method
  frameworkCommandProvider._bundle(mockCommandInterpreter);
 }

}

Run the Example Test:
To run the test you need the equinox osgi implementation as SUT, you can get the equinox source from the eclipse CVS ("pserver:dev.eclipse.org/cvsroot/rt/org.eclipse.equinox/framework/bundles/org.eclipse.osgi/").

Links:

Tipp Eclipse JDT Java Editor - Option Escape text when pasting into a string ...

Cool option in Eclipse java editor "Escape text when pasting into a string literal".


Montag, 9. November 2009

EMF - Create a Dynamic Model Instance

For developing EMF models the option "Create Dynamic Instance" can be very usefull. When you have a EMF meta model and you want to create a first test instance of the meta model the option "Create Dynamic Instance"can be used see the screenshot...



For create Dynamic Instance do a right click on the RootObject of your model that you would want to instantiate. The screen shot bellow shows the editor for editing a EMF based model dynamic in eclipse as XMI.



More details on dynamic instantiation in EMF:
http://wiki.eclipse.org/Dynamic_Browsing_and_Instantiation_Capabilites_in_EMF

Sonntag, 1. November 2009

Eclipse Tipp - Java Type Labels on Java Files

To see the type of a java file by an label in eclipse activate the option

Eclipse Preferences -> General -> Appearance -> Label Decorations -> Java Type Indicator

The result:











The Preference Page:

Dienstag, 13. Oktober 2009

JUnitExt Prerequisite as JUnit 4.7 Rule

The JUnit 4 Extensions project provides a annotation for specify precondition for a test. For example you have a database integration test, it makes no sense to run this test when the database is down. Therefor you can use the JUnit 4 Extension annotation @Prerequisite. But the disadvantage is, you must use a JUnit 4 Extension specific JUnit test runner @RunWith(AnnotationRunner.class). The Problem with the runner is when you must use a other runner for example the spring DI test runner in the test the approach did not work well.

But a feature like the @Prerequisite annotation of JUnit 4 Extensions project is very nice to have. In JUnit 4.7 there for the JUnit rules comes in mind, here is a small code example how a rule solution for the @Prerequisite annotation can look like.


Here the test with the @Prerequisite annotation and without specific test runner:


public class DatabaseTest {

@Rule
public PrerequisiteRule rule = new PrerequisiteRule();

@Test
@Prerequisite(requires="databaseIsAvailable")
public void testFindAllUsers() throws Exception {
// Database test stuff here
}

@Test
public void testGetDataSource() throws Exception {
// No Database test stuff here
}

public boolean databaseIsAvailable(){
return false;
}

}


The test result will be:



























This test without errors can look like this one:



public class DatabaseTest {

@Rule
public PrerequisiteRule rule = new PrerequisiteRule();

@Test
@Prerequisite(requires="databaseIsAvailable")
public void testFindAllUsers() throws Exception {
// Database test stuff here
}

@Test
public void testGetDataSource() throws Exception {
// No Database test stuff here
}

public boolean databaseIsAvailable(){
return true;
}


}



And here a very basic rule implementation for the test:


public class PrerequisiteRule implements MethodRule{

public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Prerequisite annotation = method.getMethod().getAnnotation(Prerequisite.class);
if(annotation != null){
String requiresMethodname = annotation.requires();
Method requiresMethod = target.getClass().getMethod(requiresMethodname);
Boolean result = (Boolean) requiresMethod.invoke(target);
if(!result.equals(true)){
fail("Test requires "+requiresMethodname);
}
}
base.evaluate();
}
};
}

}


Ok the implementation of the rule is very basic there is no good error handling for example ...

Feel free for comments ...

Links:
- http://junitext.sourceforge.net/
- http://www.junit.org/

Mittwoch, 30. September 2009

JUnit 4.7 Rule for cleanup EasyMock object after test

I try the JUnit 4.7 rule feature and I wrote a super small ExternalResource class for easymock cleanup (reset) here is the example code that makes mocking setup easier:

import static org.easymock.EasyMock.*;

import java.util.ArrayList;
import java.util.List;

import org.junit.rules.ExternalResource;

/**
* Mock resource class for cleanup mock objects after each test run.
*/
public class MockResource extends ExternalResource {

private List mockObjects = new ArrayList();

public   T createMockObject(Class clazz) {
T mock = createMock(clazz);
mockObjects.add(mock);
return mock;
}

protected void after() {
for (Object mock : mockObjects)
reset(mock);
} 
} 


/**
* Example test which use the rule for cleanup the mocks.
*/
public class ObserverTest {

@Rule
public MockResource mockResources = new MockResource();

Observer mockObserver = mockResources.createMockObject(Observer.class);

@Test
public void testObserver() throws Exception {
Car subject = new Car();
subject.register(mockObserver);
mockObserver.refresh(subject);
replay(mockObserver);
subject.setName("Porsche");
verify(mockObserver);
}
} 
With the mock resource rule no tearDown Method will be need the reset is be done by the rule.
Come to think of it, there will be sure more mocking work which can be done by a JUnit rule. So I think the rule feature is very nice and makes JUnit tests better to read ...

Montag, 28. September 2009

JPA with Hibernate Criteria API

I didn't know that with JPA Vendor Hibernate, the Criteria API of Hibernate can be used. That can be done by getting the Hibernate Session from the JPA Entity Manager.

Here a example code:

Session session = (Session) entityManager.getDelegate();
Criteria hibernateCriteria = session.createCriteria(Position.class);
// List with all positions
List list = hibernateCriteria.list();

Ok the question is would you like to have a dependency to Hibernate in your source code when you would use JPA, I think you wold not like to have, but technical it works...

Nicer would be a Criteria API that depends only on JPA and is not JPA vendor specific. For JPA 1 I didn't know a project that provides such a Criteria API that works fine, but in JPA 2 I think the Crititeria API would be part of the standard, so I think thats a good news.

Another example:

// Implementation with Hibernate Criteria
public List getPositionList() {
Session session = (Session) entityManager.getDelegate();
Criteria hibernateCriteria = session.createCriteria(Position.class);
hibernateCriteria.addOrder(Order.desc("createTime"));
return hibernateCriteria.list();
}

// Implementation with plain JPA
public List getPositionList() {
Query query = entityManager.createQuery("SELECT p FROM Position p ORDER BY p.createTime DESC");
return query.getResultList();
}