Quick Tip on Mockito — Mocking Iterator

Today I was writing unit test for a piece of code which required me to mock a iterator. My requirement was that I wanted to return true first time when hasNext() method and return false in the second iteration. It took me sometime to figure out how to write such a test case. My class for which I was writing test looks like as shown below.

import java.util.Iterator;

public class ResultFetcher {

	private ResultStore store;
	private ResultProcessor processor;

	public void fetchResults() {
		Iterator<String> iterator = store.resultIterator();
		while (iterator.hasNext()) {
			String result = iterator.next();
			processor.process(result);
		}
	}
}

The unit test code is shown below. The important line in the test is Mockito.when(iterator.hasNext()).thenReturn(true,false); which will return true first time and false second time.

import java.util.Iterator;

import org.junit.Test;
import org.mockito.Mockito;

public class ResultFetcherTest {

@Test
public void testFetchResults() {
ResultFetcher fetcher = new ResultFetcher();

ResultStore store = Mockito.mock(ResultStore.class);
ResultProcessor processor = Mockito.mock(ResultProcessor.class);
fetcher.store = store;
fetcher.processor = processor;

Iteratoriterator = Mockito.mock(Iterator.class);
Mockito.when(store.resultIterator()).thenReturn(iterator);
Mockito.when(iterator.hasNext()).thenReturn(true,false);
Mockito.when(iterator.next()).thenReturn("Hello");
fetcher.fetchResults();
Mockito.verify(processor).process("Hello");
}

}

Advertisements

Say Hello to Jelastic

These days Platform as a Service (PaaS) is one of my interest areas and I like to play with different PaaS providers to see how easy or difficult it is to develop and deploy application on them. The best thing about most of the current new generation PaaS systems is that they don’t require you to change your code or learn new programming paradigm. Google App Engine is thing of past and is losing ground in PaaS race. For last six months I have spend some of my spare time on OpenShift and Cloud Foundry and one thing I can say is that I love both of the platforms. Today I decided to spend some time on Jelastic — seeing how easy or difficult is to deploy a simple Spring MongoDB application on it. According to Jelastic website

Jelastic is the next generation of Java hosting platforms which can run and scale ANY Java application with no code changes required

Jelastic provides a web ui using which you can create the deployment environment and upload your war file to it.To check the usability of the UI I decided that I will not refer to Jelastic documentation and will try to deploy the application based on my understanding. So in this blog I am sharing the steps I performed to deploy a simple Spring MongoDB application to Jelastic.

  1. To start I created a very simple simple moviestore application using Spring Roo. For those of you who are not aware of Spring Roo can refer to my article series at IBM Developerworks on Spring Roo.Once you have installed Spring Roo, fire the Roo shell and execute following commands. This will create a Spring MVC web application with MongoDB as backend.
    project --topLevelPackage com.shekhar.moviestore --projectName moviestore
    mongo setup --databaseName moviestore
    entity mongo --class ~.domain.Movie
    field string --fieldName title --notNull
    field string --fieldName description --notNull
    repository mongo --interface ~.repository.MovieRepository
    service --interface ~.service.MovieService
    web mvc setup
    web mvc all --package ~.web
    q
    
  2. You can test the application locally by first starting the MongoDB server and then starting the application using mvn tomcat:run.
  3. But the point is to test the application on Jelastic. So go to http://jelastic.com/ and sign up for free. You don’t need to pay anything. I choose North America hosting provider.
  4. Once you have registered at Jelastic login with your credentials at https://app.jelastic.servint.net/
  5. After you have logged in to Jelastic portal you will see a Create environment link on the left. In Jelastic you have to first create environment under which your application will run. Click on the environment link and choose MongoDB, Tomcat, Java 6 as the environment topology. This is shown in image below. I really liked the UI. It is sexy.
  6. When you press create it will take couple of minutes to create the environment. So please be patient.
  7.  You will receive an email from Jelastic with the MongoDB connection details. It will give you a url to access MongoDB from web UI and an admin username and password.In my case I received url http://mongodb-moviestore.jelastic.servint.net/. I am not going to share username and password.
  8. The MongoDB UI is a RockMongo MongoDB web client. Login into it using admin username and password and Rock 🙂
  9. Next we need to create a MongoDB database and user with which our application can connect. To create database first click on databases and then “Create new Database”. Enter the name of database as moviestore and press create button. Next click on newly created moviestore database and click more then authentication and then click on add user to create a new user. Create a user with username as moviestore and password as password and press Add user.
  10. Now that we have created a user we should update the database.properties and applicationContext-mongo.xml files which were created by Spring Roo. By default they were pointing to localhost. Update the files as shown below.
    database.properties

    #Updated at Tue Feb 28 12:26:32 IST 2012
    #Tue Feb 28 12:26:32 IST 2012
    mongo.host=mongodb-moviestore.jelastic.servint.net
    mongo.name=moviestore
    mongo.password=password
    mongo.port=27017
    mongo.username=moviestore
    

    applicationContext-mongo.xml

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:cloud="http://schema.cloudfoundry.org/spring" xmlns:context="http://www.springframework.org/schema/context" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd        http://www.springframework.org/schema/data/mongo        http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd        http://schema.cloudfoundry.org/spring http://schema.cloudfoundry.org/spring/cloudfoundry-spring-0.8.xsd">
    
        <mongo:db-factory dbname="${mongo.name}" host="${mongo.host}" id="mongoDbFactory" password="${mongo.password}" port="${mongo.port}" username="${mongo.username}"/>
    
        <mongo:repositories base-package="com.shekhar.moviestore"/>
    
        <!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
        <context:annotation-config/>
    
        <bean class="org.springframework.data.mongodb.core.MongoTemplate" id="mongoTemplate">
            <constructor-arg ref="mongoDbFactory"/>
        </bean>
    
    </beans>
    
  11. Build the maven project by executing mvn clean install command.
  12. Then upload the war by clicking on upload link in the Jelastic web UI.This will take some time depending on your internet connection.
  13. After the war is uploaded you will see the war in deployment manager tab. Click deploy to moviestore environment to deploy to tomcat and select context as ROOT.
  14. Finally you will be able to view the application running at http://moviestore.jelastic.servint.net/

This was my first write up on Jelastic and I will continue experimenting with it and evaluating its capabilities. I will also spend time reading its documentation and see how it compare with other PaaS providers. Overall I was impressed with Jelastic and to me it looks like a good deployment option for Java applications.

Spring Roo PGP Exception

Today when I fired Spring Roo shell I started getting exception as shown below and I was not able to execute any command. I uninstalled Spring Roo (thinking that it might have got corrupted) but it didn’t helped after lot of firefighting I figured out the solution to overcome this problem. The problem was that yesterday I trusted some pgp keys and somehow Roo was not able to find them and started throwing exception. The solution is to remove a file name .spring_roo_pgp.bpg and restart Spring Roo. Spring Roo will create a new clean file. Continue reading “Spring Roo PGP Exception”