Author Archives: Krishna

About Krishna

Applications for social medium

Implementing Controller using Play 2.x (Scala), ScalaMock

For people in hurry here is the code and the steps.

In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how we implement a simple Controller implementation using ScalaTest / ScalaMock. I will continue from my earlier example of Implementing DAL in Play 2.x (Scala), Slick, ScalaTest of the basic CRUD operations on Coffee catalogue.

In this example as well we need the ScalaMock dependency in Build.scala as below,

 
"com.typesafe.slick" %% "slick" % "1.0.0",
...
"org.scalamock" %% "scalamock-scalatest-support" % "3.0" % "test",

In our Previous example, we have already implemented a DAL trait called CoffeeComponent with basic CRUD as below,

trait CoffeeComponent {
  def find(pk: String): Query[Coffees.type, Coffee]
  def findall(pk: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def list(page: Int, pageSize: Int, orderBy: Int, filter: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def delete(pk: String): Int
}

We are construction injecting CoffeeComponent to the CoffeeController and create a Singleton object with the same name, as below,

class CoffeesController(coffeeComponent: CoffeeComponent) extends Controller {
...
  def delete(pk: String) = Action {
    database withSession {
      println("in db session")
      Home.flashing(coffeeComponent.delete(pk) match {
        case 0 => "failure" -> "Entity has Not been deleted"
        case x => "success" -> s"Entity has been deleted (deleted $x row(s))"
      })
    }
  }
}

object CoffeesController extends CoffeesController(new CoffeeComponentImpl)

As seen above, we have a delete method, we will build a ScalaMock to mock the delete method of coffeeComponent and control the expected behavior to return 1 row effected and assert for HTTP SEE_OTHER status as below,

class CoffeesControllerTest extends FunSpec with ShouldMatchers with MockFactory {
  describe("Coffee Controller with Mock test") {

    it("should delete a coffee record with assert on status") {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
        val mockComponent = mock[CoffeeComponent]
        (mockComponent.delete _).expects("Columbian") returning (1) twice
        val controller = new CoffeesController(mockComponent)
        mockComponent.delete("Columbian") should equal (1)
        val result = controller.delete("Columbian")(FakeRequest())
        status(result) should equal (SEE_OTHER)
      }
    }
  }
}

If you notice, we are extending FunSpec of ScalaTest for BDD. Also the HTTP status is SEE_OTHER, this is because the Success is redirected to Index page.

Now if you run the ScalaTest you will see the result in STS as below,

ScalaTest Coffee Example with ScalaMock

ScalaTest Coffee Example with ScalaMock

I hope this blog helped. In my next blog, I will talk about controller routes testing and Frontend testing.

Advertisements

Implementing DAL in Play 2.x (Scala), Slick, ScalaTest

For people in hurry here is the code and the steps.

In continuation of Play 2.x (Scala) is it a Spring MVC contender? – Introduction, in this blog, I will demonstrate how we implement a simple Data Access Layer using ScalaTest and using Behavior Driven Development.

The technical stack I will be using for this demo is Java 7, Play 2.1.0, Scala 2.10.0, Slick 1.0.0, ScalaTest / ScalaMock 3.0, STS IDE for Scala Development, Scala IDE plugin with ScalaTest.

As a first step create a Play project called coffee-example and select the language as Scala as below,

play new coffee-example

Now we need to include these dependencies in Build.scala. In this example, we don’t need ScalaMock but we will still include that dependency as below,

"com.typesafe.slick" %% "slick" % "1.0.0",
...
"org.scalamock" %% "scalamock-scalatest-support" % "3.0" % "test",

Let us convert this project into Eclipse project as below,

play eclipse

Let us open STS IDE and create a DomainTest.scala under test folder. The intent is we create a new CoffeeComponent class and implement a method findById method and pass a Coffee name and return the Coffee object and assert for its price. We also need initialize the data we are supposed to assert.

class DomainSpec extends FunSpec with ShouldMatchers with InitTrait {

  lazy val database = Database.forDataSource(DB.getDataSource())

  describe("Coffee Data Access") {

    it("should find Coffee object for a given Coffee name") {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
        database withSession {
          init

          val cc = new CoffeeComponentImpl()
          val c = cc.find("Colombian")
          c.first.price should equal(799L)
        }
      }
    }
  }
}

One bug I noticed is, when there are multiple test cases opening database connection it will create Attempting to obtain a connection from a pool that has already been shutdown error.

We create a CoffeeComponent trait and CoffeeComponentImpl, which create basic CRUD operations as below,

trait CoffeeComponent {
  def find(pk: String): Query[Coffees.type, Coffee]
  def findall(pk: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def list(page: Int, pageSize: Int, orderBy: Int, filter: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)]
  def delete(pk: String): Int
}

class CoffeeComponentImpl extends CoffeeComponent {

  def find(pk: String): Query[Coffees.type, Coffee] = {
    Coffees.findByPK(pk)
  }

  def findall(pk: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)] = {
    Coffees.findAll(pk)
  }

  def list(page: Int, pageSize: Int, orderBy: Int, filter: String): Query[(Coffees.type, Suppliers.type), (Coffee, Supplier)] = {
    Coffees.list(page, pageSize, orderBy, filter)
  }

  def delete(pk: String): Int = {
    find(pk).delete
  }
}

We also need to create the Initialize Data for the test as below,

trait InitTrait {
  def init = {
    val ddl = (Suppliers.ddl ++ Coffees.ddl)

    ddl.drop
    ddl.create
    // Insert some suppliers
    Suppliers.insertAll(
      Supplier(Some(101), "Acme, Inc.", "99 Market Street", "Groundsville", "CA", "95199"))
.....
    Coffees.insertAll(
      Coffee(Some("Colombian"), 101, 799, 0, 0))
}
}

Now run the ScalaTest from Eclipse IDE, you will see something as below,

ScalaTest Coffee Example

ScalaTest Coffee Example

I hope this blog helped you. In the next blog I will demonstrate how we can mock a Controller and test the Controller.

Integrating Play 2.1 with Slick 1.0.0 Database query DSL

For people in hurry here is the code and the steps to setup.

Refer this blog on Play 2.0: Building Web Application using Scala for details on Play and Scala.

In the next few blogs I will be writing enterprise class web application using Play and Scala. I will be covering topics like Database modeling and Security. Now officially Scala has adopted Slick as the Database query DSL. But when you create a new Play application and add Slick library as mentioned in this blog, it is not working. It gives a strange error like No suitable driver found in tests.

I also found slick-play2-example, this sample expect us to create a DAL layer, but we cannot directly play with slick in our test code.

After much further research I came across this plugin. I tried integrating this with my Play application and it worked like a charm.

We will define a Coffee class and a Supplier class. One Coffee has multiple Suppliers. The class design is as below,

case class Coffee(name: String, supID: Int, price: Double, sales: Int, total: Int)

object Coffees extends Table[Coffee]("COFFEES") {
def name = column[String]("COF_NAME", O.PrimaryKey)
def supID = column[Int]("SUP_ID")
def price = column[Double]("PRICE")
def sales = column[Int]("SALES")
def total = column[Int]("TOTAL")
def * = name ~ supID ~ price ~ sales ~ total <> (Coffee.apply _, Coffee.unapply _)
// A reified foreign key relation that can be navigated to create a join
def supplier = foreignKey("SUP_FK", supID, Suppliers)(_.id)
}

case class Supplier(id: Int, name: String, street: String, city: String, state: String, zip: String)

// Definition of the SUPPLIERS table
object Suppliers extends Table[Supplier]("SUPPLIERS") {
def id = column[Int]("SUP_ID", O.PrimaryKey) // This is the primary key column
def name = column[String]("SUP_NAME")
def street = column[String]("STREET")
def city = column[String]("CITY")
def state = column[String]("STATE")
def zip = column[String]("<a class="zem_slink" title="ZIP (file format)" href="http://en.wikipedia.org/wiki/ZIP_%28file_format%29" target="_blank" rel="wikipedia">ZIP</a>")
// Every table needs a * projection with the same type as the table's type parameter
def * = id ~ name ~ street ~ city ~ state ~ zip <> (Supplier.apply _, Supplier.unapply _)
}

Below is the ScalaTest to test various capabilities of Slick,

DB.withSession{ implicit session =>

//Populate sample data
val testSuppliers = Seq(
Supplier(101, "Acme, Inc.",      "99 Market Street", "Groundsville", "CA", "95199"),
Supplier( 49, "Superior Coffee", "1 Party Place",    "Mendocino",    "CA", "95460"),
Supplier(150, "The High Ground", "100 Coffee Lane",  "Meadows",      "CA", "93966")
)
Suppliers.insertAll( testSuppliers: _*)

val testCoffees= Seq(
Coffee("Colombian",         101, 7.99, 0, 0),
Coffee("French_Roast",       49, 8.99, 0, 0),
Coffee("Espresso",          150, 9.99, 0, 0),
Coffee("Colombian_Decaf",   101, 8.99, 0, 0),
Coffee("French_Roast_Decaf", 49, 9.99, 0, 0)
)
Coffees.insertAll( testCoffees: _*)

//Assert coffee data equals to the test list of coffee
Query(Coffees).list must equalTo(testCoffees)

//List all coffee less than $10
val q1 = for { c <- Coffees if c.price < 10.0 } yield (c.name)

q1 foreach println
println("**************");

//return all suppliers for coffee less than $9.0
val q2 = for { c <- Coffees if c.price < 9.0
s <- c.supplier } yield (c.name, s.name)

q2 foreach println
println("**************");

//return all suppliers for coffee using zip
val q3 = for {
(c, s) <- Coffees zip Suppliers
} yield (c.name, s.name)

q3 foreach println
println("**************");

//Union
val q4 = Query(Coffees).filter(_.price < 8.0)
val q5 = Query(Coffees).filter(_.price > 9.0)
val unionQuery = q4 union q5
unionQuery foreach println
println("**************");

//Union second approach
val unionAllQuery = q4 unionAll q5
unionAllQuery foreach println
println("**************");

//Group by
val r = (for {
c <- Coffees
s <- c.supplier
} yield (c, s)).groupBy(_._1.supID)

//Aggregation
val r1 = r.map { case (supID, css) =>
(supID, css.length, css.map(_._1.price).avg)
}

r1 foreach println
}

In my next blog, I will take a real example and implement using Slick. I hope this blog helped.

Integrating Kickstrap with Spring MVC application

Get the latest code from Github,

In continuation of my earlier blogs on Introduction to Spring MVC, in this blog I will talk about Kickstrap, Less and how Kickstrap can be integrated with our Spring MVC based bookstore application.

If you go to Kickstrap website they mention that it is Twitter Bootstrap on Steroids. It is heavily based on Less which is a dynamic stylesheet language. You can download Kickstrap from here.

Advantages of using Kickstrap is,

As a 1st step we need to copy the Kickstrap in the application folder as below,

kickstrap bookstore-app

kickstrap bookstore-app

The tiles definition in tiles.xml in Spring MVC is as below,

<tiles-definitions>
<definition name="template" template="/WEB-INF/templates/template.jsp">
<put-attribute name="header" value="/WEB-INF/templates/header.jsp"/>
<put-attribute name="footer" value="/WEB-INF/templates/footer.jsp"/>
</definition>
...
</tiles-definitions>

In the template.jsp you need to add Kickstrap.less and less-1.3.0.min.js as below,

<link rel="stylesheet/less" type="text/css" href="/bookstore-example-with-mvc/resources/css/kickstrap.less">
<script src="/bookstore-example-with-mvc/resources/css/Kickstrap/js/less-1.3.0.min.js"></script>

If you see the template.jsp, we use some of the css class of Kickstrap like “container”, “row-fluid” and others. row-fluid helps in responsive web design.

Changing to different theme

In Kickstrap changing to different theme is easy. Open the theme.less, currently we are using cerulean theme, as below

@import "Kickstrap/themes/cerulean/variables.less";
@import "Kickstrap/themes/cerulean/bootswatch.less";

Now run the below command and open the browser and type http://localhost:8080/bookstore-example-with-mvc,

mvn clean tomcat7:run

The theme looks as below,

cerulean-theme

cerulean-theme

Below are the themes when you drilldown Kickstrap folder as shown below,

themes-bookstore-app

themes-bookstore-app

If you want to change it to, let us say cyborg theme, you need to change kickstrap.less as below,

@import "Kickstrap/themes/cyborg/variables.less";
@import "Kickstrap/themes/cyborg/bootswatch.less";

Now run the below command and open the browser and type http://localhost:8080/bookstore-example-with-mvc, you will see the change in theme,

mvn clean tomcat7:run

The theme is changed and looks as below,

cyborg-theme

cyborg-theme

I hope this blog helped you.

Reference:

Pro Spring MVC: With Web Flow by by Marten Deinum, Koen Serneels

JUnit testing of Spring MVC application – Introduction

For people in hurry, here is the Github code and the steps to run the sample.

Spring MVC is one of the leading Java Web application frameworks along with Struts. In the next few blogs, I will take an use case and demonstrate how to develop a good quality web application in an enterprise Java world. I will also demonstrate latest capabilities of Spring like Annotation based configurations and its advantages over XML based configurations. Prerequisite for this application is Java 7.x, Tomcat 7.x, Maven 3.x and STS IDE.

The use case I will be talking about is a Bookstore application, where in user register to this application and purchase books. There is also an administration task like creating the book catalog.

Spring MVC application architecture

Source Java9s: Spring MVC Architecture

Source Java9s: Spring MVC Architecture

For this sample application we extensively use the Latest Spring MVC annotation capability. The major advantage with this is we will not be depending on any xml configuration including web.xml. I personally like XML configuration with namespace, because it is readable. The advantage of annotation is, since everything is Java, if we use STS IDE, any typo can be caught at compilation time,  and we can write a good quality code and even measure the code coverage. We also used Kickstrap as the css engine for this application. Here is a blog on Integrating Kickstrap with Spring MVC application.

What is code coverage

Code coverage is a measure of how well you unit tested your code. If you use a good IDE like STS IDE we can install ecobertura using the update site. Once you setup ecobertura, you can start developing your application. When you run your JUnit test in “Cover as” mode, it will show the code coverage of your JUnit tests as below,

eCobertura STS-IDE view

eCobertura STS-IDE view

In the subsequent blogs I will use test driven development (TDD) to build each layer and gradually increase the code coverage and write better quality code. The layers I will be developing in TDD in the order are,

Reference:

Pro Spring MVC: With Web Flow by by Marten Deinum, Koen Serneels

JUnit testing of Spring MVC application: Testing Spring Webflow

For people in hurry get the latest code from Github and run the below command,


mvn clean test -Dtest=com.example.bookstore.web.controller.CreateOrderTest

In continuation of my earlier blogs on Introduction to Spring MVC and Testing Frontend using Selenium in Spring MVC, in this blog I will demonstrate how to test Web layer in Spring MVC and Spring Web Flow. If you want to measure the quality of JUnit testing of your Spring Web Flow application refer Measuring navigation flow JUnit test in Spring Web flow. There is another blog I have written on JUnit testing Spring Web Flow refer JUnit testing with Spring Webflow.

In this blog I will demo how to build a Spring Web Flow based application using Test driven development (TDD). The use case I will be talking of is a web flow where in user drills down thru few categories and selects few books and select delivery options and place an order.

There is a good introduction of Spring Web Flow here. But just to give a brief introduction about Spring Web Flow, it is composed of a set of states. A state is a point in the flow where some event happens: for instance showing books list for a category or adding the books to the shopping cart. Each state has one or more transitions that are used to move to another state. A transition is triggered by an event.

As a first step, please refer this createOrders-flow.xml, if you notice carefully OrderForm is stored in the flowScope. And this object carries the state between each step. Let us see the bootstrapping process in JUnit test as below,

public class CreateOrderTest extends AbstractXmlFlowExecutionTests {
private OrderController orderController;

protected void setUp() {
orderController = Mockito.mock(OrderController.class);
}

@Override
protected void configureFlowBuilderContext(MockFlowBuilderContext builderContext) {
builderContext.registerBean("orderController", orderController);
}

@Override
protected FlowDefinitionResource getResource(FlowDefinitionResourceFactory resourceFactory) {
return resourceFactory.createFileResource("src/main/webapp/WEB-INF/view/public/createOrders/createOrders-flow.xml");
}

//JUnit tests below
}

If you notice this class is subclassed from a class AbstractXmlFlowExecutionTests, it has 3 overridden methods, setup, configureFlowBuilderContext, getResource. getResource method is the one where we set the createOrders-flow.xml and is returned for testing. If you also notice we have used Mockito to mock OrderController and register the bean in the flow XML.

Let us start building the JUnit test to test each node (view-state) of the flow. For starting the flow you need to do as below,

public void testStartCreateOrderFlow() {

MutableAttributeMap input = new LocalAttributeMap();
MockExternalContext context = new MockExternalContext();
startFlow(input, context);

Mockito.verify(orderController, VerificationModeFactory.times(1)).initializeForm();
Mockito.verify(orderController, VerificationModeFactory.times(1)).initializeSelectableCategories();

assertCurrentStateEquals("selectCategory");
assertResponseWrittenEquals("selectCategory", context);
}

If you notice carefully in the flow, we are asking the controller to call the initializeForm at on-start event and call initializeSelectableCategories at on-render of selectCategory view-state.

Using Mockito we are verifying if the initializeForm and initializeSelectableCategories called once only. And finally we assert for the next state.

Similarly we test other view states.

Finally we test calling a subflow by mocking the subflow, refer createMockBookingSubflow below you will get the idea. If you want to understand more refer Mocking a subflow.


public void testSelectDeliveryOptions_AddAndNext() {

setCurrentState("selectDeliveryOptions");
 getFlowScope().put("orderForm", createTestOrderForm());
 getFlowDefinitionRegistry().registerFlowDefinition(createMockBookingSubflow());

MockExternalContext context = new MockExternalContext();
 context.setEventId("finish");
 resumeFlow(context);
 }

private Flow createMockBookingSubflow() {
 Flow mockBookingFlow = new Flow("secured/placeOrders");
 mockBookingFlow.setInputMapper(new Mapper() {
 public MappingResults map(Object source, Object target) {
 // assert that 1L was passed in as input
 return null;
 }
 });
 // immediately return the bookingConfirmed outcome so the caller can respond
 new EndState(mockBookingFlow, "endOrderOk");
 return mockBookingFlow;
 }

I hope this blog helped you. In my next blog I will be taking about integrating Kickstrap with Spring MVC application.

Reference:

Pro Spring MVC: With Web Flow by by Marten Deinum, Koen Serneels

JUnit testing of Spring MVC application: Testing Frontend using Selenium

In continuation of my earlier blogs on Introduction to Spring MVC and Testing Controller in Spring MVC, in this blog I will demonstrate how to test Web layer in Spring MVC. We can also incorporate Authentication and Authorization, learn more about it in the blogs on Spring Security.

The objective of this demo is 2 fold, to build the plumbing for Web layer using TDD and actually test the web layer using Selenium Java API.

For people in hurry, get the latest code from Github and run the below 2 commands in order

mvn clean tomcat7:run

mvn clean test -Dtest=com.example.bookstore.web.frontend.SeleniumLoginFrontendTest

Maven dependency to use Selenium is as below

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.26.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>2.26.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-htmlunit-driver</artifactId>
<version>2.26.0</version>
<scope>test</scope>
</dependency>

Also you need to install Selenium IDE plugin for Firefox.

Since this is a web application, we need to build the plumbing for web application, See the com.example.bookstore.web.BookstoreWebApplicationInitializer for more details. Also notice that we don’t need any web.xml if we use the latest Spring 3.0. But when you try to build the project, maven complains that war project should have web.xml. In order to get around this we need to set failOnMissingWebXml to false as shown in the below configuration in pom.xml,

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
<archiveClasses>true</archiveClasses>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>

Now let us start exploring the JUnit test for this,

public class SeleniumLoginFrontendTest {

private WebDriver browser;

@Before
public void setup() {
browser = new FirefoxDriver();
}

@Test
public void startTest() {
browser.get("http://localhost:8080/bookstore-example-with-mvc/");

browser.findElement(By.id("login")).click();

// Will throw exception if elements not found
browser.findElement(By.id("username")).sendKeys("jd");
browser.findElement(By.id("password")).sendKeys("secret");

browser.findElement(By.id("loginButton")).click();
browser.findElement(By.id("account")).click();

assertEquals("John", browser.findElement(By.id("firstName")).getAttribute("value"));
}

@After
public void tearDown() {
browser.close();
}
}

Finally run the application in the tomcat7 using Maven command and run the JUnit test as mentioned in the beginning of this blog. The tests will succeed.

I hope this blog helped you. In my next blog, I will talk about how to implement Spring Web flow using TDD.

Reference:

Pro Spring MVC: With Web Flow by by Marten Deinum, Koen Serneels