Showing posts with label mock testing. Show all posts
Showing posts with label mock testing. Show all posts

Monday, September 26, 2011

Hibernate(JPA), Spring MVC and JBoss 6


After spending many hours finally i am able to configure Spring with Hibernate in JBoss Server.
For this application I have used Spring 3.5, Hibernate 3.5.1 and JBoss 5 and 6.
Following are some important configuration file required for this Integration
Here is link for application Source Code

https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B0YFdqXJcI3mMTgxZDc2OGItMjM4NS00NTA5LWJjMzQtNTUzNTc4ZGNmMGFm&hl=en_US

web.xml
No Speciall Configuration is required in web.xml. Here is how i configiured Controller Servler

  <servlet>
        <servlet-name>Spring MVC</servlet-name>
           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
        <servlet-name>Spring MVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>



persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="helloworld" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/OracleDS</jta-data-source>
     <class>com.playground.beans.Message</class>

    <properties>
      <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9Dialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
       <property name="hibernate.show_sql" value="true"/>
     <!-- Print sql executed - useful for debugging -->
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.format_sql" value="true"/>
    <!-- Auto-detect entity classes -->
       <property name="hibernate.archive.autodetection" value="class, hbm"/>

    </properties>
  </persistence-unit>
  </persistence> 


spring.xml 


<?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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop.xsd">

       <mvc:resources mapping="/resources/**" location="/resources/"/>
          <mvc:annotation-driven/>
         
         <context:component-scan base-package="com.playground"/>
        
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
        </bean>

        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">   
            <property name="persistenceUnitName" value="helloworld" />
         </bean>
   
     <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
          <property name="transactionManagerName" value="java:/TransactionManager" />
          <property name="userTransactionName" value="UserTransaction" />
     </bean>


     <!-- Use Spring AOP capabilities to manage transactions -->
    <aop:config>
      <aop:pointcut id="accountTransactions"
               expression="execution(* com.playground.services.ProcessMessage.*(..))"/>
      <aop:advisor pointcut-ref="accountTransactions" advice-ref="txAdvice" />
    </aop:config>

        <tx:advice id="txAdvice" transaction-manager="transactionManager">
          <tx:attributes>
            <tx:method name="processMessage" propagation="REQUIRED"/>
            <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
          </tx:attributes>
        </tx:advice>
 </beans>



DAO File

package com.playground.dao;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.playground.beans.Message;
@Component("MessageDAO")
public class MessageDAO {
   
   @Autowired
   EntityManagerFactory entityManagerFactory;
    public String processMessage(Message message){
                EntityManager manager=entityManagerFactory.createEntityManager();
                System.out.println("Here I reached in Last Point:"+message.getMessageText());
                manager.persist(message);
                return "Sucess";
    }
    }

Maven POM File
I used maven for war file creation and dependencies resolution. Following is my POM file. Most important point we need to take care is that your war file should not contains Hinernate jar files becuase this will make conflict with JBoss Hibernate libraries
Following is my POM file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>PlayGround</groupId>
    <artifactId>PlayGround</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>PlayGround</name>
    <url>http://maven.apache.org</url>
    <dependencyManagement>
        <dependencies>
        </dependencies>
    </dependencyManagement>
    <properties>
        <springframework>3.0.5.RELEASE</springframework>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework}</version>
        </dependency>
       
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>3.0.5.RELEASE</version>
        </dependency>
       
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
       
        <!-- logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.6.1</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
            <scope>runtime</scope>
        </dependency>


        <!-- Hibernate Stuff -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.1-Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>3.2.0.Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.5.1-Final</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>3.5.1-Final</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.0.Final</version>
            <scope>provided</scope>
        </dependency>


    <!-- Required only for Release in Jboss if we Exclude Hibernate becuase of conflict with JBoss -->
   
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.6</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
       
            <dependency>
                <groupId>commons-collections</groupId>
                <artifactId>commons-collections</artifactId>
                <version>3.1</version>
            </dependency>
       
       
            <dependency>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
                <version>1.6.1</version>
            </dependency>
       
            <dependency>
                <groupId>asm</groupId>
                <artifactId>asm</artifactId>
                <version>3.1</version>
            </dependency>
       
            <dependency>
                <groupId>antlr</groupId>
                <artifactId>antlr</artifactId>
                <version>2.7.6</version>
            </dependency>

            <dependency>
                    <groupId>xml-apis</groupId>
                    <artifactId>xml-apis</artifactId>
                    <version>1.0.b2</version>
                    <scope>provided</scope>
            </dependency>
   
   
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>1.0.0.GA</version>
                <scope>provided</scope>
            </dependency>
           
        </dependencies>
    <build>
        <finalName>PlayGround</finalName>
        <defaultGoal>package</defaultGoal>

      <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <locales>en</locales>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


Wednesday, September 14, 2011

Why and how to use Mockito

Mockito is an open source testing framework for Java. This framework allows creation of “Mock Objects” during Unit testing for the purpose of Test Driven Development. It helps you to create Mock Objects and define behaviour of these objects so you can use them as per your requirement in your test cases
Main Website for Mockito
http://code.google.com/p/mockito/
Mockito Example
To run Mockito example you should have mockito jar in your project class path. In my example I am using Maven to build project
http://code.google.com/p/mockito/downloads/list
Sample Class Source Code       
import static org.junit.Assert.assertEquals;import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.junit.Test;

public class MockitoTestCases {

 @Test
 public void example1() {

  /*
   * A Simple Example where you we have used VERIFY. Test Result will be
   * successful if we verify with 1 Else test result will be failure
   */
  List mockedList = mock(List.class);
  mockedList.add("1");
  // This will make test result successful
  verify(mockedList).add("1");
  // This will make test result failure
  // verify(mockedList).add("2");

  mockedList.get(10);
  verify(mockedList).get(10);
  // This will make test fail
  // verify(mockedList).get(101);

  // Here we are mocking an Iterator
  Iterator ii = mock(Iterator.class);
  ii.next();
  verify(ii).next();
  // This will make test result failure because notify method is not
  // called for this object
  // verify(ii).notify();

  // Verify Times
  List mockedList1 = mock(List.class);
  mockedList1.add("1");
  mockedList1.add("1");

  verify(mockedList1, times(2)).add("1");
  // This will make result failure becuase add is only called 2 times
  // verify(mockedList1, times(3)).add("1");

  // Here We are mocking an Object behaviour by specifying WHEN clause
  ArrayList<String> mockedList2 = mock(ArrayList.class);
  mockedList2.add("one");

  when(mockedList2.get(0)).thenReturn("first");
  System.out.println(mockedList2.get(0));

  when(mockedList2.add("1")).thenReturn(true);
  System.out.println(mockedList2.add("1"));

  when(mockedList2.add("1")).thenReturn(false);
  System.out.println(mockedList2.add("1"));

  System.out.println(mockedList2.size()); // return 0
  when(mockedList2.size()).thenReturn(100);
  System.out.println(mockedList2.size());// return 100

  /*
   * Create a ArrayList using Mockito. If some one will inquire 99th
   * element it will return results else it will return null value
   */

  ArrayList<String> mockObject = mock(ArrayList.class);
  when(mockObject.get(99)).thenReturn("I am 99th Object");

  System.out.println(mockObject.get(0)); // return null
  System.out.println(mockObject.get(99)); // return I am 99th Object

  System.out.println(mockObject.size()); // return 0
  when(mockObject.size()).thenReturn(10);
  System.out.println(mockObject.size()); // return 10
  for (int i = 0; i < mockObject.size(); i++) {
   System.out.println("I am priting i:" + i);
  }
  // but if you write mockObject.get(i) it will return null

  for (int i = 0; i < mockObject.size(); i++) {
   System.out.println("I am priting mockObject.get(i):"
     + mockObject.get(i));
  }

  // Here we are mocking an Iterator
  Iterator i = mock(Iterator.class);
  when(i.next()).thenReturn("Hello").thenReturn("World");
  String result = i.next() + " " + i.next();
  // This makes test successful
  assertEquals("Hello World", result);
 // This makes test fail
  // assertEquals("Hello World1", result);
}
}

 Maven Dependencies for Mockito and JUnit
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>1.9.0-rc1</version>
  <scope>test</scope>
</dependency>

  <!—Or if you needs extra dependencies: objenesis & hamcrest -->
<dependency>
    <groupid>org.mockito</groupid>
    <artifactid>mockito-all</artifactid>
    <version>1.8.5</version>
    <scope>test</scope>
</dependency>

Maven POM.XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>MockitoTest</groupId>
  <artifactId>MockitoTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>MockitoTest</name>
  <url>http://maven.apache.org</url>
<dependencies>
  <dependency>
   <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>1.8.5</version>
      <scope>test</scope>
  </dependency>
 <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.8.2</version>
   <scope>test</scope>
  </dependency>
</dependencies>
<build>
  <finalName>MockitoTest</finalName>
  <testSourceDirectory>src</testSourceDirectory>
  <testResources>
   <testResource>
    <directory>src</directory>
   </testResource>
  </testResources>
 <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.1</version>
    <configuration>
     <source>1.6</source>
     <target>1.6</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-site-plugin</artifactId>
    <version>2.3</version>
    <configuration>
     <locales>en</locales>
    </configuration>
   </plugin>
   </plugins>
 </build>
</project>