Montag, 30. November 2009

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: