Eclipse Yoxos Services Downloads Blogs About
Home > Blogs >

Holger Staudacher

on May 3rd, 2012Server-Side Apps with access to device functionality aka. accessing the iOS Geolocation API with Java.

Whenever we talk about server-side apps and RAP mobile, one topic always comes up: how to access native functionality like Geolocation or the Camera. With this post I want to show you how we access this functionality on the server-side. At writing, we’ve implemented Geolocation Support, and more additions are planned for the near future.

I have to point out one thing first.  When you take look at RAP mobile from a very abstract view, it is nothing more than an object synchronization mechanism. That is, if a button (or any other widget) is created on the server it also needs to be created on the client. This is exactly the same for native functionality. When the server needs the location of the client it has to tell the client that it needs the location. Then, the client has to tell the server the location and this cycle starts over again. The challenge in this approach is to hook the location to the right session. Fortunately, RAP’s server side has solved these issues a long time ago, and it’s pretty easy to hook this information together.

One issue that remains is that SWT has no API for native access because it was made for the desktop. So, a new API is required that needs be an abstraction for all devices. But wait a minute – this sounds like a well known problem that has been solved already. I’m referring to Phonegap/Cordova. This technology created a JavaScript abstraction for accessing native functionality within HTML5 Apps. And, IMHO, these guys did a really great job and there is no need to reinvent the wheel. We decided to take the Phonegap API as a template and created a very similar Java API. Our first result is the Geolocation API which is located in the RAP mobile server code. As mentioned in previous posts, everything on the server side is open source, including this API. The RAP mobile server code is located in the com.eclipsesource.rap.mobile*.jar and is included in the demos target. You can also take a look the Geolocation API here at github.

We have created a demo for the Location API, which you can see in the videos linked below. The source code for this demo is also located on github. To conclude, I can proudly say that with RAP mobile it’s now possible to access the Geolocation API of iOS and Android from Java by writing the code only once!


on Apr 20th, 2012Server-Side Apps with RAP mobile – the programming model

In my last post I gave you an overview of server-side apps and how they relate to RAP mobile. In this post I want to dive into some technical details. I’ll assume that you are a Java programmer and that you are familiar with servlets and tomcat. Not necessary but really helpful is some knowledge of OSGi.

So, let’s get started. To create RAP mobile Applications you’ll write Java Code only. This of course means you will have some dependencies. The basic dependencies that result from using RAP mobile are two open source jar files. One is the widget toolkit which includes the SWT API for writing UIs and some other server stuff. The widget toolkit is part of the Eclipse RAP project and is called RWT (RAP Widget Toolkit) and it’s jar file is named org.eclipse.rap.rwt_VERSION.QUALIFIER.jar. The second jar file is the RAP mobile jar itself. It’s called com.eclipsesource.rap.mobile_VERSION.QUALIFIER.jar and contains additional API and other mobile-related stuff. Of course these two jars have dependencies too. These are javax.servlet, org.json and a few others. They are included in the RAP mobile target (see the target definition file in the examples) and can also be consumed manually or via Maven.

Once you have set up your Java Project and dependencies (you can use this template) the first thing you’ll need to write is an ApplicationConfiguration. It can look like this:

public class Configuration implements ApplicationConfiguration {
 
  public void configure( Application application ) {
    Bootstrapper.bootstrap();
    application.addEntryPoint( "/my-app", MyEntryPoint.class, null );
  }
}

You may notice that the really interesting stuff happens in the configure method. This method will be called by the framework and is used to configure your environment. You’ll use the configure method most often to add IEntryPoints. An IEntryPoint marks the entry point of your UI code and can look like the following MyEntryPoint.  (If you want to go into more depth on the UI Code,  take a look at the SWT resources and the examples.)

public class MyEntryPoint implements IEntryPoint {
 
  public int createUI() {
    Display display = new Display();
    Shell shell = new Shell( display, SWT.NO_TRIM );
    shell.setLayout( new GridLayout( 1, false ) );
 
    Button button = new Button( shell, SWT.PUSH );
    button.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, false ) );
    button.setText( "Hello World" );
 
    shell.open();
    return 0;
  }
}

In the configure method of the ApplicationConfiguration you need to connect the entry point to a path, e.g. “/my-app”. This will make your application available using this URL http://SERVER:PORT/my-app. Next, you need to hook your ApplicationConfiguration Implementation to the framework.

At this point you need to make a choice between two RAP mobile operating modes. The easiest mode to use is RAP mobile together with plain servlet technology. For this variant you’ll write a web.xml to hook the framework to your application, similar to the example below:

<!--?xml version="1.0" encoding="UTF-8"?-->
 
org.eclipse.rwt.Configurator
my.Configurator
 
org.eclipse.rwt.engine.RWTServletContextListener
 
    rwtServlet
    org.eclipse.rwt.engine.RWTServlet
 
    rwtServlet
    /*

The more advanced operating mode is to use it together with OSGi, which I prefer because I like modularity much. But this requires that you have basic knowledge about OSGi and the service model. Hooking the ApplicationConfiguration in this scenario is pretty straight forward. All you have to do is register your implementation as an OSGi service and starting one more bundle called org.eclipse.rap.rwt.osgi. In an activator it can look like this:

public class Activator implements BundleActivator {
 
  private ServiceRegistration registration;
 
	public void start(BundleContext bundleContext) throws Exception {
	  Configuration configuration = new Configuration();
	  registration = bundleContext.registerService( ApplicationConfiguration.class.getName(),
	                                                configuration,
	                                                null );
	}
 
	public void stop(BundleContext bundleContext) throws Exception {
		registration.unregister();
	}
 
}

Now you can simply launch your OSGi framework – but, don’t forget the HttpService (it is in the org.eclipse.osgi.services bundle).  And now, the fun part. Point your mobile client to the url of your server and enjoy the mobile UI which should look like the advanced one below! icon smile Server Side Apps with RAP mobile   the programming model

Screen Shot 2012 04 20 at 9.29.10 AM Server Side Apps with RAP mobile   the programming model

If you haven’t tested the clients already, don’t hesitate to request them here. We have also created some examples which can be found at github.  In upcoming posts, we’ll provide a more detailed tutorial for both operating modes.

on Apr 16th, 2012Serving mobile devices with server-side apps

You may have read the title of this post and are asking yourself, “what the heck is a server-side app?”. Let me try to explain. When an app works with sensitive data there is always a security risk in storing the data on the device. If the device is lost or stolen the sensitive data is lost or worse, no longer confidential.  A server-side app can prevent this. Data is stored on the server and the client displays and manipulates it, but no data is stored locally. I think you’ve got it: server-side apps are nothing more than a thin client approach adopted to the mobile/app sector.

When you’re confronted with this problem, you’ve probably either started by designing the server application or are porting an existing server application to be accessible by mobile devices. So, your next step will be to plan how to visualize the server-side app on the clients. The most common approach is to build an App for iOS, Android and so on and render the data in a more or less generic UI. You’ll invest a lot of effort in creating and securing the communication between server and client to get your server-side app ready. And, you’ll have joined the club of developers, including me, who have reinvented the wheel once more.

This is the problem we are solving with RAP mobile. RAP mobile consists of a server and generic clients, with the server based on standard servlet technology and a kick-ass OSGi integration. The server’s open source and hosted within the Eclipse RAP project. The generic clients currently exist for iOS and Android, and in both cases, all the clients do is talk to the server and display a UI. But, every other server-side app does this too. What’s special here?

With usual server-side apps you have to couple the client to the server. The data and message contents are defined and the client needs to understand them, resulting in a more or less a tight coupling between these two all created by yourself. With RAP mobile, the work on communication is done by the framework for you. The server produces JSON based messages that the RAP mobile clients can understand. The messages contain information like “Create a Window, create a Button, set the text of the button to …”, (I think you get it). When you sketch this out it looks like this:

architecture Serving mobile devices with server side apps

This approach allows us and you (because the server’s open source) to come up with any client as long as it understands JSON. I think the major benefit RAP mobile brings is that you can concentrate on the server-side and your domain requirements, instead of programming a generic UI for every platform.

When you’ve read this far you might now be asking yourself, “When everything is on the server side and I don’t have to write a native UI for the mobile devices, eg. in Objective-C, how does the native UI get created?”  And now the Eclipse open source project comes into the game with Eclipse RAP. RAP provides a widget toolkit which is based on SWT, which means that you write your UI completely in Java. When RAP was created the goal was to enable a developer to create a desktop and a web application with the same code base. As a result, the RAP developers solved problems like multi-user awareness, clustering support, styling and many many more. In the meantime, we’ve gone even further and extended this idea to the mobile space. (And, we’re making good progress, because on the server side we’re working with a mature technology.) In short, it means that when you write a RAP mobile app for iOS, Android and so on, you don’t have to worry about the native client, but you can write your UI in plain Java and run it in the server.

If you’re hungry for more icon wink Serving mobile devices with server side apps , visit the RAP mobile website, watch the demo videos, clone the examples and run your own app. To join the developer preview, you’ll need to complete a short form but, in a few months we will move into an open beta. I hope you will have fun with this as much as I do. Any feedback is welcome.

on Mar 20th, 2012Simple JUnit4 templates for Eclipse

JUnit and Eclipse are a great combination, but one thing that I missed every time I worked with JUnit4 was the code templates. Currently, Eclipse ships with pre-defined templates for JUnit3 but not for JUnit4. So, I wrote three basic JUnit4 templates that can be imported from the “Templates” Preference Page. Take a look at the screenshot below to see how to get there. The templates are called test, setup and teardown. They all create method stubs with the right Annotation and the necessary static imports – pretty simple but I think its efficient. You can find the templates in this gist.

Screen Shot 2012 03 20 at 12.20.54 PM Simple JUnit4 templates for Eclipse

After importing the templates you can use them in a test class by typing the first letters of each template and use the content assist (Ctrl/cmd+space) to complete. This results in an assist like the one below. By pressing enter the template will be inserted into your class. Hope this makes test writing easier icon smile Simple JUnit4 templates for Eclipse

Screen Shot 2012 03 20 at 12.24.04 PM Simple JUnit4 templates for Eclipse

 

on Jan 23rd, 2012An OSGi JAX-RS connector Part 1: Publishing REST services

In a recent blog post Peter Kriens commented that the OSGi service model is as important as object-orientation. I feel the same – I don’t want to write software without this concept anymore. But for me, the service model only makes sense when it’s used together with the modularity OSGi provides. I think the modularisation layer is the greatest advantage of the OSGi platform and the services are really only there to simplify the communication between modules.

When it comes to developing a REST API with Java, this advantage is missing in most of today’s libraries (e.g. Restlet or Jersey), because the Java language still lacks modularity. But especially for the design of a REST API this concept can be a great benefit, because it overcomes the limitation of only being able to separate REST services by url and Java packages. With modularity the service implementations can be separated into modules which improves the maintainability and the beauty of the whole system a lot.

A few months ago I discovered JAX-RS for developing REST services. (Before that I used Restlet.) I have to say that the JAX-RS API makes it really easy to develop REST services. See this article for a how-to. A reference implementation of this API is Jersey. The cool thing about this implementation is that it plays really well together with the OSGi HttpService and it ships as bundles. In this way we have the option to actively deploy REST services into the HttpService. But is this how we want to publish REST services? To me, it’s not!

In my ideal world I would write my @Path annotated Pojos and publish them as OSGi services. That’s it. The runtime should take care of publishing and service wiring. Sadly, Jersey has no built-in feature for that. This is the reason I wrote a little OSGi-JAX-RS connector. The only thing the connector does is that it publishes OSGi services as REST services using JAX-RS. Of course, there are OSGi remote services, but using them does not allow the use of JAX-RS the way I’d prefer, namely as a lightweight additional bundle.

You can find the connector in GitHub. To make it work simply install it into your OSGi instance by using this jar. (You’ll also find a p2 repository there). That’s it. The only thing you have to take care of is writing the REST services like the one in this example.

@Path( "/osgi-jax-rs" )
public class ExampleService {
 
  @GET
  public String seyHello() {
    return "JAX-RS and OSGi are a lovely couple.";
  }
}

The activator can then look like this:

public class Activator implements BundleActivator {
 
  private ServiceRegistration<?> registration;
 
  @Override
  public void start( BundleContext context ) throws Exception {
    ExampleService exampleService = new ExampleService();
    registration = context.registerService( ExampleService.class.getName(), exampleService, null );
  }
 
  @Override
  public void stop( BundleContext context ) throws Exception {
    registration.unregister();
  }
}

Further instructions can be found in the README of the git repository. It also contains two examples for using this connector with and without declarative services. In the second part of this blog series I will show you how to configure the services using the OSGi Configuration Admin Service and publish services on different ports within the same OSGi instance. I hope you enjoy this connector as much as I do.

followme An OSGi JAX RS connector Part 1: Publishing REST services

on Jan 17th, 2012Continuous Integration Tests for REST APIs with Maven, Jetty and restfuse

As you might know from previous posts, most of my work time has something to do with the development of REST based systems. The systems we develop are mostly written in Java. To ensure that a system works, we have a step in our continuous integration process that executes integration tests before automated deployment is launched. With this short post I’d like to show you our setup for these integration tests because when I searched a few months ago the results were rare.

We write integration tests for REST systems with JUnit and restfuse. Check this post for a how-to on restfuse. Thanks to the Maven surefire plugin we can simply execute these tests in our maven build. Here is the build and dependency section of the test module’s pom.

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.9</version>
      <executions>
        <execution>
          <id>test</id>
          <phase>test</phase>
          <configuration>
            <testClassesDirectory>${project.build.outputDirectory}</testClassesDirectory>
          </configuration>
          <goals>
            <goal>test</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    ...
  </plugins>
</build>
 
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.8.1</version>
    <scope>test</scope>
  </dependency>  
  <dependency>
    <groupId>com.restfuse</groupId>
    <artifactId>com.eclipsesource.restfuse</artifactId>
    <version>1.0.0</version>
  </dependency>
</dependencies>

Most of our Java-REST applications ship as war files.  So, at this stage the question becomes, “How can I test the war file I just built?” One answer is to hot deploy the war file and run the tests against it. But, for a hot deployment we need a server running tomcat (or another servlet container), right? Actually, we don’t icon wink Continuous Integration Tests for REST APIs with Maven, Jetty and restfuse . We can simply embed a Jetty plugin into our maven build, start it and deploy our war file using the Maven Jetty plugin. The related section in the pom looks like this:

<build>
  <plugins>
    ...
    <plugin>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>maven-jetty-plugin</artifactId>
      <version>${jetty-version}</version>
      <configuration>
        <scanIntervalSeconds>10</scanIntervalSeconds>
        <stopKey>foo</stopKey>
        <stopPort>9090</stopPort>
        <contextPath>/</contextPath>
        <tmpDirectory>/tmp/work/</tmpDirectory>
        <webApp>/tmp/test.war</webApp>
        <daemon>true</daemon>
        <reload>manual</reload>
      </configuration>
      <executions>
        <execution>
          <id>start-jetty</id>
          <phase>test-compile</phase>
          <goals>
            <goal>deploy-war</goal>
          </goals>
        </execution>
        <execution>
          <id>stop-jetty</id>
          <phase>verify</phase>
          <goals>
            <goal>stop</goal>
          </goals>
        </execution>
      </executions>
    </plugin>  
    ...    
  </plugins>
</build>

It is important that we deploy the war file before the actual test phase, in our example, during test-compile. To make this work we need to copy the new war file into the configured directory before we run the maven build. This can be accomplished with a simple shell script.  The following snippet shows how it looked for our jenkins job:

rm -rf /tmp/work
mkdir /tmp/work
cp $WORKSPACE/../job/**/*.war /tmp/test.war

A few last points.  In our setup we split the integration test build from the main build but you can merge them together as well. And, when using restfuse an important thing to keep in mind is that you need to configure the port to be the same as the one jetty uses to run the tests.

That’s it – short but efficient. Maybe you have a similar approach to share in a comment with us?

followme Continuous Integration Tests for REST APIs with Maven, Jetty and restfuse

on Nov 16th, 2011Effective Mockito Part 5

With this effective Mockito Post I want to share a really simple pattern with you. We call this pattern “check answers” and we use it whenever we work with Mockito Answers. The code resulting from creating Mockito Answers generally looks ugly. But, as good programmers we care about test quality, right? icon smile Effective Mockito Part 5

Let’s see how we can make better looking answers using the “check answer” pattern. Mockito’s Answers are great when you need to verify that a method was called with specific parameters, or you need to execute an operation that also needs to be mocked. I’m sure you have seen situations where Answers were very useful. Let’s dive into a simple example. Our fancy program consists of three classes which are listed in the snippet below.

public class MyRuntimeState {
 
  private boolean state;
 
  public void setState( boolean state ) {
    this.state = state;
  }
 
  public boolean isTrue() {
    return state;
  }
 
}
 
 
public class MyDelegate {
 
  public void doSomething( MyRuntimeState state ) {
    // do some fancy operation
  }
 
}
 
 
public class MyObject {
 
  private final MyDelegate delegate;
 
  public MyObject( MyDelegate delegate ) {
    this.delegate = delegate;
  }
 
  public void operate() {
    MyRuntimeState state = new MyRuntimeState();
    state.setState( true ); // this is the important fact we want to test
    delegate.doSomething( state );
  }
 
}

As you can see we have the Types MyObject, MyDelegate and MyRuntimeState. MyObject needs a MyDelegate in its constructor. In the operate method, MyObject calls MyDelegate‘s doSomething method with a newly created MyRuntimeState object. Let’s assume that for some reason our fake system needs a MyRuntimeState with the state ‘true‘ to work (be creative – it’s just an example icon wink Effective Mockito Part 5 ).  So, MyObject needs to set the state of the MyRuntimeState object to true. This is exactly the case where Answers are useful to verify that the state is true within the doSomething invocation (we can probably also do this with verify in this example, but there are harder operations out there where verify can’t be used).  Let’s look at the test for this mechanism.

@RunWith( MockitoJUnitRunner.class )
public class MyObjectTest {
 
  @Mock
  private MyDelegate delegate;
  private MyObject myObject;
 
  @Before
  public void setup() {
    myObject = new MyObject( delegate );
  }
 
  @Test
  public void testSendsRightState() {
    doAnswer( new Answer<Object>() {
 
      @Override
      public Object answer( InvocationOnMock invocation ) throws Throwable {
        MyRuntimeState state = ( MyRuntimeState )invocation.getArguments()[ 0 ];
        assertTrue( state.isTrue() );
 
        return null;
      }
    } ).when( delegate ).doSomething( any( MyRuntimeState.class ) );
 
 
    myObject.operate();
  }
 
}

You see that it’s a fully working test that tests exactly what we want, but it’s also a smell. I dislike several things in the testSendsRightState method. The first thing is the method chaining over several lines. The second thing is that we have an indentation level of three which leads to unreadable code. The third thing is that we can’t see at a glance what will be tested. The fourth thing I don’t like is that the assert statement comes before the actual operate call at least in the writing of the code. The last thing is that this method is way too long.

Let’s try to get rid of most of the smells by simply doing one refactoring. You may say that this is obvious, and yes it is;). We need to extract the creation of the Answer object into a separate method. I name these methods createCheck***Answer (*** stands for a named check) because the answers that will be created are invoking the actual asserts. The result can look like this:

@Test
public void testSendsRightState() {
  Answer<Object> checkStateAnswer = createCheckStateAnswer();
  doAnswer( checkStateAnswer ).when( delegate ).doSomething( any( MyRuntimeState.class ) );
 
  myObject.operate();
}
 
private Answer<Object> createCheckStateAnswer() {
  return new Answer<Object>() {
 
    @Override
    public Object answer( InvocationOnMock invocation ) throws Throwable {
      MyRuntimeState state = ( MyRuntimeState )invocation.getArguments()[ 0 ];
      assertTrue( state.isTrue() );
 
      return null;
    }
  };
}

This simple refactoring has a huge impact on our test method. The test method has only a length of three lines of code now. The indentation level is one. The call chain fits into one line. Even the createCheckStateAnswer is more readable because it’s not surrounded by chained calls. One drawback still resists this solution. That is, that the assert is now called within another method. To me, this is a very low price to pay compared to the problems in the first test. And, the best thing about this solution is that when you only read the test method you see at first glance that an answer called checkStateAnswer was created that obviously does something like check a state. Other programmers should be able to understand most of the test method without reading the createCheckStateAnswer method.

I know that this solution is very simple and for you, may be obvious. But when I started with Answers I didn’t do this for reasons only the Programming Gods know now. If you have any other things related to Answers in your repertoire please share them with us in a comment.

followme Effective Mockito Part 5

Read the other Effective Mockito posts:

on Nov 14th, 2011Introducing restfuse – a JUnit Extension to test REST APIs

For several projects at EclipseSource we are creating REST APIs. I’m involved in most of them and there is one thing that bothers me with every project. That is, testing. I mean, of course we are writing our unit tests first and we mock our services to get fast unit tests, but at some point you also have to make sure that the whole system works with integration tests. And, when writing integration tests for REST APIs in Java, as far as I know, there are currently only two solutions.

The first one is to write plain JUnit tests and do all the requests yourself within the test methods (maybe with the help of utilities). The other option is to use a library called rest-assured. This library provides a kind of DSL for testing REST APIs. You can write your tests with JUnit and use mockito-like syntax to send a request and test the response. But this doesn’t feel like the right solution, because you always have to configure your request with real Java code within your test method. I would prefer a solution where I can simply configure the request using something like annotations and just execute the test after the request is sent.

Another thing that bugs me are asynchronous services. When it comes to handling asynchronous services you always have two options: callbacks or polling. How can I test those services? For polling it’s easier – you can loop the request code – but does this sound right to you? For callbacks you have to open a server, again within your test method or before. It seems there are no cool solutions for this right now – even rest-assured can’t handle these services very well. That’s why I took a little time and tried to solve these problems. The result is a small library called restfuse.

Restfuse is a JUnit extension. It introduces an annotation called @HttpTest which can be used to configure a request. The request is sent before the annotated method is executed as a test method. The response is then injected into the test object and can be used within the test method. It also provides some new asserts like assertNotFound or assertOk to test response codes. A simple @HttpTest looks like this:

@RunWith( HttpJUnitRunner.class )
public class RestfuseTest {
 
  @Rule
  public Destination destination = new Destination( "http://restfuse.com" ); 
 
  @Context
  private Response response; // will be injected after every request
 
  @HttpTest( method = Method.GET, path = "/" )
  public void checkRestfuseOnlineStatus() {
    assertOk( response );
  }  
}

And of course, it also solves the problem with asynchronous services by introducing two annotations called @Callback and @Poll which can be used together with the @HttpTest annotation. For more information on these tests for asynchronous services take a look at the restfuse site.

Restfuse is open source, licensed under the EPL v – 1.0 and is hosted at github. The 1.0 version is also in the Maven Central and online as a p2 repository (yes, it’s an OSGi bundle).  I hope this small library will help you as much as it helped me. I would appreciate feedback on how to make restfuse even better.

followme Introducing restfuse   a JUnit Extension to test REST APIs

on Oct 17th, 2011Effective Mockito Part 4

This Effective Mockito Post will be IDE specific again but related to the last post on Mockito’s spies. If you’ve read Part 3 you should now be familiar how to use them to “pseudo mock” statics. When writing code it often comes to a point where we want to debug using single step debugging. When using Mockito and especially when spies come into the game there is still something pretty annoying.

That is, when we want to debug our Object-Under-Test’s real method and the object is a spy. When we try to step into the object’s method we always land in internal Mockito code. After a little reading we can drill deeper but the next landing place is in java.lang.reflect code and so on. To be honest, this is really not the nicest way to debug code. What I want is that regardless of whether I use spies or not, when I step into an object’s method I land directly in this method. In the past my workaround was to set a breakpoint in the test at the method call and in the method itself. This enabled me to stop at the first point and resume the execution until it stops the second time in the method. But there is a much more elegant way. Let’s see how we can do this.

First of all, let’s take a look at an example. The code below shows a simple test from the last Effective Mockito post. The test uses a spy to “pseudo mock” a static method. We set a breakpoint in the line of the isPropertySet call and debug this method. Sadly when doing this we run into the effect described above.

@RunWith( MockitoJUnitRunner.class )
public class MyObjectText {
 
  @Spy
  private MyObject objectUnderTest;
 
  @Test
  public void testIsPropertySet() {
    doReturn( "some runtime property" ).when( objectUnderTest ).getProperty();
 
    boolean isPropertySet = objectUnderTest.isPropertySet();
 
    assertFalse( isPropertySet );
  }
 
}

When using Eclipse there is a very simple way to avoid this called “Step Filtering”. We can add packages or classes to this Filterlist using the preferences. When filters are activated the classes will automatically be skipped during debugging. By setting a filter like the one in the screenshot below we can simply step over the Mockito and reflection code.

stepfilters Effective Mockito Part 4

If you are not using Eclipse there is probably a similar way to achieve this with your IDE. It would be cool if you would share this tip with us in a comment. Meantime, I hope that Step Filtering is as helpful to you as it is for me.  Finally, I want to thank Fluffi and Frank for getting me to dive into this.

followme Effective Mockito Part 4

Read the other Effective Mockito posts:

on Oct 13th, 2011Effective Mockito Part 3

In the previous Effective Mockito post we saw how to use the @Mock Annotation to get a clean test. In this post I want to show you how to use Mockito’s spy mechanism to eliminate testing troubles with third party libraries.

Testing is one of the most important things in software development. I assume you agree with me because you decided to read this blog post icon wink Effective Mockito Part 3 .  It goes without saying that when we develop software we often rely on third party functionality. This does not affect our testing because we can mock objects from third party libraries thanks to Mockito. But there is one thing that always ruins my karma…

That is, static methods. And even worse, static methods that depend on runtime state. I know there are solutions like PowerMock to enable mocking statics, but I think there is a more elegant solution to avoid the troubles with statics -  without manipulating the bytecode and without adding another mocking library, as we would with PowerMock.

Let’s dive into an example to see how. First, take a look at our third party code. In this example I know that I will have to use a static method from the framework which exists in the class FancyFrameworkUtil. The only purpose of this code is to show you that I have to use it and that the third party library changes its return type magically at runtime as the comment says (this sort of thing happens way too often).

public class FancyFrameworkUtil {
 
  public static String getProperty() {
    return "some runtime property"; // this property changes at runtime ;)
  }
 
}

Let’s get to the code we want to write: a highly sophisticated type called MyObject icon wink Effective Mockito Part 3 . This type has only one method called isPropertySet which will become API (by this I mean the method will be added to a public interface). The method only checks to see if the value of the third party’s framework has a specific value and returns a boolean depending on the value.

public class MyObject {
 
  public boolean isPropertySet() {
    String property = FancyFrameworkUtil.getProperty();
    boolean result = true;
    if( property.equals( "some runtime property" ) ) {
      result = false;
    }
    return result;
  }
 
}

We now know that the framework method returns a value that can change at runtime but this does not mean we can’t write a test.

public class MyObjectTest {
 
  private MyObject objectUnderTest;
 
  @Before
  public void setUp() {
    objectUnderTest = new MyObject();
  }
 
  @Test
  public void testIsPropertySet() {
    assertFalse( objectUnderTest.isPropertySet() );
  }
 
}

As you can see it’s a very straightforward test. But it’s not complete because we haven’t tested what happens when the framework’s property value changes. We can’t be sure if our MyObject#isPropertySet ever returns true. I’m sure you’ve had a similar problem in the past, too.

At this point we have a choice. Introduce another framework to mock the static framework method or do something like the following. First, we need to extract the call to the third party library in a separate method in our MyObject implementation. It’s important that we change the visibility of this method to package private. This is the price we have to pay. But I don’t think its a high price because this method will not become API and is only visible in the implementation’s package. By separating the interface and the implementation into different packages this really isn’t a problem.

public class MyObject {
 
  public boolean isPropertySet() {
    String property = getProperty();
    boolean result = true;
    if( property.equals( "some runtime property" ) ) {
      result = false;
    }
    return result;
  }
 
  String getProperty() {
    return FancyFrameworkUtil.getProperty();
  }
 
}

This is all we have to do to our implementation to enable the “pseudo mocking” of the FancyFrameworkUtil‘s method. Now comes the testing, and at this point we can use a spy. A spy is a real object with one or many mocked methods. Therefore we can spy on our objectUnderTest. In our case we want to mock the getProperty method that was added last. It can look like this.

public class MyObjectTest {
 
  private MyObject objectUnderTest;
 
  @Before
  public void setUp() {
    objectUnderTest = spy( new MyObject() );
  }
 
  @Test
  public void testIsPropertySet() {
    doReturn( "some runtime property" ).when( objectUnderTest ).getProperty();
 
    assertFalse( objectUnderTest.isPropertySet() );
  }
 
  @Test
  public void testIsPropertySetWhenPropertyChanged() {
    doReturn( "foo" ).when( objectUnderTest ).getProperty();
 
    assertTrue( objectUnderTest.isPropertySet() );
  }
 
}

As you can see in the test methods, the spying in the setUp method enables us to change the return value of the framework’s method by introducing a delegation step. With this we can ensure that our method isPropertySet reacts to changes in the framework’s property.

I hope it’s now clear how to use a spy to mock static framework methods by using delegation steps. If you know alternative ways, please take a minute to share it with us in a comment. By the way, there is also an @Spy Annotation you can use. Have fun spying icon wink Effective Mockito Part 3

followme Effective Mockito Part 3

Read the other Effective Mockito posts:

 

© EclipseSource 2008 - 2011