Sunday, December 08, 2013

Emerging languages series - Scala



Although my experience in Scala language is limited but in last couple of weeks have read a lot about Scala and its growth over recent years. Coming from Java background and recent demand for Scala has forced me to dig deeper to explore the potential and features of the language.

Scala overview  –
Scala is an acronym for “Scalable Language”. Scala is a statically typed, object oriented functional language, merging two popular programming approaches into one
In other words we can say when Object-Oriented meets Functional then the result is known as Scala. It was built by Martin Odersky at EPFL, launched in 2003.
Scala runs on the JVM. Java and Scala classes can be freely mixed, no matter whether they reside in different projects or in the same.
Java libraries, frameworks and tools are all available. Build tools like ant or maven, IDEs like Eclipse, IntelliJ, or Netbeans, frameworks like Spring or Hibernate all work seamlessly with Scala. Scala runs on all common JVMs and also on Android.
Already used by Twitter, LinkedIn, Yammer, Foursquare, eBay, Amazon , Guardian newspaper and many others

Key features of Scala language  – Scala has a set of features which differ from Java. Some of these are:
All types are objects
Type inference
Functions are objects
Anonymous function
Curried function
Closures
Traits
Domain specific language (DSL) support
Concurrency support inspired by Erlang

Scala comes with an interactive interpreter, the REPL (for Read, Evaluate, Print Loop). After installing Scala, you can start the REPL by entering the command scala in a command prompt or shell window. Visit the Scala download page here. 

You can type statements and expressions at the prompt, and the REPL will evaluate these and print the results. The REPL is a useful tool for experimenting with Scala language features. The REPL understands a number of special commands that start with a colon. Type the command :help to see an overview. Type :quit to exit the REPL.

Compiling and running Scala code –
Before getting into any example please remember you can Compile Scala source files using the Scala compiler, scalac. When you use Scala as a compiled language your code must be organized a little differently than when using it as a scripting language. You’ll need to create a Scala object with a main method, as in the following example.

// HelloWorld.scala
object HelloWorld {
def main(args: Array[String]) {
 println(“Hello World!”)
}
}

Save this in a source file named HelloWorld.scala. Compile it with: scalac HelloWorld.scala and run it with: scala HelloWorld. Note that in this last command, you supply the name of the object (HelloWorld) rather than the name of the source file (HelloWorld.scala) or the compiled class file (HelloWorld.class).


Scala features By Example

Values and variables -
val name: Type = expression    // use to define an immutable value
var name: Type = expression   // use to define a mutable variable

val myVal : Int = 1;
var name = "Sajid"

Tuples -
Tuples are type-safe containers for multiple values. They useful if you want to return more than one value from a method. They are different from collections;
each element in a tuple has its own type, whereas in collections all elements in the collection usually have the same type.

// Defines a tuple with a String and an Int
val tup = (“Hello”, 123)
// The elements of a tuple are named _1, _2 etc.
println(tup._1)
println(tup._2)

// Method that returns a Tuple with two Ints
def div(a: Int, b: Int): (Int, Int) = (a / b, a % b)

// Call the method, use pattern matching to extract the values from the result, throw away the second value
val (x, _) = div(20, 7)


Methods
def name[TypeParams](ParamList1)(ParamList2)(...): ReturnType = {
// Statements and expressions
}

// Here you see return type is inferred and “return” keyword is optional
def add(x:Int, y:Int) = {
  x + y
println(add(42,13))


Default parameters
Parameters may have a default value that is used if a value is not supplied when calling the method.
def greet(name: String = “there”) {
println(“Hello “ + name)
}

Return multiple variables - It is possible to return multiple variables using Tuple
def swap(x:String, y:String) = (y, x) 
val (a,b) = swap("hello","world") 
println(a, b)


Functions –
The difference between a function and a method is that a function is a value (an object) while a method is not. A function is an instance of one of the traits Function0, Function1 etc., depending on the number of parameters that the function takes.

def add(a:Int, b:Int):Int = a + b
val m:Int = add(1, 2)
println(m)

You can convert a method to a function by assigning it to a val or var. However, to avoid ambiguity, you have to either explicitly specify the type of the val or var, or put an underscore after the method name to indicate that you want to treat it as a function.
// A method
def succ1(x: Int) = x + 1
// Explicitly specify the type of succ2
val succ2: Int => Int = succ1
// Or put an underscore after the method name
val succ2 = succ1 _


Higher order functions –
def identity(x: Int) = x
def sqr(x: Int) = x * x
def cube(x: Int) = x * x * x

def sum(f: Int=>Int, a: Int, b: Int): Int =
if (a == b) f(a) else f(a) + sum(f, a + 1, b)

println(sum(identity, 1, 10))
println(sum(sqr, 1, 10))
println(sum(cube, 1, 10))

"sum" is now a "higher order" function, It's first parameter is a function which maps an Int to an Int

The type "Int" represents a simple Integer value. The type Int => Int represents a function which accepts an Int and returns an Int.


Anonymous functions –
A method that requires a function as a parameter  the function's type is (Int,Int) => Int

def sum(f: Int=>Int, a: Int, b: Int): Int =
if (a == b) f(a) else f(a) + sum(f, a + 1, b)
println(sum(x=>x, 1, 3))
println(sum(x=>x*x, 1, 3))
println(sum(x=>x*x*x, 1, 3))

We can create "anonymous" functions on the fly. x => x*x is a function which takes an "x" and returns x*x


Curried functions –
Currying allows to turn a function that expects two arguments into a function that expects only one, and that function returns a function that expects the second argument. Creating basically a chain of functions.

def addA(x: Int, y: Int): Int =
x + y
def addB(x: Int):Int=>Int =
y => x + y
val a = addA(10, 20)
val b = addB(10)(20)
println(a)
println(b)

You can take any function of multiple arguments and curry it.


Traits –
trait Name[TypeParams] extends ClassOrTrait with Trait1 with Trait2 with ... {
// Constructor statements and trait members
}

A trait can extend one class and multiple other traits. A trait can have a constructor (you can put statements in the body of the trait that are executed as part of its constructor), but it cannot have constructor parameters.

Traits are like Java interfaces, except that a trait can be partially implemented. Like a Java interface, a trait cannot be directly instantiated even if it is fully implemented.

trait Car {
  val brand: String
}

trait Shiny {
  val shineRefraction: Int
}

One class can extend several traits using the with keyword:
class BMW extends Car with Shiny {
  val brand = "BMW"
  val shineRefraction = 12
}


Closure –
A "closure" is a function which carries with it references to the environment in which it was defined.
Alternately we can say that closure is a function, whose return value depends on the value of one or more variables declared outside this function. Consider the following piece of code with anonymous function

object Test {
   def main(args: Array[String]) {
      println( "muliplier(1) value = " +  multiplier(1) )
      println( "muliplier(2) value = " +  multiplier(2) )
   }
   var factor = 3
   val multiplier = (i:Int) => i * factor
}

Here  factor has a reference to a variable outside the function but in the enclosing scope.


Functions are ObjectsYes you read it correct J
Probably it might be little difficult to digest it if you coming from Java background. Don’t worry, here comes a golden rule of thumb. The key to scala is that everything is an object. Since every value is an Object in Scala, Functions are Objects, too!

Every Function you’ll ever define in Scala, will become an instance of an Implementation which will feature a certain Function Trait. There is a whole bunch of that Function Traits, ranging from Function1 up to Function22. Wow, and why are there so many? Since Functions are Objects in Scala and Scala is a statically typed language, it has to provide an appropriate type for every Function which comes with a different number of arguments. If you define a Function with two arguments, the compiler picks Function2 as the underlying type. If you define a Function with seven arguments, you’ll end up with Function7. And since there is a maximum up to Function22, that means you can’t define a Function which will accept 23 arguments or more.

new Function1[Int, Int] {
 def apply(x: Int): Int =
 x + 1
}


Patten matching –
Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy.
Here is a small example which shows how to match against an integer value:

object MatchTest1 extends Application {
  def matchTest(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }
  println(matchTest(3))
}

The block with the case statements defines a function which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.

Here is a second example which matches a value against patterns of different types:
object MatchTest2 extends Application {
  def matchTest(x: Any): Any = x match {
    case 1 => "one"
    case "two" => 2
    case y: Int => "scala.Int"
  }
  println(matchTest("two"))
}

The first case matches if x refers to the integer value 1. The second case matches if x is equal to the string "two". The third case consists of a typed pattern; it matches against any integer and binds the selector value x to the variable y of type integer.


Finally some of the key benefits of Scala –
  • Scala's case classes and pattern-matching make for very clean code, for example, and Scala traits (like interfaces with implemented methods) can be a very powerful and simple way to "inherit" behaviour without the pain of OO inheritance.
  • Scala's powerful type inference also combines the benefits of a strictly typed language with some of the benefits of dynamic typing in terms of having to write less code yourself.
  • Maintainability e.g. Scala code is often much more concise than Java (with all that boilerplate) and fewer LOC often means fewer places to screw up and less maintenance in the longer term.
  • Access to great Scala libraries e.g. for Collections, as well as to Java's existing libraries.
  • Scalability e.g through the use of Actors for (asynchronous) concurrency instead of threads, or through greater use of immutable data, functional programming etc.
  • Scala's hybrid ability to take advantage of FP and/or OOP as required for the task in hand.
Most people are using Scala on the server, because that's where you can gain the benefit of its scalability. Obviously, you can mix Scala with Java on a JVM server, and use your preferred client-side technology for browser interfaces etc. Scala is also the basis for version 2 of the lightweight Play! framework for web applications (although my understanding is that version 2.x is not currently Java EE compatible). My impression is that there is a growing trend towards looking at using the right language for specific purposes rather than a monolithic "one size fits all" approach.
Twitter is a prominent user and promoter of Scala, while LinkedIn also uses Scala for some applications.

Resources
Download Typesafe Reactive Platform for Scala - http://typesafe.com/platform/getstarted
Scala IDE for Eclipse - http://scala-ide.org/

Java 8 vs Scala: A Feature Comparison

Here’s a nicely written article on InfoQ which goes deep into this comparison and list out some of the key findings. Just to mention Java 8 is going to provide a variety of new language features, with the potential to fundamentally change the way we write applications. Especially the functional programming constructs, such as lambda expressions, can be considered a paradigm shift. This shift provides great new possibilities for more concise, compact and easy to understand code.
If you want to try them out then explore early builds of Java 8 on most platforms.

The best way to find out what a language can do for you is probably to try it out, and best way would be to sign up and learn about Functional Programming Principles In Scala from the language's creator Martin Odersky of EPFL at Coursera. Just check and register for any future date for free course.

Sunday, November 24, 2013

Hybris commerce suite - Insight

Recently started exploring Hybris commerce suite 5.0.4 and have some of the interesting facts to share. So let’s start with basics.

What is [y] Hybris ?
Hybris is one of the upcoming agile and comprehensive commerce suite. Hybris platform is simple and based on open standards like Spring, ZK, SOLR/Lucene, ANT, Groovy, Apache Commons. The hybris commerce suite is engineered for expansion, extension and scale.

How’s the [y] Hybris architecture ?
From business standpoint the hybris Commerce Suite is divided into individual packages, such as Commerce, Content, Channel and Orders. These packages are bundles of functionality assembled for a certain range of business functionality.

From a technical point of view, packages consist of individual modules (aka extensions).
Extensions written by hybris provide standardized functionality and are supported and maintained by hybris.


hybris Commerce Suite is run in a Java Virtual Machine on a Servlet Container or a J2EE-compliant application server (such as IBM Websphere or Oracle WebLogic) and connects to an external database (MySQL, Oracle DB, Microsoft SQL Server). Internal caching and persistence mechanisms allow the hybris Commerce Suite to run on a Servlet Container. A full-fledged J2EE-compliant application server can be used, but is not necessary.


















What are the key Hybris commerce capabilities and features which comes out of the box  ?

General Storefront Capabilities - Language selection , Country selection , Currency selection , SEO frienddly URLs
Product Search - Solr-based product search with Keyword Search , Keyword Autocomplete , Spelling suggestions , Faceted browsing and more
Merchandising
Personalization and Promotion
Catalog Navigation
Product Display
Cart
Checkout
Hosted Payment
Customer Account
Store Location
Content Management
Data Import / Export
Google Local / Google Shopping
Content Pages and Templates
Organization Management
Jirafe Customer Intelligence
Google Analytics
Quote Negotiation
Order Approval
Order Management (OMS)
Store Locator
Device Detection

Lets dig deeper into some of the other concepts which is essential to know –

Hybris Cockpit framework –
The hybris Cockpit framework offers a large number of highly configurable components which can be used to build a new cockpit for your customers needs, such as for example workflow and comments.

The hybris Cockpit framework is the foundation for all hybris Cockpits. It offers a large number of highly configurable components, which can be used to build a Graphical User Interface (GUI) to support high-level business use cases, allowing users to perform all their common tasks quickly and intuitively. The hybris Cockpit framework complements the functionality offered by the hMC, which provides lower-level control over all the data in the hybris system.

The hybris Cockpit framework is based on ZK, a rich internet application (RIA) framework that enables desktop-like GUIs within a web browser. The ZK Framework is also well supported by Spring. ZK delivers a rich set of user interface (UI) components, making it easy and quick for developers to deliver a rich front end experience.

The major features of the hybris Cockpit framework include:
  • Security infrastructure based on Spring security
  • Ready to use front end template
  • Base configuration as a starting point for new applications, based on Spring
  • Reusable front end components in addition to existing ZK components
  • Generic abstraction of persisted items in the front end layer via the Type Service
  • GenericSearch providers
  • Highly customizable front end
  • Automatically stored user interface configuration at application run time
  • Drag and drop functionality
Here’s the key Hybris cockpits listed with brief description -

Hybris Administration Console -  The hybris Administration Console is an administration Web page provided by the hac extension. It provides functionality for administration, monitoring, and configuration of the hybris Commerce Suite.
Hybris Management Console (hMC) - hMC is the administration tool of the hybris Commerce Suite. As part of the hybris Commerce Suite, it runs in web browsers. Using the hMC, you can manage business objects of the hybris Commerce Suite such as products, customer data, orders.

Product Cockpit - The hybris Product Cockpit enables organizations to manage and structure product information and catalogs in high-volume and collaborative environments. Product managers can visualize their input from multiple perspectives and make product management processes more efficient

WCMS Cockpit - The hybris WCMS Cockpit enables you to manage data of a website. For efficient management of information on your online shop, you can use both the catalog perspective and live edit perspective. Each of them provides you with different ways of data management.
In the hybris WCMS Cockpit you can easily do the following:
·         Create and update website pages and content components
·         Check and change website pages status
·         Synchronize catalog versions of your website
·         Create collections of chosen pages
·         Search for website pages, according to advanced criteria

Admin Cockpit - At present, the hybris Administration Cockpit is used for the manipulation of: Data Validation constraints and Instances of types

Customer service Cockpit - The hybris Customer Service Cockpit enables you to quickly and efficiently manage the customer and orders in the call-center environment. 

Report Cockpit - The hybris Reporting Module adds Report Cockpit in which users can create and manage personal Dashboard containing rich graphical report widgets.

Print Cockpit - The hybris Print Cockpit enables you to create the publication structure and to manage the publication data for in an intuitive and user-friendly way. Linked with Adobe InDesign, it is a unique and powerful application.

Lets take closer look at some technical bits –

Adding a new page in Hybris –
  • Create a new page using the cmscockpit and with the available templates(we can also create new templates using the hmc as per the requirement).
  • Add components to the content slots available
  • Create a controller to handle the user requests for the newly created page.
  • Get the request mapping from the request, perform the business logic and return the model and view

Adding a new component in Hybris –
  • Create own item in items.xml file as below
            jaloclass="de.hybris.platform.endeca.jalo.cms2.components.OurComponent">
           //necessary attributes go here.....
  •  Create a new controller OurComponentController.java
      Note: The name of controller is important and should be created as follows: Component Type +"Controller" (in       our case OurComponentController). Beside that we also have to create a representation of our component           ourComponent.jsp

      All the controllers  are defined the way we define beans in Spring MVC in the spring-servlet.xml file as                 mentioned below
  •  Perform the business logic and return the model and view.


Creating new extensions --
The hybris Commerce Suite comes with an extension generator system called extgen located in the ${HYBRIS_BIN_DIR}/platform/extgen/ directory. Using extgen, you can create new extensions based on extension templates.

The hybris Commerce Suite comes with the following extensions, which you can use as a template for new extensions:

yempty
ycockpit
yaddon
ybackoffice
yacceleratorstorefront
yacceleratortest
ycommercewebservices
yinstoreinitialdata
yacceleratorcore
yacceleratorfacades
yacceleratorinitialdata

Extgen prompts you to specify:
  • The extension's name.
  • The extension's Java package.
  • The extension template to use.
After you have provided the prompted values, extgen does the following:
  1. Copying the extension template to a temporary directory.
  2. Modifying the extension template to reflect the specified values.
  3. Copying the new extension from the temporary directory to the directory specified by  the extgen.extension.path property in the project.properties file.
To create a new extension we follow following steps -
  1. Optionally: Modify default values for the extension generation process.
  2. Create a new extension.
  3. Reference the new extension in localextensions.xml file.
  4. Rebuild the hybris Commerce Suite.
  5. Update the hybris Commerce Suite.
Afterwords, you can start implementing your business logic in the new extension.

How to get started with Hybris ?
Best to register at https://wiki.hybris.com and get started. As of now they only allow certain partner companies to register so please check with your organization.
Once you registered at their wiki then you can access the product documentation.

I would highly recommend doing the Hybris core and commerce Trails. They are logically sequenced and it helps to understand overall product features and capabilities. Make sure you are good with Spring framework fundamentals , Annotations and ant commands.



Final thoughts ... No deny that Hybris has put great efforts to bring a light weight agile commerce framework which seems very promising. Best part is it cuts lot of development time to build some of the common features in a commerce site in no time, Their modular approach and open stack also gives you enough choice to pick and chose as per your need. It will be interesting to see how their future releases fair. I am yet to see how it scales and perform in a high volume and high transaction environments.

Sunday, November 10, 2013

Emerging languages series - Groovy

Our favorite Java is getting some serious competition in recent years , It seems there are more than 200 languages that target Java platform.
There is growing interest in languages like Scala, Groovy , Clojure , JRuby, Jython for their features and simplicity. Out of this lot we will take a close look at Groovy today as its getting wide attention in the market over recent years.

Why Groovy ?
  • Groovy is more or less a superset of Java
  • Builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • Could seamlessly switch back and forth between Java and Groovy 
  • Considered simpler and easier to learn over Jython and JRuby
  • Groovy has Java-like syntax and hence the learning curve is not steep.
  • Simplifies testing by supporting unit testing and mocking out-of-the-box

Once you install Groovy, you could straightaway start programming in Groovy,  just put your Groovy jar file along with your application and get the program working in any machine.
There are many online editors and IDE plugin available to compile and run your Groovy code.

So what is Groovy ?
James Strachan conceived the idea of Groovy language and started development in 2003.
Groovy is a dynamic language that dynamically compiles the code to the Java platform. It is popular as a scripting language and also widely used for unit testing Java code. Groovy is open source (Apache v2 license) and is backed by VMware.
The current stable release is Groovy 2.2. You can use Groovy in most common operating systems like Linux, Windows, and Mac. 

Let’s see how Groovy looks better Java with few examples –

Hello World Example –

// Java
class HelloWorld {
public static void main(String []args) {
System.out.println("Hello world");
}
}

// Groovy
println("hello world")


More Detailed Examples –

Let’s take a look at collection (map) processing example. Lets create a map and do some processing in both Java and Groovy.

// Java
Map worldCapitals = new HashMap<>();
worldCapitals.put("England", "London");
worldCapitals.put("Japan", "Tokyo");
worldCapitals.put("France", "Paris");
worldCapitals.put("Italy", "Rome");
worldCapitals.put("USA", "Washington");
for(Map.Entry capital : worldCapitals.entrySet()) {                       
System.out.printf("%s => %s \n", capital.getKey(), capital.getValue());
}

// Groovy
def worldCapitals =   [ "England" : "London",
"Japan" : "Tokyo", 
"France" : "Paris",
"Italy" : "Rome",
"USA" : "Washington" ]
worldCapitals.each {
key, value ->  
println "$key = $value" 
}

In this case Groovy provides a simple array-like syntax for the Map data structure. See how use of each() method closure makes it simple to write the code.

We all know how we write custom code to sort a map by value in Java but the same can be achieved in a line with Groovy. See below -

def sortedMap = worldCapitals.sort { it.value }
sortedMap.each {
key, value ->  
println "$key => $value" 
}

In above Groovy code, we just passed the it.value (current iterator’s value) to the sort method. With the power of closures, the code became much simple and readable.
Groovy provides a higher-level abstraction to this functionality, and hence the code is much simpler.

Tip - The soon to be released Java 8 has also introduced concept of closures in form of  "lambda expressions". It will be interesting to see how Java is incorporating these new age language features in their new release. I will write separate post to cover Java 8 features and capabilities soon.

XML Generation Example -
In general it’s very common to generate structured output like HTML , XML or JSON in Java code. So let’s see one example around this piece.

// java
PrintWriter pw = new PrintWriter(new FileWriter("/capitals.xml"))
pw.println("");
for(Map.Entry capital : worldCapitals.entrySet()) {                  
pw.printf("\t \n \t\t '%s' \n \t \n", capital.getKey(), capital.getValue());
}
pw.println("
");


// Groovy
def capitals =   [ "England" : "London",
"Japan" : "Tokyo", 
"France" : "Paris",
"Italy" : "Rome",
"USA" : "Washington" ]

xmlbuilder = new groovy.xml.MarkupBuilder()
xmlbuilder.worldcapitals {
capitals.each {
key, value ->
country(name:key) { capital(value) }
}
}

Now just see how simple it is to do the same thing with Groovy with lot of readability. Groovy supports builders (based on Builder design pattern) for creating HTML and XML files.

Take away from this comparison -
  • Traversing a data structure is easy in Groovy - you can use “closures” instead of plain loops and use each() method. 
  • Groovy is high on meta-programming and regular expression handling capabilities.
  • Groovy builders are fabulous if you dealing with HTML , XML , JSON etc.
  • Better for productivity and code readability for sure
  • Being a dynamic language Groovy is an excellent candidate for creating DSLs (Domain Specific Languages)

We have just tried to explore few basic features of Groovy here. You should explore further programming improvements such as automatic check for nulls, helper methods, embedded expressions in strings, and operator overloading. One should also explore its meta-programming and regular expression handling capabilities.
You’ll find Grails web framework and Groovy Server Pages (GSP) interesting if you are a serious web-developer. If you are an admin, you may find Gradle build automation framework useful. Grails framework (that is similar to Ruby on Rails) is built on top of powerful and popular frameworks such as Spring and Hibernate.
Resources to learn further –
Programming Groovy 2 - Dynamic Productivity for the Java Developer, By Venkat Subramaniam
Groovy in Action, By Dierk Koenig, Andrew Glover, Paul King, Guillaume Laforge, Jon Skeet

If you are a developer, tester or script guru, you have to love Groovy. So keep grooving and have fun with it !!

Friday, February 15, 2013

What TDD won’t tell you and why BDD is equally important?

Most of us think Test Driven Development is a cycle of test, implement and refactor. In reality its the freedom to start working toward your solution before you can map it all out.

It’s the freedom to make changes knowing your tests will alert you if you have violated a previous assumption that you have forgotten.

Since TDD forces you to write test first, it also forces you to think about how you want to use an API, because that is the very first thing you write down. This is a good thing and it leads to more usable APIs.
TDD also forces you to factor out dependencies in order to be able to mock them. Thats the other point where TDD encourages good design.
Now here comes the twist : There is more to software design than just nice to use APIs and good principles.TDD does almost nothing for you in order to find a good solution for your problem. 
TDD won’t tell you following -
  • Can your domain model represent all the cases needed by the business?
  • Which of all the design patterns would help you? Is there any well known algorithm you could use to solve your problem? 
  • Does the problem become trivial once you approach it in a functional way?
  • Is recursion a solution or a dead end?

Ultimately one has to understand the problem and know lots of possible approaches to a problem in order to design software well. There is just no way around it.
Once you have the solution in your mind, once you know the basic data structures and algorithm you going to use, TDD will help you to implement it in a clean, well factored way.
Having said enough about TDD I would like to now shift my focus on BDD (Behavior Driven Development) and its real value.
TDD is more “low level” talking about unit tests and integration tests and how to write code that tests real code while BDD is about specifications and behaviors.
In TDD we talk about Arrange Act Assert while in BDD we have Given When Then
There are clear cut differences between both. BDD is more “high level” dealing with specifications and was intended to be used by domain experts as well as developers
As a matter of fact one should write unit tests as well as specifications – because we need to test both.
TDD is described by a basic red-green-refactor cycle, I have come across this interesting checklist on dzone which is written in the form of questions we should ask ourselves while going through the different phases of the cycle.


Happy Testing :)

Sunday, January 06, 2013

ATG DUST – A JUnit framework for ATG applications



Well we all have been writing the classic JUnit tests from years now but it becomes challenging to write test cases when you dealing with framework like ATG.
So here comes ATG DUST - A framework for writing JUnit tests for applications built on the ATG Dynamo platform.

Its indeed makes our life lot simpler by providing some amazing features. The highlight of this framework is that it allows one to quickly write test classes that depends on Nucleus or ATG Repositories. By using ATG DUST one can drastically cut down on development time. It takes only a few seconds to start up a test with a repository, not like application server which takes good time to start up.

To get started go straight to first test page . This page will walk you through the process of running a basic test which starts Nucleus.

This tutorial walks you through the steps of writing a test which does not need to run in an application server. This is one of the underlying benefits of writing unit tests.
The test does not depend upon starting up an application server so turnaround time is also very quick.

Visit out-of-the-box-component-testing page which gives you a feel of simple test class. Try to open the java source (StartWithModulesTest.java) file attached there to get a fair idea how easy to use ATG DUST.

The best part I liked about ATG DUST is having the ability to load any specific ATG module and write a quick Repository test class. Go to the repository test page for a simple example.
The repository is started up against an in-memory Hypersonic Database.

DUST also support Formhandler test features with the help of utility (ServletTestUtils) class which can create a dummy Dynamo Request/Response pair.

Some of the key classes to look at –
atg.adapter.gsa.GSATest - A basic GSA test which has several utility methods.
atg.test.util.DBUtils  - Utility code for getting a connection to a database. The most common method is getHSQLDBInMemoryDBConnection.
atg.test.util.FileUtil  - A collection of utility methods for dealing with the file system.
atg.nucleus.NucleusTestUtils - This class contains some utility methods to make it faster to write a unit test that needs to resolve components against Nucleus.

Note on ATG version support – ATG DUST was developed using 9.0 but it work on most ATG versions back to 7.2 . I used ATG DUST version 1.2.2

Download ATG DUST

Popular Posts