Mostrando entradas con la etiqueta spring framework. Mostrar todas las entradas
Mostrando entradas con la etiqueta spring framework. Mostrar todas las entradas

miércoles, enero 02, 2013

Testing Spring Data MongoDB Applications with NoSQLUnit

Spring Data MongoDB


Spring Data MongoDB is the project within Spring Data project which provides an extension to the Spring programming model for writing applications that uses MongoDB as database.

To write tests using NoSQLUnit for Spring Data MongoDB applications, you do need nothing special apart from considering that Spring Data MongoDB uses a special property called _class for storing type information alongside the document.

_class property stores the fully qualified classname inside the document for the top-level document as well as for every value if it is a complex type.

Note Type mapping
MappingMongoConverter is used as default type mapping implementation but you can customize even more using @TypeAlias or implementing TypeInformationMapper interface.

Application


Starfleet has asked us to develop an application for storing all logs of starship crew members into their systems.

To implement this requirement we are going to use MongoDB database as backend system and Spring Data MongoDB at persistence layer.

Log documents have next json format:

Example of Log Document

{
        "_class" : "com.lordofthejars.nosqlunit.springdata.mongodb.log.Log" ,
        "_id" : 1 ,
        "owner" : "Captain" ,
        "stardate" : {
                "century" : 4 ,
                "season" : 3 ,
                "sequence" : 125 ,
                "day" : 8
        } ,
        "messages" : [
                        "We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research. Our eminent guest, Dr. Paul Stubbs, will attempt to study the decay of neutronium expelled at relativistic speeds from a massive stellar explosion which will occur here in a matter of hours." ,
                        "Our computer core has clearly been tampered with and yet there is no sign of a breach of security on board. We have engines back and will attempt to complete our mission. But without a reliable computer, Dr. Stubbs' experiment is in serious jeopardy."
        ]
}

This document is modelized into two Java classes, one for whole document and another one for stardate part.

Stardate class

@Document
public class Stardate {

        private int century;
        private int season;
        private int sequence;
        private int day;

        public static final Stardate createStardate(int century, int season, int sequence, int day) {

                Stardate stardate = new Stardate();

                stardate.setCentury(century);
                stardate.setSeason(season);
                stardate.setSequence(sequence);
                stardate.setDay(day);

                return stardate;

        }

        //Getters and Setters
}
Log class

@Document
public class Log {

        @Id
        private int logId;

        private String owner;
        private Stardate stardate;

        private List<String> messages = new ArrayList<String>();

        //Getters and Setters
}

Apart from model classes, we also need a DAO class for implementing CRUD operations, and spring application context file.

MongoLogManager class

@Repository
public class MongoLogManager implements LogManager {

        private MongoTemplate mongoTemplate;

        public void create(Log log) {
                this.mongoTemplate.insert(log);
        }

        public List<Log> findAll() {
                return this.mongoTemplate.findAll(Log.class);
        }

        @Autowired
        public void setMongoTemplate(MongoTemplate mongoTemplate) {
                this.mongoTemplate = mongoTemplate;
        }

}
application-context file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">

     <context:component-scan base-package="com.lordofthejars.nosqlunit.springdata.mongodb"/>
     <context:annotation-config/>

</beans>
Tip
For this example we have used MongoTemplate class for accessing to MongoDB to not create an overcomplicated example, but in a bigger project I recommend use Spring Data Repository approach by implementing CrudRepository interface on manager classes.

Testing


As has been told previously, you don’t have to do anything special beyond using class property correctly. Let’s see the dataset used to test the findAll method by seeding _log
collection of logs database.

all-logs file

{
        "log":[
                {
                        "_class" : "com.lordofthejars.nosqlunit.springdata.mongodb.log.Log" ,
                        "_id" : 1 ,
                        "owner" : "Captain" ,
                        "stardate" : {
                                "century" : 4 ,
                                "season" : 3 ,
                                "sequence" : 125 ,
                                "day" : 8
                        } ,
                        "messages" : [
                                "We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research. Our eminent guest, Dr. Paul Stubbs, will attempt to study the decay of neutronium expelled at relativistic speeds from a massive stellar explosion which will occur here in a matter of hours." ,
                                "Our computer core has clearly been tampered with and yet there is no sign of a breach of security on board. We have engines back and will attempt to complete our mission. But without a reliable computer, Dr. Stubbs' experiment is in serious jeopardy."
                        ]
                }
                ,
                {
                        "_class" : "com.lordofthejars.nosqlunit.springdata.mongodb.log.Log" ,
                        "_id" : 2 ,
                        "owner" : "Captain" ,
                        "stardate" : {
                                "century" : 4 ,
                                "season" : 3 ,
                                "sequence" : 152 ,
                                "day" : 4
                        } ,
                        "messages" : [
                                "We are cautiously entering the Delta Rana star system three days after receiving a distress call from the Federation colony on its fourth planet. The garbled transmission reported the colony under attack from an unidentified spacecraft. Our mission is one of rescue and, if necessary, confrontation with a hostile force."
                        ]
                }
                ...
}

See that _class property is set to full qualified name of Log class.
Next step is configuring MongoTemplate for test execution.

LocalhostMongoAppConfig

@Configuration
@Profile("test")
public class LocalhostMongoAppConfig {

        private static final String DATABASE_NAME = "logs";

        public @Bean Mongo mongo() throws UnknownHostException, MongoException {
                Mongo mongo = new Mongo("localhost");
                return mongo;
        }

        public @Bean MongoTemplate mongoTemplate() throws UnknownHostException, MongoException {
                MongoTemplate mongoTemplate = new MongoTemplate(mongo(), DATABASE_NAME);
                return mongoTemplate;
        }

}

Notice that this MongoTemplate object will be instantiated only when test profile is active.
And now we can write the JUnit test case:

WhenAlmiralWantsToReadLogs

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:com/lordofthejars/nosqlunit/springdata/mongodb/log/application-context-test.xml")
@ActiveProfiles("test")
@UsingDataSet(locations = "all-logs.json", loadStrategy = LoadStrategyEnum.CLEAN_INSERT)
public class WhenAlmiralWantsToReadLogs {

        @ClassRule
        public static ManagedMongoDb managedMongoDb = newManagedMongoDbRule()
                        .mongodPath(
                                        "/Users/alexsotobueno/Applications/mongodb-osx-x86_64-2.0.5")
                        .build();

        @Rule
        public MongoDbRule mongoDbRule = newMongoDbRule().defaultManagedMongoDb("logs");

        @Autowired
        private LogManager logManager;

        @Test
        public void all_entries_should_be_loaded() {

                List<Log> allLogs = logManager.findAll();
                assertThat(allLogs, hasSize(3));

        }

}

There are some important points in the previous class to take a look:
  1. Because NoSQLUnit uses JUnit Rules you can use @RunWith(SpringJUnit4ClassRunner) freely.
  2. Using @ActiveProfiles we are loading the test configuration instead of the production ones.
  3. You can use Spring annotations like @Autowired without any problem.

Conclusions


There is not much difference between writing tests for none Spring Data MongoDB and applications that use it. Only keep in mind to define correctly the _class property.

We keep learning,
Alex.
Els astronautes volen baix, Els núvols passen com qui no diu res. Amb les butxaques a les mans, Caminarem els passos d’altres peus. (Pa amb Oli i Sal - Blaumut)
Music: http://www.youtube.com/watch?v=Hkc5piclElg

viernes, noviembre 18, 2011

What a wicked game you play, To make me feel this way, What a wicked thing to do, To let me dream of you ( Wicked Game - Chris Isaak)



In my previous post I was talking about how to create a service using Jdk service provider. In current post I am going to talk about how to implement your own Jsr223 Script Engine. And as you will see, script engines are a kind of Jdk service providers, so instead of creating your own set of interfaces, we are going to see how to implement a service provider of an already defined service. 

Moreover we are going to see how we can convert a scripting language expression evaluator (in this case Spring EL) to be Jsr-223 compliant.

First of all for those who do not know what is Jsr-223 specification (or Java Scripting API), Jsr-223 is a scripting language independent framework for using script engines from Java code. Thanks of Jsr-223, we only use javax.script package instead of importing language specific classes.

For example using Spring EL scripting language, requires you import in your business class at least two Spring classes ExpressionParser and SpelExpressionParser, and if you want to use another scripting language, more specific vendor classes should be added, so your code is tied to script parser used.

If you use Java Scripting API, two classes are required, ScriptEngineFactory and ScriptEngine, regardless of the language used. And this occurs because ScriptEngine is an interface returned by ScriptEngineFactory service.

Let's start coding:

First class to implement is ScriptEngineFactory and is responsible of creating a new ScriptEngine. It must implement ScriptEngineFactory interface and its implementation will be the service provider of Scripting API.



First part of class is where we are defining what is the name of script language used to get the engine, the version of language (I have chosen Spring version), and version of engine.

Then three special methods:

  • getMethodCallSyntax: returns a String which can be used to invoke a method of a Java object using the syntax of the supported scripting language. In case spEL, the equivalent of calling a Java method from script, is using Types with special T operator.
  • getOutputStream: returns a String that can be used as a statement to display the specified String using the syntax of the supported scripting language. In case of spEL, there is no output stream so an unsupported exception is thrown.
  • getProgram: returns a valid scripting language executable progam with given statements. As previous method, an unsupported exception is thrown.

and finally the most important method getScriptEngine, which must return an implementation of ScriptEngine interface. In this case the Spring EL script engine. Let's see how spEL ScriptEngine is implemented.


First of all class extends from AbstractScriptEngine, which provides implementation for several of the variants of the eval method. Compilable interface is implemented too. ScriptEngines that implements this interface can compile scripts so any further execution of expression does not require any recompilation.

Most important method is eval which should cause immediate script execution using vendor library.

Main purpose of this class is adapt Jsr-223 classes to Spring EL classes. If you look carefully this class, it contains a private inner class that extends CompiledScript. This class is responsible of storing compiled expression, so subsequent calls of eval method requires no reparsing. This class is returned when compile method is called.

As final note spEL language contains some features that go beyond a standard script like registering Java functions into script, referencing Spring Beans, expression templating or navigation through properties of root objects. Of all of these features I think it would be useful having root objects support in Jsr-223 implementation, so I have coded a special attribute named "root". So if you set an attribute to script context with name "root",  attribute's content will be treated as root object.

Before implementing this solution I wondered another possibilities like not implementing root objects, or using Adapter pattern implementing two interfaces ScriptContext and EvaluationContext, but I dismissed because there were duplicated methods (different signature, same behaviour), and from developer's point of view  could be a bit confusing. Moreover this approach implies that caller should know that are running spEL script. Also I planned of using MethodResolver or PropertyResolver but was rejected because spEL would have been extended.

With attribute approach, if you are not using root objects, there are no differences between using Scripting API with Javascript, Groovy or spEL.

And finally service configuration. Create META-INF/services directory into resources folder, and create javax.script.ScriptEngineFactory file; this is the full qualified name of service interface with next content:

And that's all about implementation, with next unit tests you will see clearly how is used:

First one is testing that SpelScriptEngine is returned by ScriptEngineManager.

Not complicated, it is used as you would use for retrieving Javascript engine. Short name is used as engine identifier.

And next unit test contains some assertions about how some Spring EL features are used with ScriptEngine rather than SpelExpressionParser.

Notice how in first test, SpelScriptEngineImpl.ROOT_OBJECT constant is used, so Inventor instance is specified as root object.

Hope you found this post useful.

Feel free to use this code, I have created a git repository so you can download, branch, ... https://github.com/maggandalf/spEL223

Also I have uploaded project as zip file. Download Code.

Music: http://www.youtube.com/watch?v=UAOxCqSxRD0

lunes, octubre 17, 2011

Una terra promessa Un mondo diverso Dove crescere i nostri pensieri Noi non ci fermeremo Non ci stancheremo di cercare Il nostro camino (Terra Promessa - Eros Ramazzotti)


INTRODUCTION

The essence of the Observer Pattern is to "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." GoF. Observer pattern is a subset of publish/subscribe pattern which allows a number of observer objects to see an event. 

This pattern can be used in different situations, but in summary we can say that Observer pattern can be applied when an object should be able to notify messages to other objects, and you don't want these objects  being tightly coupled. In my case I have used this pattern when an asynchronous event should be notified to one or more graphical component.

This pattern can be implemented using an adhoc solution or using java.util.Observer/Observable classes. But my projects are always developed with Spring whether they are web or desktop applications. So in current post I will explain how I implement Observer pattern with Spring.

HANDS ON

Event handling in Spring ApplicationContext is provided through ApplicationEvent class and ApplicationListener interface. If a bean that implements ApplicationListener interface is deployed into the context, every time an ApplicationEvent is published to container, ApplicationListener receives it.

Spring comes with built-in events, like ContextStartedEvent, ContextStoppedEvent, but you can also create your own custom events.

For developing your own events, three classes are required, observer role, observable role and the event. Observers are those who receive events and must implement ApplicationListener class. Observable classes are responsible of publishing events and must implement ApplicationEventPublisherAware. Finally event class has to extend ApplicationEvent.

CODING

What I am going to implement is wikipedia example of Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern#Example) but using Spring Events instead of Observer/Observable Java classes. The example is a basic publish/subscribe example where one String message is sent from one module to another one.

Let's create MessageEvent. This event contains a String that represents the message we want to send. It is a simple class that extends from ApplicationEvent.


Next class is the Observable class. This class must implements ApplicationEventPublisherAware. This interface defines a setter method with ApplicationEventPublisher as parameter. This parameter is used for publishing events.

In current implementation see that also implements Runnable interface so user can create from console input, asynchronous messages. Most important line is 26 where an event is created and published.


The Observer class is even simpler. Implements ApplicationListener interface. Method onApplicationEvent is called when an event is published. See that it is a generic interface, so no cast is required. This differs from java.util.Observer class.


In application context file, you register both ApplicationListener and ApplicationEventPublisherAware beans.

And finally a main class to test the system. A thread is created to execute multiple asynchronous events. 


So start the program and write something to console. You will see something like:

hello
Thread-0
Thread-0
MessageEvent [message=hello]

I have entered "hello" message and thread name of event publisher is printed. Then event is sent and handler thread name is printed too. Finally the received event is shown. There is one thing that should call your attention. Both sender (Observable) and receiver (Observer) are executed in same thread; by default event listeners receive events synchronously. This means that publishEvent() method, blocks until all listeners have finished processing the event. This approach has many advantages (for example reusing transaction contexts, ...), but in some cases you will prefer that each event is executed in new thread, Spring also supports this strategy.

In Spring, class responsible of managing events is SimpleApplicationEventMulticaster. This class multicasts all events to all registered listeners, leaving it up to the listeners to ignore events that they are not interested in. Default behaviour is that all listeners are invoked in calling thread. 

Now I am going to explain how Spring Event Architecture is initialized and how you can modify. By default when ApplicationContext is started up, it calls initApplicationEventMulticaster method. This method verify if exists a bean with id applicationEventMulticaster of type ApplicationEventMulticaster. If it is the case defined ApplicationEventMulticaster is used, if not a new SimpleApplicationEventMulticaster with default configuration is created.

SimpleApplicationEventMulticaster has a setTaskExecutor which can be used for specifying which java.util.concurrent.Executor will execute events. So if you want that each event is executed in a different thread, a good approach would be using a ThreadPoolExecutor. As explained in last paragraph, now we must explicitly define SimpleApplicationEventMulticaster instead of using default ones. Let's implement:


First of all SimpleApplicationEventMulticaster must be defined as a bean with id applicationEventMulticaster. Then task pool is set, and we rerun our main class. And output will be:

hello
Thread-1
pool-1
MessageEvent [message=hello]

Note that now sender and receiver thread is different.

And of course you can create your own ApplicationEventMulticaster for more complex operations. You just have to implement ApplicationEventMulticaster and defining it with applicationEventMulticaster bean name, and events will be executed depending on your own strategy.

Hope that now your Spring desktop applications can take full advantage of Spring events for separating modules.


Music: http://www.youtube.com/watch?v=GfnkcKiocRw

miércoles, septiembre 28, 2011

Ratti Ratti Sachi Maine Jaan Gavayi Hai, Nach Nach Koylo Pe Raat Bitayi Hai, Akhiyon Ki Neend Maine Phoonko Se Uda Di (Jai Ho - A.R. Rahman)




Last week Spring Integration 2.1 M1 was released. One of new features is an implementation of MessageStorage interface that relies upon MongoDB for persistence.  

In current post I will show you an example of Spring Integration using Claim Check pattern and MongoDB as storage system.

First of all a small introduction of each component we will use.

Spring Integration provides an extension of the Spring programming model to support the well-known Enterprise Integration Patterns. It enables lightweight messaging within Spring-based applications and supports integration with external systems via declarative adapters.

MongoDB is a high-performance, schema-free, document-oriented database, which stores JSON-like documents.

Claim Check pattern is an EIP pattern which allows you to replace message content with a claim check (a unique key), which can be used to retrieve the message content at later time. This pattern can be used when message content is very large and should be sent by request or when you cannot trust the information with an outside party and you use a claim check to talk with it.

As an example I have used a simplified version of Cafe Sample Application that are shipped with Spring Integration bundle, but adding MongoDB MessageStore.


In this diagram you can see a schema of sample application. First of all cafe component is the gateway, the point of entree to the system, and is connected to orders channel. Orders are sent to splitter, and each order is sent through pack channel. Last step is check-in component. This component is responsible to store order into MongoDB and generate an UUID. Finally UUID is sent to output (in this case console output).

Now I will show you the code of first part of application. I have assumed that you have already installed MongoDB on your system and is running.

Application context file contains Spring Integration beans that define structure defined above. See that the most important part is the definition of MongoDbFactory at line 18, and line 22 where we are defining database name (test database is created by MongoDB by default). The other part of file is self-explained. See that in line 37, claim check is defined and MongoDB message storage is referenced.

Next important piece of code is Cafe interface. This class acts as a facade for placing orders and not explained yet, for retrieving orders. Let's see this class:

Typical Spring Integration gateway class, where entering points are defined. For now line 7 is the most important because this method will be called for placing orders into orders channel.
And now you are ready to send orders using Cafe interface and receiving at console output not the order but an UUID.

This is a simple snippet that can be executed as unit test (in fact this is not a unit test I know, but for teaching purpose is enough). And if you execute it you will see two long numbers in console, something like:


Remember that number because is required in next step. Meanwhile orders are stored into database. If mongo console is opened, we can query test database and all orders stored will be returned.


Now that check-in has been implemented and tested, it is time to implement check-out method. In this example user (you) will enter UUID using console. Entered reference will be sent to input channel, order object with entered code will be retrieved from database, and sent it to stdout channel. Let's see the code:


Not much difference but instead of using claim-check-in we are using claim-check-out. In line 37 we are defining a gateway to enter UUID (recoverOrderAndSent method of Cafe interface). Introduced identification is sent to input channel and check-out is executed, consequently order with that identifier is sent to output channel (console output).

And our "test" now looks like:


Take a look, first of all two orders are sent to check-in component. Orders are saved to MongoDB and returned UUID are printed to console. Next step in that method is asking user to introduce one of previous UUID and order is checked-out. 

And the output:


Note how simply is to configure your application to use claim-check pattern with Spring Integration, only configuring XMLs, without writing one line of code.. This is a simple example, of course you can use all the power of Spring Integration (aggregators, splitters, adapters, ...) with claim-check.

I wish you have found that post useful.

Download code.

Music: http://www.youtube.com/watch?v=NtDzUwVWQL0

lunes, julio 04, 2011

Umetxoak Ikusirik Lorea Ezin Bizirik Arantzak Kendu Nahi Dizkio Bizi Berri Bat Eman (Loretxoa - Benito Lertxundi)



EJP (or Easy Java Persistence) is a powerful and easy to use relational database persistence API for Java. It has no need for mapping Annotations or XML configuration, and there is no need to extend any classes or implement any interfaces. In it is site we can find the following statement: "EJP is, by far, the easiest persistence API available for Java."

From my point of view EJP is a mixture of some features between myBatis and Spring Jdbc Template Row Mapper.

An example of EJP from its website:


and Customer and Support classes are simple POJOs without annotations or any special tag, and no configuration file.

What I am going to explain in this post is how integrate EJP with Spring.

First of all, we are going to create an interface which defines all permitted operations:


This is an example of common operations provided by EJP. Methods that should be clarified are:

  • newDatabase method is used for returning a Database object. This object is a facade that implements all operations supported by EJP. It is the main class of EJP project with permission of DatabaseManager class.
  • loadAssociations are responsible (as its name suggests) to load an object associations.
  • queryForObject methods execute a "query by example" queries.
  • queryForInt is a method used for queries that return numerical results like count(*), avg(...), ...
EjpJdbcTemplate is the implementation of previous interface, and makes use of JdbcTemplate class as core.

Getting a new Database:


Remember that Database object is the core of EJP, and is required to execute all EJP operations. This method creates one Database with given Connection. databaseName is not mandatory, but for no reason is a constructor attribute. A null can be passed without any problem. In this implementation database name is a class attribute.

Deleting:


No secret in deleting an object. Using ConnectionCallback, connection is provided, and Database object is created.

Loading Associations:


If you want to load explicitly all associations of an object, load associations method must be called. The only integration difficult is that database.loadAssociations returns void, and ConnectionCallback should always return a result. In this case void.TYPE is used.

Executing Queries:


In this case most important line is where Database executeQuery method is called. This method returns a class of type Result. This class is a wrapper of ResultSet class but also can deal directly with beans (implicit wrapping), instead of getting one-by-one each parameter. But for following JdbcTemplate strategy and use a row mapper, ResultSet is used for mapping results.

Querying for Int:



See that follows the same schema as executeQuery, but instead of using RowMapperResultSetExtractor, a SingleColumnRowMapper is used. This mapper is used when the query result returns a single result.

Now I am going to show how to use this template into a DAO implementation.


Not much secret in this DAO. Only two methods requires special review findAllCustomersOrderedByName() and findCustomerByExample()

The first one:


this.template.queryForObject(Customer.class, "ORDER BY first_name",BeanPropertyRowMapper.newInstance(Customer.class)) 

 is converted by EJP to SELECT * FROM Customer ORDER BY first_name.

The second one:

this.template.queryForObject(customer, BeanPropertyRowMapper.newInstance(Customer.class)) 

instead of receiving a Class it receives an instance itself to execute the query. In case that first name field was set to alex, the equivalent SQL query would be SELECT * FROM Customer WHERE first_name='alex'


Now I have explained a strategy to integrate EJP with Spring. Because I have followed same structure as Spring-Data Jdbc-Extension project, rather than create a "HelloWorld" project, I decided to fork Spring-Data project into my Github account, and uploaded the code as a new extension for the project. Moreover a Jira issued has been created with id DATAJDBC-11. If you want to watch full code and unit tests go to git@github.com:maggandalf/spring-data-jdbc-ext.git and review spring-data-jdbc-ext/spring-data-jdbc-core/src/main/java/org/springframework/data/jdbc/ejp directory.

I wish you have found this post useful.


Music: http://www.youtube.com/watch?v=PlEknDUSRc0&feature=fvwrel

miércoles, abril 20, 2011

Are You Locked Up In A World That's Been Planned Out For You? Are You Feeling Like A Social Tool Without A Use? (She - Green Day)



From JBehave site: JBehave is a framework for Behaviour-Driven Development (BDD). JBehave allows developers, QA and non-technical or business participants, to write stories in a plain text file with minimal restrictions about grammar. Then a POJO is created for executing created story. This POJO should have the typical BDD structure Given, When and Then.

From Springsource site: Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application.

From Selenium site: Selenium is a suite of tools to automate web app testing across many platforms.


We have three technologies JBehave for acceptance tests, Selenium for web application testing and Spring dealing with infrastructure. In this post I will talk about integrating JBehave with Selenium 2 and Spring.

For this example I have created a very simple web application using Spring MVC. I know that business logic is not accurate to the reality, but it is simple enough to illustrate how to integrate all these technologies together.


I have divided this post in three main subsections:

  • Integrating JBehave with Spring. There is no web application here, only business logic.
  • Integrating Spring MVC with Selenium 2. Only to show how easy is implementing automated tests with Selenium 2.
  • Integrating JBehave with Selenium 2. Web application used in previous example but instead of using only Selenium for automating testing, JBehave instructs to Selenium which steps should execute.
Application that I will use is a simple TraderService, (explained in JBehave page (http://jbehave.org/reference/stable/)). This TraderService generates Stocks, and if a Stock is traded below threshold, its alert status is OFF and if it is traded above, alert status is ON.

In this tutorial I assume that you have a basic idea of JBehave and Spring.


  • Integrating JBehave with Spring:

In this case no web GUI is used, we are going to use JBehave for writing acceptance tests of business logic.

Basic classes are:
  • TradingService, that defines a method for creating stocks. TradingServiceImpl is the implementation.
  • Stock, that contains stock information and logic about its status.
  • StockAlertStatus is Stock status Enum.

Acceptance test part:

First of all we should create a story. A story is where stakeholders, developers... should say what they want the application do, and which are the expected results for given parameters. In our case a story has been created for validating that alarm is OFF if trade value is under threshold, and ON otherwise.


The important parts of that file are: Scenario for describing what we are testing, all symbols between <> that are used as variables, and Examples that are values injected to previous "<>" variables. In this story file two examples are provided, so two executions will be produced, one for each row. As final note, Given, When, Then words should be placed at start and are reserved words, also more than one Given, When or Then could be used in each story.

Next step, create a class that transforms a story written in "natural language" to code. We could say that this class is equivalent of creating a junit class; In JBehave these classes are called Steps. Because we are integrating with Spring an annotation called Steps is created. This annotation extends from Component annotation so Spring component-scan can wire up step classes too.


And Steps annotation is used in TradingServiceSteps class.


In TradingServiceSteps is where all magic occurs. This class is responsible of transforming story file to an execution. Let's see:

@Steps because we want Spring creates automatically this bean. TradingService is the business logic we want to test, and is injected using Autowire annotation. And finally one method for each Given, When, Then. Explained quickly, when JBehave finds an @Given, it searches into loaded stories for a phrase starting with Given. After that checks if @Given string value matches the Given definition expressed in story file. If matches then inject the story parameters as method parameters, for example STK1 as string parameter, or 5 as double threshold parameter. Moreover, in this case because we are using Examples in our story file, @Named annotation for each parameter is required. The named parameters allow the parameters to be injected using the table row values with the corresponding header name. Each parameter is converted from String to required parameter type.

We have written stories, and how to execute them (TradingServiceSteps class). JBehave requires another class, that will be responsible of configurating it. Basically you should configure Step classes and story files location, and what kind of reports are generated.

In our case, because we are integrating JBehave with Spring, some information is provided using Spring Injection.


This class is where JBehave is configured and is responsible for running all stories. Let's examine the most important lines:

In line 1 we specify a JUnit runner for running JBehave stories with Spring.
In line 2 we are configuring JBehave with Enum parameter converter, see that StockAlertStatus is an enum, because it is not a primitive parameter, a converter should be provided. JBehave comes with some convertes, but we can implement ours too.
In line 3 the embedder that we will use. This is the standard embedder for JBehave. Embedder represents an entry point to all of JBehave's functionality that is embeddable into other launchers.
And finally with @UsingSpring we are providing two Spring files, one where step classes are defined, and the other one where JBehave is configured.

Configuration file is a standard Spring file injecting required JBehave parameters:


This is a generic configuration file, that I use in all projects. You configure the output, the classloader for Embedder and prefix for parameters

And finally a Spring context file where all step classes are defined. And you know what, thanks of Spring this is as simple as:



No magic, remember that each Step class has an @Steps annotation? Thanks of component-scan, you don't have to define each Step class in @UsingSteps annotation or using tags.

Now run previous class as JUnit, and reports with results are generated.


  • Integrating Spring MVC with Selenium 2

Selenium 2 is a suite of tools to automate web app testing across many platforms. In this case WebDriver approach has been used. WebDriver is an interface for automating tests in a programmatic way. Selenium provides several implementations depending on browser where tests are run.

For this example I have created an Spring MVC application, that are composed of two pages, one form where all stock information is provided and a page where status of inserted stock is showed. Of course Spring MVC controller for managing all information is also implemented.

Controller of this small application is:


showForm method is used for showing the form where user will write stock information. submitForm method is called when submit button is pushed, and creates an stock and send to showstatus page the status of stock.

StockForm is simply a class with three attributes (stock, threshold and tradeAt price). No secret here.

Form page is also so simply but I will show it because form information will be used for configuring Selenium:



Page for showing status:


WebDriver is used in JUnit test for automatizing a sequence of events. In this case, the sequence will create an stock below threshold and assert that response page shows that alert status is OFF.



Most important sections of previous JSP are:

JSP taglibs <form:input path=""/> like <form:input path="name"/> in form, and <div id="result">. These fields are important because they are used by Selenium for filling form and asserting showed status.

For example, in Selenium class:

WebElement name = driver.findElement(id("name")) returns a "reference" to <input id="name" type="text"> element and using sendKeys method, you are sending keyboard chars to that component.

WebElement element = driver.findElement(id("result")), returns a "reference" to div element and using
assertThat(element.getText(), is(StockAlertStatus.OFF.name())); getText method, none tag characters of element are returned.

Now running this test is as simple as running TraderIsAlertedSelenium class as a simple JUnit test class. When running this class a browser (Firefox in this case) will be opened, and all programmed interactions will be executed on your screen.

At this point we just have to join both previous parts, and integration between JBehave with Spring and Selenium will be reality.


  • Integrating JBehave with Selenium 2 and Spring

JBehave has a module called JBehave-Web, that is used for integrating JBehave with web pages. Base classes are WebDriverProvider and WebDriverPage. Both classes are used by JBehave for abstracting from browser, and also for providing common methods to test webpages. In this example I won't use jbehave-web for two reasons, first because Selenium 2 with WebDriver offers a level of abstraction that is enough for this example, and secondly because WebDriverPage is a class that implements some common funcionalities for testing, but it is abstract, I don't like using extension only for sharing common operations between classes, it is a bad practice (not discussed here), I prefer aggregation. So in this case I have preferred  implementing my class for implementing common functionalities.


In this case abstraction from browser is acquired using WebDriver (Selenium) interface. Moreover all common operations are implemented into this class. The idea of this class is to be used in several projects and for that reason a better design should be desired, but for current example is enough.

Next group of classes are those that use PageUtils object. I have created one class for each page that Selenium should interact with. Acts as a facade to web.

For example class for dealing with page containing form to insert new stock is:


Three operations can be executed in this page, the first one is open the page. Because "insert a new stock" is accessed manually (in this case is the front page), an open method is provided with URL. Also a method for filling stock form and and another for submitting it are provided.

And finally a class that transforms an story written in "natural language" to code (also known as Steps class), this class would be the same used in first example (TradingServiceSteps) but adapted for dealing with web pages (using previous classes).


See that there is no differences between this class and the one created in first example, but using web page interfaces instead of business objects. 

Next modified files are:

Story file:


that has been modified to use web terminology.

Spring file:


that injects into TradingServiceWebSteps required beans.

Configuration file used in first example is the same, and Spring file for configuring JBehave is the same too.

In summary I can definitely say that integrating JBehave with Selenium 2 and Spring is not a difficult task, compared with the benefits that lead us having an automated acceptance test platform. I wish you have found this post useful.

Download Full Code

sábado, febrero 19, 2011

Basta Imaginar e Ele Está Partindo, Sereno e Lindo E Se a Gente Quiser....... Ele Vai Pousar.



This week Springsource people have uploaded the first milestone of Spring Framework 3.1.

For my diary work, Environment Abstraction is the best feature developed in current milestone.

Environment Abstraction allows us grouping bean definitions for activation in specific environments. For example you can define two data sources, where one will be used in testing (HSQL configuration) and the other one in production (PostgreSQL). I am sure that in your life using Spring, you have had uploaded by mistake the test database configuration into production code. Environment Abstraction tries to avoid this situation.

Now I have showed you a typical example, but you can also create a custom resolution of place-holders, so for example in test mode you use a properties file with log level property configured to TRACE, and in production the properties file configured to INFO.

Another example that I find it interesting is in acceptance tests. One of my tasks is design and develop planners for robots. In Unit Testing we are mocking the hardware interface with the robot. But in acceptance tests, instead of mocking the hardware interface, we inject an emulator interface, so you can see how a fictional software robot is moving in your screen and validate that all movements are correct visually.

In previous Spring versions, what we have is three Spring XML files, one for production, another one for acceptance tests, and one main file that imports one of both files, so depending on environment we import one file or another. As you can imagine this implies a manual process between production environment and testing environment; although is not tedious, can be omitted so having emulator hardware interface in production instead of driver interface to robot.

With Spring 3.1, only one file is required with both configurations, and depending on environment Spring loads the required beans.

An example of what I am explaining is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
     <beans profile="test, integration">
          <bean .../>
          <bean .../>
          <context:property-placeholder .../>
     </beans>
     <beans profile="production">
          <bean .../>
          <bean .../>
          <context:property-placeholder .../>
     </beans>
     <beans>
          <bean ..../>
     </beans>
</beans>

First thing you will notice is that beans tag is still the root but also is self-nested. The first two nested beans have an attribute called profile. This attribute inform when the beans it contains are active. First beans are active when configured profile is test or integration, while second ones when production profile is active. The last one definition is always activated.

Continuously we are writing something like "depending on environment", and I suppose you are wondering how you specify that environment.

You have an environment variable called spring.profiles.active where you specify which is the current profile. For setting this variable you can use an export in case of *nix systems, or as parameter execution -Dspring.profiles.active, or in context.xml in case of web applications, ...

For example a valid environment definition should be:

export spring.profiles.active=test

In case you are using Java-based Container Configuration, @Profile("profileName") can be used in beans definition, for specifying profile name.

ApplicationContext has getEnvironment() method for specifying which profiles are activated.

AnnotationConfigApplicationContext ctx = ...
ctx.getEnvironment().setActiveProfiles("dev");
ctx.register(...)
ctx.refresh();


I have developed a simple example that have two classes, where one prints passed message in upper case, and the other one prints the message between sharp character. Depending on profile configuration it changes message format. Moreover the same example is provided but using Java-based Container Configuration.

Download code from my GITHub if you want to see the source code.

I hope you find this new feature as useful as I find, and more important, once you have configured your machines with required environment variable, you won't worry any more about changing configuration files.