Monday, February 24, 2014

Selenium webdriver Junit test example

Selenium is one of the best tool for automating web application testing. If number of pages of web application increase gradually, it is really hard for application tester to test every page after new deployment.

Selenium provide web driver for almost browser including firefox, IE, Google Chrome etc. Even you can integrate selenium web driver with Junit, TestNG or plan Java, .Net code.

Selenium provide two type of web drivers. Browser base driver like FirefoxDriver will open the Firefox browser and perform the test. In this case, Selenium will fill up all fields and click on necessary places, just like an automated robot. But if you want to write test cases that does't require browser then you can use  HtmlUnitDriver. It will create instance of in-memory browser. But browser base driver is important when you want to test your application whether its compatible with all modern browser like Google chrome, Firefox and IE.

You can download Selenium library from  http://docs.seleniumhq.org/download/.

However, you can add it in your project as maven dependency.
   
  
   org.seleniumhq.selenium
   selenium-java
   2.39.0
   
    
     org.seleniumhq.selenium
     selenium-iphone-driver
    
    
     xml-apis
     xml-apis
    
   
  
Following snippet  is showing initialization of Firefox web driver and HtmlUnitDriver.

Create a new instance of the html unit driver
private WebDriver driver= new HtmlUnitDriver();

 // Create a new instance of the Firefox driver
private WebDriver driver= new FirefoxDriver();


Here is an example showing how to perform login before test any secure page. In Junit @BeforeClass annotation method will be called before run any test case.


@BeforeClass
 public static void setUpBeforeClass() throws Exception {

  entity = new Users("moin", "123", "abc@gmail.com", "xyz",
    "");
         // Create a new instance of the html unit driver
  driver = new HtmlUnitDriver();
              
                // And now use this to visit your login URL. e.g 
  driver.get(serverBaseUrl + "/login");
                // set the user name in user id text field
  driver.findElement(By.name("j_username"))
    .sendKeys(entity.getUserName());
                 // set the password in user password text field
  driver.findElement(By.name("j_password"))
    .sendKeys(entity.getPassword());

  driver.findElement(By.className("pull-right")).click();
  System.out.println(driver.getPageSource());
  if (driver.findElement(By.cssSelector(".jumbotron")).getText()
    .contains("Welcome to ScrapperX")) {

   System.out.println("Login Success");
  } else {
   System.out.println("Login fail");
   throw new Exception("Login Require");

  }

  Thread.sleep(1000);
 }

After login you can test any secure page in the same session. Below snippet is showing how to test "update user profile page"
 
       @Test
 public void testUpdateProfile() {
  driver.get(serverBaseUrl + "/users/editprofile");
                // clear the exist first name or else sendKeys will append new text
  driver.findElement(By.name("firstName")).clear();
  driver.findElement(By.name("firstName"))
    .sendKeys(entity.getFirstName());
  driver.findElement(By.name("lastName")).clear();
  driver.findElement(By.name("lastName")).sendKeys(entity.getLastName());
  driver.findElement(By.name("password")).clear();
  driver.findElement(By.name("password")).sendKeys(entity.getPassword());
  driver.findElement(By.name("c_password")).clear();
  driver.findElement(By.name("c_password"))
    .sendKeys(entity.getPassword());
    // in several way you can select a checkbox
                 /*
   * List checkbox =
   * driver.findElements(By.name("paymentActive")); ((WebElement)
   * checkbox.get(0)).click();
   */
                // select paymentActive checkbox
  WebElement checkbox = driver.findElement(By.name("paymentActive"));
             
  if (checkbox.isSelected() == false) {
   checkbox.click();
  }

  driver.findElement(By.className("btn")).click();
  System.out.println(driver.findElement(By.cssSelector(".alert"))
    .getText());
  assertTrue("Update user profile fail",
    driver.findElement(By.cssSelector(".alert")).getText()
      .contains("Update Complete"));
 }


You can access any field or html element by css class name, id and field name. Following example is showing how to select a drop-down option.
   Select cardTypeDropDown = new Select(driver.findElement(By
    .name("cardType")));
   cardTypeDropDown.selectByValue("visa");

Here is an working example of testing Google search.
package com.scrapperx.web.controller;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSearchTest {

 @Test
 public void testGoogleSearch() throws InterruptedException {
  // Create a new instance of the html unit driver
  // Notice that the remainder of the code relies on the interface,
  // not the implementation.
  System.out.println("http://www.google.com");
  WebDriver driver = new FirefoxDriver();

  // And now use this to visit Google
  driver.get("http://www.google.com");

  // Find the text input element by its name
  WebElement element = driver.findElement(By.name("q"));

  // Enter something to search for
  element.sendKeys("tometo");

  // Now submit the form. WebDriver will find the form for us from the
  // element
  element.submit();

  // Check the title of the page
  System.out.println("Page title is: " + driver.getTitle());
        Thread.sleep(10000);
  driver.quit();

 }
}

Saturday, February 22, 2014

Bootstrap autocomplete using Typeahead JS

Typeahead provide very good solution for auto complete suggestion. Here is an example showing auto suggestion based on user query. When user type a keyword, a json request will be send to server side and response will be appeared right bottom of search field.
  
 

Thursday, February 20, 2014

Java junit lifecycle methods

 JUnit is more popular framework for unit testing in java.  JUnit provide four life cycle methods for each test case class.

 @BeforeClass and @AfterClass anotation used before methods which are called by framework once for all test case.

@Before  and @After are used on methods which are called before and after any test method run.

Here is an example code snippet.



package com.test;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class ExampleTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  
  System.out.println("Before all test case execution");
 }

 @AfterClass
 public static void tearDownAfterClass() throws Exception {
   System.out.println("After all test case execution");
 }

 @Before
 public void setUp() throws Exception {
    System.out.println("Before single test case execution");
 }

 @After
 public void tearDown() throws Exception {
  System.out.println("After single test case execution");
 }

 @Test
 public void testMethod1() {
   System.out.println("a");
 }

 @Test
 public void testMethod2() {
   System.out.println("b");
 }

}


Tuesday, August 27, 2013

Deploy war to WebLogic using Maven

First off you need Maven and Weblogic setup in your computer to start this tutorial.
My Weblogic(10.3.6.0) has setup under : C:\Oracle\Middleware.

Set Middleware home :
 
set MW_HOME=C:\Oracle\Middleware

1. Build the plug-in JAR file using the WebLogic JarBuilder Tool (wljarbuilder) under %MW_HOME%/wlserver_10.3/server/lib/ with the following command:
 
java -jar wljarbuilder.jar -profile weblogic-maven-plugin
The weblogic-maven-plugin.jar contains a Project Object Model (pom.xml) file which specifies the groupId, artifactId, version, and packaging of the weblogic-maven-plugin.jar:
 groupId=com.oracle.weblogic
artifactId=weblogic-maven-plugin
version=10.3.6.0
packaging=maven-plugin

2. Extract the pom.xml file from weblogic-maven-plugin.jar under the %MW_HOME% wlserver_10.3/server/lib directory, and then copy the pom.xml file to %MW_HOME%/wlserver_10.3/server/lib.
 
jar xvf %MW_HOME%/wlserver_10.3/server/lib/weblogic-maven-plugin.jar META-INF/maven/com.oracle.weblogic/weblogic-maven-plugin/pom.xml


copy %MW_HOME%/wlserver_10.3/server/lib/META-INF/maven/com.oracle.weblogic/weblogic-maven-plugin/pom.xml  to %MW_HOME%//wlserver_10.3/server/lib/pom.xml

Add following in your project pom.xml file:


3.Provision the weblogic-maven-plugin.jar in your local Maven repository with the following command. However, for a shortened command-line goal invocation of the plug-in, follow the directions in next step 4 before performing this step.
http://docs.oracle.com/cd/E21764_01/web.1111/e13702/maven_deployer.htm
 
mvn install:install-file -Dfile=%MW_HOME%/wlserver_10.3/server/lib/weblogic-maven-plugin.jar -DpomFile=pom.xml



4.
  you can shorten the full invocation of the plug-in by providing a pom.xml file  and modifying the settings.xml file located in your $HOME/.m2 directory, before you provision the plug-in in your Maven repository
  1. Change the settings.xml file as follows:
    
    
    
       
       com.oracle.weblogic
     

 b. Replace the %MW_HOME%/wlserver_10.3/server/lib/pom.xml file with the following(Use same version that was in the pom.xml):




  4.0.0
  com.oracle.weblogic
  weblogic-maven-plugin
  maven-plugin
  10.3.4
  Maven Mojo Archetype
  http://maven.apache.org
  
    
      org.apache.maven
      maven-plugin-api
      2.0
    
  
 
  
   
      
       maven-plugin-plugin
       2.3
       
         weblogic
       
      
    
  
 


From within MW_HOME/wlserver_10.3/server/lib/, run the mvn install command.

mvn install

From within MW_HOME/wlserver_10.3/server/lib/, provision the weblogic-maven-plugin.jar in your local Maven repository as follows:

mvn install:install-file -Dfile=%MW_HOME%/wlserver_10.3/server/lib/weblogic-maven-plugin.jar -DpomFile=pom.xml

Now, you can use a shortened command-line goal invocation, such as:

mvn weblogic:deploy

Deployment Goals
weblogic.deploy
weblogic:undeploy
weblogic:redeploy
weblogic:start-app
weblogic:stop-app
weblogic:list-apps
weblogic:update-app
weblogic:help


  

Create Oracle Stored Procedure example

Following is a basic oracle store procedure example:

CREATE OR REPLACE PROCEDURE procPrintHelloWorld
IS

 usr_id VARCHAR2(20):=' sujan ';
BEGIN
 
  DBMS_OUTPUT.PUT_LINE('Hello World!'|| usr_id);
 
END;
/
To see output on console you need to run following command.

 set serveroutput on size 30000;

Run store procedure:


 EXEC procPrintHelloWorld;

If you get any compilation error, run following command to display it.

SHOW ERRORS

Friday, August 16, 2013

Add SVN email notification

SVN email notification is important when many programmer involves  in software development. For example, you are working on module and other programmers are using that. So if you check-in updated the classes , you have to notify other developers that module has been updated.

SVN provide post commit hook option, there you can add any script or programme that would be execute after SVN commit. Here I will add email notification in post-commit hook script.

I have create a repository in /apps/subversion/hsolite/.
Using ls command you can see default directories created under repository. There is a directory called hooks where you will put you post-commit script. When any user will commit in SVN, post-commit script will be execute.


To send email notification you need find out "mailer.py" and "mailer.conf"

[root@domU-12-31-39-09-29-13 hsolite]# find / -name "mailer.py"
/usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/mailer.py


[root@domU-12-31-39-09-29-13 hsolite]#  find / -name "mailer.conf"
/usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/tests/mailer.conf

Now copy the mailer.py and mailer.conf  under /apps/subversion/hsolite/hooks and  /apps/subversion/hsolite/ respectively.

[root@domU-12-31-39-09-29-13 hsolite]#  cp /usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/mailer.py   /apps/subversion/hsolite/hooks/mailer.py

[root@domU-12-31-39-09-29-13 hsolite]# cp  /usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/tests/mailer.conf   /apps/subversion/hsolite//mailer.conf

Now edit the mailer.conf and override following properties

mail_command = /usr/sbin/sendmail
commit_subject_prefix = [svn-myproject]
from_addr = noreply@mydomain.com
to_addr = commits-myproject@mydomain.com  # this is a mailing list


Under hooks directory you will find "post-commit.tmpl" that you need to rename to "post-commit".

Replace "post-commit" script  contains with the following snippet.
------------------------------------------------
#!/bin/sh

REPOS="$1"
REV="$2"

/apps/subversion/hsolite/hooks/mailer.py commit "$REPOS" "$REV" /apps/subversion/hsolite/mailer.conf

-------------------------------------------------------

Make sure "post-commit" is executable.
[root@domU-12-31-39-09-29-13 hsolite]# chmod +x post-commit


Testing :
Using svnlook  yon can get latest revision number.

[root@domU-12-31-39-09-29-13 ~]# svnlook info /apps/subversion/hsolite/
sujankn
2013-08-16 07:41:29 -0400 (Fri, 16 Aug 2013)
0

[root@domU-12-31-39-09-29-13 ~]# svnlook youngest /apps/subversion/hsolite/
2850

Test the hook script:

[root@domU-12-31-39-09-29-13 ~]# REPOS=/apps/subversion/hsolite/
[root@domU-12-31-39-09-29-13 ~]#  REV=2850
[root@domU-12-31-39-09-29-13 ~]#  "$REPOS"/hooks/mailer.py commit "$REPOS" $REV "$REPOS"/mailer.conf 

After run above command you should receive email notification with revision number 2850

[root@domU-12-31-39-09-29-13 ~]# REPOS=/apps/subversion/hsolite/
[root@domU-12-31-39-09-29-13 ~]#  REV=2850
[root@domU-12-31-39-09-29-13 ~]#   sh $REPOS/hooks/post-commit  $REPOS$REV
If post-commit script run successfully then commit some files in SVN then check your email inbox for notification.

Monday, August 5, 2013

Weblogic JPA 2.0 configuration

If you find following exception in webloginc while running JPA 2.0 web application
Caused By: java.lang.NoSuchMethodError: javax.persistence.spi.PersistenceUnitInfo.getValidationMode()Ljavax/persistence/ValidationMode;

you need to add following line in commEnv.cmd( located at %BEA_HOME%\wlserver_10.3\common\bin\) just after  "set BEA_HOME=C:\Oracle\Middleware"


set PRE_CLASSPATH=%BEA_HOME%\modules\javax.persistence_1.1.0.0_2-0.jar;%BEA_HOME%\modules\com.oracle.jpa2support_1.0.0.0_2-1.jar

Then restart your server again.