Wednesday, 27 August 2014

ASP.NET MVC3 Vs MVC4 Vs MVC5

ASP.NET MVC 3

  • New Project Templates having support for HTML 5 and CSS 3.
  • Improved Model validation.
  • Razor View Engine introduced with a bundle of new features.
  • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
  • Controller improvements like ViewBag property and ActionResults Types etc.
  • Unobtrusive JavaScript approach.
  • Improved Dependency Injection with new IDependencyResolver.
  • Partial page output caching

ASP.NET MVC 4

  • ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients. Follow to create your first ASP.NET Web API service.
  • Adaptive rendering and other look-n-feel improvements to Default Project Templates.
  • A truly Empty Project Template.
  • Based on jQuery Mobile, new Mobile Project Template introduced.
  • Support for adding controller to other project folders also.
  • Task Support for Asynchronous Controllers.
  • Controlling Bundling and Minification through web.config.
  • Support for OAuth and OpenID logins using DotNetOpenAuth library.
  • Support for Windows Azure SDK 1.6 and new releases.

ASP.NET MVC 5

Creating your first ASP.NET MVC 5 Application in 4 simple steps
  • Bootstrap replaced the default MVC template.
  • ASP.NET Identity for authentication and identity management.
  • Authentication Filters for authenticating user by custom or third-party authentication provider.
  • With the help of Filter overrides, we can now override filters on a method or controller.
  • Attribute Routing is now integrated into MVC 5.

Passing data from Controller to View in ASP.NET MVC

ASP.NET MVC is a framework that facilitates building web applications based on MVC (Model-View-Controller) design pattern. Request coming from client reaches the Controller through URL Rewriting Module. Controller decides which model to use in order to fulfill the request. Further passing the Model data to View which then transforms the Model data and renders response to client as shown in following basic level request flow diagram.
ASP.NET MVC Request Flow
In this ASP.NET MVC Tutorial, we will discuss and implement different options to pass data from ASP.NET MVC Controller to View. Following are the available options to pass data from a Controller to View in ASP.NET MVC:
  • ViewBag
  • ViewData
  • TempData
If we want to maintain state between a Controller and corresponding View- ViewData and ViewBag are the available options but both of these options are limited to a single server call (meaning it’s value will be null if a redirect occurs). But if we need to maintain state from one Controller to another (redirect case), then TempData is the other available option.
It’s common that initially it might be a bit difficult for a ASP.NET WebForms developer to digest above flow and need for options to pass data from Controller to View. Because in WebForms approach, Controller and View are tightly coupled to each other.

ViewBag Example

As we discussed earlier that ViewBag and ViewData serves the same purpose but ViewBag is basically a dynamic property (a new C# 4.0 feature) having advantage that it doesn’t have typecasting and null checks.
So, In order to pass data from Controller to View using ViewBag, we will modify our EmployeeController code as follows:
 public class EmployeeController : Controller
 {
           // GET: /Employee/
          public ActionResult Index()
         {
                     ViewBag.EmployeeName = “Muhammad Hamza”;
                     ViewBag.Company = “Web Development Company”;
                     ViewBag.Address = “Dubai, United Arab Emirates”;                     
                     return View();
         }
  }
And to get Employee details passed from Controller using ViewBag, View code will be as follows:
  <body>
    <div>
          <h1>Employee (ViewBag Data Example)</h1>
          <div>
                       <b>Employee Name:</b> @ViewBag.EmployeeName<br />
                      <b>Company Name:</b> @ViewBag.Company<br />
                      <b>Address:</b> @ViewBag.Address<br />
          </div>
    </div>
  </body>
In order to see the above changes in action run the solution, we will find the following output.
ViewBag Example

ViewData Example

As compared to ViewBag, ViewData is a dictionary object which requires typecasting as well as null checks. Same above implementation using ViewData can be achieved as follows:
 public class EmployeeController : Controller
 {
           // GET: /Employee/
          public ActionResult Index()
         {
                     ViewData["EmployeeName"] = “Muhammad Hamza”;
                     ViewData["Company"] = “Web Development Company”;
                     ViewData["Address"] = “Dubai, United Arab Emirates”;                     
                     return View();
         }
  }
And to get Employee details passed from Controller using ViewBag, View code will be as follows:
  <body>
    <div>
          <h1>Employee (ViewBag Data Example)</h1>
          <div>
                       <b>Employee Name:</b> @ViewData["EmployeeName"]<br />
                      <b>Company Name:</b> @ViewData["Company"]<br />
                      <b>Address:</b> @ViewData["Address"]<br />
          </div>
    </div>
  </body>
Run the application to view the following output.
ViewData Example

Using TempData in ASP.NET MVC

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempdData can be used to maintain data between controller actions as well as redirects.
Note: Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors.
Let’s see how we can use TempData in a practical scenario to pass data from one controller action to another.
   //Controller Action 1 (TemporaryEmployee)
   public ActionResult TemporaryEmployee()
  {
                  Employee employee = new Employee
                  {
                          EmpID = “121″,
                          EmpFirstName = “Imran”,
                          EmpLastName = “Ghani”
                  };                   
                  TempData["Employee"] = employee;
                  return RedirectToAction(“PermanentEmployee”);
  }   
 
   //Controller Action 2(PermanentEmployee)
   public ActionResult PermanentEmployee()
  {
                 Employee employee = TempData["Employee"] as Employee;
                 return View(employee);
   }
As in above example, we store an employee object in TempData in Controller Action 1 (i.e. TemporaryEmployee) and retrieve it in another Controller Action 2 (i.e. PermanentEmployee). But If we try to do the same using ViewBag or ViewData, we will get null in Controller Action 2 because only TempData object maintains data between controller actions.
An important thing about TempData is that it stores contents in Session object. Then one may raise a question that  “What’s the difference between TempData in ASP.NET MVC and Session?” or “Why we have TempData dictionary object?, Why can’t we use the Session object directly?

ASP.NET MVC TempData Vs Sessions

Although ASP.NET MVC TempData stores it’s content in Session state but it gets destroyed earlier than a session object. TempData gets destroyed immediately after it’s used in subsequent HTTP request, so no explicit action required. If we use a Session object for this purpose, we would have to destroy the object explicitly.
It’s best fit for scenarios when:
  • we need to preserve data from current to subsequent request.
  • passing error message to an error page.

7 jQuery Code Snippets every web developer must Know

jQuery extensively simplified web developer’s life and has become a leader in javascript available libraries. There are a lot of useful jQuery snippets available but here in this post I am going to share 7 basic and widely used code snippets that every front-end web developer must have. Even for those who are new to jQuery can easily understand and get benefit from these routinely used code snippets.

1. Print Page Option
Providing option to print a page is a common task for web developers. Following is the available code:

<!– jQuery: Print Page –>
$(‘a.printPage’).click(function(){
           window.print();
           return false;
}); 

<!– HTML: Print Page –>

<div>
<a  class=”printPage” href=”#”>Print</a>
</div>
2. Helping Input Field/Swap Input Field
In order to make an Input Text field helpful, we normally display some default text inside it (For Example “Company Name”) and when user click on it, text disappears and user can enter the value for it.
You can try it yourself by using the following code snippet.

<!– jQuery: Helping Input Field –>
$(‘input[type=text]‘).focus(function(){    
           var $this = $(this);
           var title = $this.attr(‘title’);
           if($this.val() == title)
           {
               $this.val(”);
           }
}).blur(function() {
           var $this = $(this);
           var title = $this.attr(‘title’);
           if($this.val() == ”)
           {
               $this.val(title);
           }
});

<!– HTML: Swap Input Field –>

<div>
       <input type=”text” 
name=”searchCompanyName”
value=”Company Name” 
title=”Company Name” />
</div>


3. Select/Deselect All options

Selecting or Deselecting all available checkbox options using a link on HTML page is common task.

<!– jQuery: Select/Deselect All –>
$(‘.SelectAll’).live(‘click’, function(){ $(this).closest(‘.divAll’).find(‘input[type=checkbox]‘).attr(‘checked’, true); return false; }); $(‘.DeselectAll’).live(‘click’, function(){ $(this).closest(‘.divAll’).find(‘input[type=checkbox]‘).attr(‘checked’, false); return false; });

<!– HTML: Select/Deselect All –>

<div class=”divAll”> <a href=”#” class=”SelectAll”>Select All</a>&nbsp; <a href=”#” class=”DeselectAll”>Deselect All</a> <br /> <input type=”checkbox” id=”Lahore” /><label for=”Lahore”>Lahore</label> <input type=”checkbox” id=”Karachi” /><label for=”Karachi”>Karachi</label> <input type=”checkbox” id=”Islamabad” /><label for=”Islamabad”>Islamabad</label> </div>


4. Disabling Right Click

For web developers, its common to disable right click on certain pages so following code will do the job.
 
<!– jQuery: Disabling Right Click –>
$(document).bind(“contextmenu”,function(e){
       e.preventDefault();


   });
 
 
5. Identify which key is pressed.
Sometimes, we need to validate the input value on a textbox. For example, for “First Name” we might need to avoid numeric values. So, we need to identify which key is pressed and then perform the action accordingly.
<!– jQuery: Which key is Pressed. –>
$(‘#txtFirstName’).keypress(function(event){
     alert(event.keyCode);
  });
 
<!– HTML: Which key is Pressed. –>
<asp:TextBox ID=”txtFirstName” runat=”server”></asp:TextBox>
 
 
6. Validating an email.
Validating an email address is very common task on HTML form.
 
<!– jQuery: Validating an email. –>
$(‘#txtEmail’).blur(function(e) {
            var sEmail = $(‘#txtEmail’).val();
            if ($.trim(sEmail).length == 0) {
                alert(‘Please enter valid email address’);
                e.preventDefault();
            }        
            var filter = /^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]
                             {2,4}|[0-9]{1,3})(]?)$/;        
            if (filter.test(sEmail)) {
                alert(‘Valid Email’);
            }
            else {
                alert(‘Invalid Email’);
                e.preventDefault();
            }
        });
 
<!– HTML: Validating an email–>
<asp:TextBox id=”txtEmail” runat=”server” />
 
 
7. Limiting MaxLength for TextArea
Lastly, it usual to put a textarea on a form and validate maximum number of characters on it.
 
<!– jQuery: Limiting MaLength for TextArea –>
   var MaxLength = 500;
       $(‘#txtDescription’).keypress(function(e)
       {
          if ($(this).val().length >= MaxLength) {
          e.preventDefault();}
       });
 
<!– HTML: Limiting MaLength for TextArea–>
<asp:TextBox ID=”txtDescription” runat=”server” 
                         TextMode=”MultiLine” Columns=”50″ Rows=”5″></asp:TextBox>

Tuesday, 5 August 2014

Manual and Automated Testing

There are mainly two broad types of software testing – Manual Testing and Automated Testing.
Manual Testing
Manual Testing involves testing the software without any automation script or any tool. Testers check the application or software by taking up the role of an end user. They try to find out if there is any unexpected behavior or failure in the application. Test Management can be taken care of by using test plans and test cases.

Automation testing

Automation testing process involves testing with the help of automation scripts and executing the scripts to run the application with the help of some automation tool. Once the script is ready then these tests can run quickly and efficiently.
Since the cost of automated testing is in the form of efforts and time required to create the scripts, not all tests can be converted to automated test. There should be a valid reason to pay that cost.
Reasons for Automation
1. Regression testing to confirm that new changes have not affected the application adversely. It considers already existing test cases for execution. This is an efficient process when we need to provide feedback to the developer immediately.
2. The test cases need to be iterated multiple number of times often with varying datasets to cover multiple workflow paths.
3. When we require support for agile methodologies.
4. Customized reports are required for monitoring.

Getting Started with Automated Testing

Once the need for automated testing has been established, it involves creation of relevant test scripts. Test script creation can be done only by a skilled testers having knowledge of testing, the suite of tools as well functionality under development. Such resources are costly and their time is a premium. Considering this fact, it is often not possible to budget the automation of all tests. Some of the major decision points while identifying cases for testing automation are
1. System modules where requirements do not change frequently
2. Ample time is at hand to describe a test via scripts
3. The application/software module is critical enough to justify the upfront cost of automation
4. After functional testing we want to do performance testing with multiple virtual users using the same test script.
With the scope of automation decided, next step is to pick the testing tool. The following checklist can help with the selection.
1. The tool should be able to easy to work with. It should execute test cases in unattended manner. It should provide interface to write scripts, efficient IDE and ease of test execution.
2. The tool should provide support to various technologies. It should support testing using different browsers, languages, and types of applications.
3. It should integrate with a software that does Application Lifecycle Management so that it can be used for running automated Build Verification Tests as well as the reports can be integrated with other reports created by ALM software

Automated testing frameworks

There are three automated testing tools namely Selenium, QTP (Quality Test Professional) and Coded UI Test (CUIT) .We will consider above mentioned main aspects of automation and see how these tools provide the support for each category.
Ease of Use
- Recording and Playback Functionality
Each of the testing tools has the ability of recording the actions and playback the recorded actions. Selenium provides the plug-in named Selenium IDE with Mozilla Firefox with which the actions can be recorded. QTP provides record button to record a new test. Recording for
- IDE and tools with which the tester can write the scripts
With Selenium IDE there is no special tool and specific technology to write the script. We can insert commands with ‘Table or Source View’ when required.
QTP provides Keyword View to display test steps graphically or Expert View which shows VB Script lines.
Selenium IDE comes as a plug-in with Mozilla Firefox. With this we can create a test suite which comprise of various test cases. With Selenium IDE is, you can convert recorded Selenium IDE scripts into different languages and after conversion you can run it in Selenium RC. Selenium RC has two components, one is “Selenium Server” and another is “Selenium Client”.
With QTP IDE for the first time 3 add-ins are provided ActiveX, Visual Basic and Web. Various links to best practices, new features for the current version are available with start page. We can either open existing test case or create a new one.
- Ease of Test Case execution
With Selenium IDE we have the option of executing the entire test suite already recorded or a test case at a time.
Depending upon the add-ins loaded in QTP IDE the record and run window shows tabs. Windows Application tab is always available. The tests can be executed with run button which in turn opens the run dialog box. We can specify the location for run specific results and provide parameters if any.
These tools can execute test cases without human intervention.

Comparison Between Selenium and QTP

Platform Support
-Language Support
Selenium uses Selenese, a high-level, cross platform language to write Selenium commands which is a domain specific language. There are 3 basic categories for the commands – named actions, accessors and assertions. To write tests there are a lot of programming languages like C#, Java, Perl, PHP, Python or Ruby.
QTP scripts can be written with VBScript which is a high-level language with support to everything except polymorphism and inheritance.
- Support for various application types
Selenium supports only Web applications.
QTP supports almost any kind of applications.
Selenium scores fewer points in this regard as it supports only web application. QTP supports almost all kinds of applications

- Support for various browsers
Selenium supports all versions of IE, Firefox, Safari and Opera and a few more browsers.
QTP supports IE & Firefox. But both do not provide full cross browser support.
Selenium is the clear winner in this respect
- Support for Data Driven Testing
Selenium IDE supports xml data source using user extensions.
Data Driven testing is implemented as Excel workbook that can be accessed by QTP. There are 2 types of data sheet global and local. Global sheet is a single one which can be accessed from every action in a test. There can even be a local data sheet associated with every action.
- Exception Handling
Selenium IDE does not support error handling particularly unexpected errors (as it supports only HTML language). Selenium RC will provide support for it (it supports languages with .NET, Java, Perl, Python, PHP, Ruby).
QTP provides VBScript with the help of which we can use On Error statements.
- Validations or Assertions
Selenium assertions can be used in 3 modes assert, verify and waitFor. When an “assert” fails, the test is aborted. When a “verify” (Soft Assertions) fails, the test will continue execution, logging the failure. This facility can be used with TestNg framework. The “waitFor” commands wait for some condition to become true. They will succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the current timeout period.
For QTP there are checkpoints: to verify application under test. These are of 10 types – Standard, Table, Image, Bitmap, Database, Text, Text Area, Page, Accessibility, and XML. A checkpoint is a verification point that compares the current value with the expected value. If the current and expected value match it generates a PASS status otherwise FAIL status.
- Support for Objects
Object properties are not supported by Selenium. Selenium objects can be managed by using UI element user extensions. QTP comes with in-built object repository.
QTP objects have user friendly names.
Integration with Application Lifecycle Management and going beyond
- ALM Integration
Selenium being an Open Source software can be integrated with other Open Source products for Application Lifecycle Management like QMetry. This in turn can provide platform for software development lifecycle platform in the form of Atlassian Jira (project tracking tool), FogBugz or Bugzilla (bug tracking tool).
QTP being a part of Quality Centre it supports requirement traceability matrix. QTP integrates seamlessly with QC. Test management and mapping the manual testing process with automation becomes a lot easier with this integration
QC is still not complete life cycle management tool. It does not provide support for efforts management, build management or support to different process templates. It supports only test management, bug management and requirement management.
- Going beyond
Selenium being Open Source a lot of plugins available. Selenium IDE has plug-ins for customization, for adding new functionality to API, changing existing functionality.
QTP provided plug-ins for ActiveX controls, web application and VB objects. Other than these plug-ins for other objects like Microsoft .NET, multimedia plug-ins and Windows Mobile are also available. These QTP plugins available at an additional cost.
Each of the tools keeps on adding features as per need. Selenium being open source there are a lot of plug-ins.

Selenium WebDriver Training

What is Selenium Webdriver?

Webdriver is known to be the latest version of Selenium i.e. Selenium 2.x. More powerful than the primitive Selenium rc 1.x and comes with lots and lots of libraries and new features to work with. It’s not mandatory to know Selenium RC to work with Webdriver. You can directly learn webdriver and start working on it. There is no need of selenium server if you are working with Webdriver API

What makes it different from Selenium RC?

  • More object oriented as compare to Selenium RC.
  • Has wider range of APIs
  • Interacts natively with browser where as Selenium RC is Javascript based.
  • Can test Iphone and Andriod based application which is not supported by Selenium RC.
  • Implements HTMLUnit driver which makes test execution really fast.
  • Unlike Selenium RC there is no server in Webdriver.
  • Supports almost all lastest web browsers where as Selenium RC does not works on latest versions on Firefox and IE.

WebDriver Architecture

Selenium WebDriver architecture

Element Identification using Selenium WebDriver: Questions and Answers

1: What is the method used to launch URL using Selenium WebDriver?
Answer: In Firefox, we can set the homepage as the required URL as shown in the code below. This will launch the URL set in homepage on launching the driver.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference(“browser.startup.homepage”,“http://www.google.com”);
//We will provide the profile used as argument for Firefox Driver.
WebDriver driver = new FirefoxDriver(profile);
In case, we do not want to use profile, we can use the get method to launch the URL.
WebDriver driver = new FirefoxDriver();
driver.get(“https://www.google.com”);
2: What is the difference between findElement and findelements method in Selenium?
Answer: To locate an element in the page, we use findElement method whereas findElements gives the collection of web elements in the Page.
Syntax for findElement is:
WebElement tableinfo = driver.findElement(By.className(“tableClsName”));
This will give the first element in the page with className as “tableClsName”. Now once the element is recognized, we can perform action on the WebElement. Suppose the element is a button, we can click on the button as shown below:
Tableinfo.click();
Suppose the WebElement is an input box, we can insert data in the input box as shown below:
Tableinfo.SendKeys(“This is a test”);
Syntax for findElements is:
List<WebElement> tabledata = tableinfo.findElements(By.tagName(“td”));
This will give collection of all elements in the page with className as “td”.
We can further work on the collection of the object and extract the required information or perform actions on the required webElement as shown below:
List<WebElement> tabledata = tableinfo.findElements(By.tagName(“td”));
for (int iCnt = 0;i<tabledata.size();iCnt++)
 {
String strData = tabledata.get(iCnt).getText() ;
If(strData.contentEquals(“this is the row”))
{
System.out.println(“Web Element Found”)
iCnt = tabledata.size()-1;
}
}
3: What are the value ways to identify an object in Selenium WebDriver?
Answer: Below are the various locators by which elements can be identified in Selenium WebDriver:
1. Id:  Identifies WebElement by the ‘Id’ attribute.
2. ClassName: Identifies webelement by the ‘class’ attribute.
3. cssSelector: identifies element based on the css of the webElement.
4. linkText: Identifies element by the actual text of the link. Text should match exactly with the link text.
5. Name: Identifies webelement by the ‘name’ attribute.
6. partiallinkText: Identifies element by the actual text of the link. The link is identified on partial match of text.
7. tagName: Identifies an object by the tagName of the webElement.
8. xpath: Identifies an object by the xpath of the object.

Selenium WebDriver – Interview Questions

1: What is Selenium Web Driver?
Answer:  Selenium Web driver uses accessibility API to drive the browser and recognizes the object in web-based application. It allows writing automated tests replicating the behavior of real user, e.g. Clicking on a link or feeding data in an edit box. Using Selenium Web Driver together with any programming language and other testing framework like TestNG and JUnit, automation test framework to execute tests on different browsers can be created. We can use the robust features of the programming language to interact with other components of application like database interaction, files interaction to create a robust and reliable framework.
 2: What are the various browsers supported by Selenium WebDriver?
Answer: WebDriver available for automation in different browsers are ChromeDriver, InternetExplorerDriver, FirefoxDriver, OperaDriver and HtmlUnitDriver.
 3: What are the programming languages supported by WebDriver?
Answer: Python, Ruby, C#, Java, Perl, php and javascript are supported.
 4: What are the necessary steps required, before I start creating selenium tests on java using eclipse?
Answer: We require following configuration to be set up before creating test in eclipse:
  1.  Java needs to be installed in the machine.
  2.  Eclipse IDE needs to be installed.
  3.  Selenium Libraries for WebDriver should be available.
 5: Do we need to install some additional executable files working with Selenium WebDriver?
Answer: For Firefox driver, we do not require any additional executable as it is bundled with Java client bindings, For IE driver, Chrome driver, and Opera driver, we require additional executable that can be downloadable from Selenium Official website.
An example of how to create an instance of Internet Explorer Web Driver is shown in below example.
6: Is there any specific pre-condition before executing a selenium script on Internet Explorer?
Answer: Yes, Protected Mode settings should be same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones.
 7: What are Firefox profile preferences?
Answer: Using Firefox Profile, we can set the preferences for the Firefox in the profile.
The steps to define profile in Selenium are:
1.  Create an object of firefox profile
FirefoxProfile profile = new FirefoxProfile();
2.   Set the required preference of the firefox :
profile.setPreference(“browser.startup.homepage”,”http://www.google.com”)
3.  Create the driver object with profile as defined above.
WebDriver driver = new FirefoxDriver(profile);
8: What is the use of using TestNG with selenium in Java?
Answer: TestNG is a unit testing framework used for java programming language. Test Cases using Selenium Webdriver to identify webelement in the web application can be integrated/created on TestNG framework. Some of the useful features TestNG provides are as follows:
1.  Using Annotation to describe order of test cases, defining start conditions and end condition using  @after and @before annotations.

Selenium IDE: Interview Questions with Answers

1:  Explain the various features provided by Selenium IDE?
Answer: The layout of Selenium IDE is divided into following four areas:
1. MenuBar – Following are the menu options available in Selenium IDE:
 a.   File – Allows creating new test case, test suite, open existing test case, test suite, exporting tests to other formats.
 b.   Edit – Allows editing existing test steps, and adding new commands and comments.
 c.   Actions – Allows to record, play a test, execute command, toggle breakpoint and set entry point.
 d.  Options – Allows the changing of settings including set the timeout value for commands and specifying the format used for saving test cases.
 e.  Help – provides documentation for selenium IDE.
   2.  Toolbar – Provides buttons to manage test execution including test execution and test execution.
   3.  Test Case Pane – Test Case Pane shows the list of test case on the left and test steps in table or
source pane on the right. We can add/modify commands, target and value in the table for the test.
    4.  Log/Reference/UI-Element/Rollup Pane – This pane helps us to view logs of execution, reference explaining the selected command. We can also set to filter logs for info, warning, error and debug in this window.
 2: Explain what are the various items available from file menu
Answer: From the File Menu, We can perform various tasks
a.  Create New Test Case.
b.   Create new Test Suite.
c.   Save test cases and test suites.
  1.    Export Test cases/test suites to various formats. E.g : Ruby/Python/java/c# with WebDriver or RC.
  2.   Open existing test cases and test suites.
d.   Rename a test case.
3: Can the script prepared in Selenium IDE be used with webdriver/Remote control?
Answer: Yes, the script created in Selenium IDE can be exported to WebDriver/Remote Control in the languages java/c#/python/ruby that can be run using junit(java), RSpec(ruby), nUnit.
4: My Application is running slowly, can I change the default timeout value of recorder command?
Answer: We can reset the default timeout value for recorded command from Options Menu. By default the timeout is set as 30000 ms. In options, we can also define the recording settings and order of locator preference for object identification.
 5: What is the short cut key to create a new test in Selenium IDE?
Answer: The shortcut key to create a new test in Selenium IDE is Ctrl + N.
Some other useful shortcut keys in Selenium are:
Open a test – Ctrl + O :  Save a test – Ctrl + S  : Add test to test suite : Ctrl + D.
 6: What is the use of Select and find button in target in Selenium IDE?
Answer: On clicking on select, we can add the locator of an element in the page. Click on Select and click on an element in the page, the locator for the element will be added in the target. Find helps us to verify object exists in the page and highlights the object in the page if exists, else error is displayed in the log.

How to Configure Eclipse to work with Selenium

Before starting working with Selenium using Eclipse IDE, we did some configuration that needs to be done for starting and understanding Selenium. This post will explain step wise, how to start working with selenium using Eclipse:

Pre- Conditions: We will require following before beginning the configuration:

1. Java needs to be installed in the machine.
2. Eclipse IDE needs to be installed .
3. Standalone libraries of selenium, at the time of writing this post, I am using selenium-server-standalone-2.33.0.jar
4. Verify in Path variable in User defined variable for machine, is set to the path where standalone libraries is placed as shown below



Configuration Steps: 


Step 1: In eclipse, create a new java project as shown below from File>New Java Project

Create a new Java Project

Step 2: Once a java project is created, right click on project and select option “Build Path>Configure build path
Configure build path of project
Step 3: Click on Add External JAR’s and add the selenium standalone jar as shown below.
 Step 4: Now in src for the project, Add a new package, and add a new class as shown below.

Select methods stubs to create as public static void main(String[] args)

                                         
Step 5: Write the code in the class created above and execute. This will open Google in internet explorer . Write selenium in search and click on search.

Code to be placed in void main:

WebDriver ieDriver = new InternetExplorerDriver();
ieDriver.get(“http://www.google.com”);
WebElement element = ieDriver.findElement(By.name(“q”));
element.sendKeys(“selenium”);
element.submit();

Design Patterns in Selenium

Before creating tests in Selenium, we should look for design patterns to be followed in the test. Defining Design pattern to be used in automation helps in easier maintenance of the project once the number of tests increases. Design Pattern should be used in such a manner that rework due to of any code changes are minimum, creating new test uses the existing code.
Following are a few strategies or design patterns used in Selenium for making tests easier to create and maintain:
1.       Page Object Model
2.       Using Page Factory in Page object
3.       Loadable components
When we write code for tests in Selenium, we can break down the code in such a manner that code maintenance is better. Suppose we have two tests. One tests for an image visible on home Page post login and another verifies welcome text post logging in the application. Writing the same code in two different tests will require code to be changed in two different places in case object property changes in login Page and at times in case we have large number of tests in the test suite, it will take considerable time to fix the automation code. We should refactor the code and create smaller private methods that are used in different tests.
So now, we can make change at one place and it will be reflected in many tests by refactoring the tests.
In Page Object Model, we create individual classes for each of the pages with all the methods pertaining to the Page. These methods specific to a page covers both positive and negative scenarios specific to page.
Page Object Model reduces the duplication of code, improves readability and increases robustness of the test. Also the code is lot more maintainable, which is specifically useful in case properties of objects in the application changes frequently.
Page Factory uses the factory class from web driver’s support library to define objects in the page in a better and simpler manner. We declare some fields on a PageObject that are Web Elements or List<Web Element>.initialize the page objects.
We can use Loadable components in the Page design providing a standard way of ensuring that pages are loaded successfully.
Together with this, we can use best practices to ensure the quality of code is highly robust, reusable and maintainable.

Activities in Testing Process

Testing Process includes following activities that should be followed sincerely for proper testing.
1. Test Planning
 Before beginning with testing, we need to define test plan based on which we perform testing for the rest of testing life cycle. We should develop a test plan based on following key points to be considered in testing life cycle.
  • Test Objectives should be measurable, prioritized, and should be signed off between stakeholders before moving forward with test planning. Acceptance Criteria should also be defined during objective settings to validate if the test objective has been accompanied.
  • Test Matrix should be defined on how to test the test objectives and to validate all the requirements are covered in testing.
  • Test Schedule should be defined, how milestones in testing will be covered and timeframe in which milestones will be delivered
  • Budgeting and resources planing should be defined.
  • Testing material including environment ans software/availability should be defined.
  • Training required for testing should be defined.
 2. Test Control Activities
Once Test plan is created and signed off by stakeholder, Activities in test plan should be compared with actual and any deviation from the projected plan should be reported to stakeholders as risk.

3. Test Analysis
In this phase, test objectives defined in test planning are converted into test scenarios and test cases.Below are the main task in this phase:
  • Reviewing the test artifacts like business requirements, design, and test objectives.
  • Identifying and prioritizing test scenarios and test cases based on business requirements.
  • Identification of test data for execution of test conditions
  • Test environment availability
 4. Test implementation
Below are activities in test implementation
  • Developing and prioritizing test cases with test steps
  • Preparation of test data for execution of test scripts.
  • Environment set up for testing.
  • Development of automation test harness.
  • Preparation of test suites for regression, smoke testing, and execution of similar tests in batch.
 5. Test Execution and Reporting
  • Execution of test scripts either manual or automated.
  • Reporting defects found during test script execution.
  • Regression testing and retesting of fixed defects. 
  • Reporting of test execution status to stakeholders.
 6.  Exit criteria
  • Evaluating Testing status against the exit criteria specified in test planning.
  • Test Status should validate that all acceptance criteria are verified.
 7. Test Closure Activities
  • Delivering all the planned test artifacts to the client. For e.g : Automated Test Scripts,test scripts, test data for further reuse.
  • Handover of artifacts and knowledge transfer to maintenance team
  • Analysis of lesson learnt during testing process.

Selenium Remote Control

Selenium Remote Control (RC)

 Overview

  • While Selenium IDE may seem a productive and efficient tool for writing test-cases, it lacks many essential features of a testing tool:
    • Conditional statements
    • Loops
    • Logging
    • Exception handling
    • Reporting
    • Test fixtures and data-driven tests
    • Test dependencies
    • Taking screenshots
  • Selenium RC is the answer to a more powerful test-suite for your applications.
  • It follows a client/server model allowing client libraries to execute tests on a browser controlled by the server.
images/selenium_rc_overview.png

Selenium Server

  • Selenium server is the program that drives the browser
  • It embeds Selenium Core framework and injects it into the browser
  • It communicates with the running test client and drives the browser
  • Client tests sends commands that the server interpretes in order to drive the browser
  • The server sends back results to the client
  • Client and server communicates via HTTP GETs and POSTs so you can easily plug into
  • Server is configurable at startup via command-line options. use java -jar selenium-server.jar -h to see the list of options

Client libraries

  • Client libraries provides the API to program tests and execute them on the server
  • Each implementation provides access to all Selenium commands
  • Supported API implementation exists in:
    • Java (also accessible via Groovy)
    • .Net
    • PHP
    • Python
    • Perl
    • Ruby

Locators In Selenium

Locators
Selenium uses what is called locators to find and match the elements of your page that it needs to interact with. There are 8 locators strategies included in Selenium:
  • Identifier
  • Id
  • Name
  • Link
  • DOM
  • XPath
  • CSS
  • UI-element
 Identifier
Works with the ID and name attributes of your html tags. Let’s consider the following example:
<html>
<body>
<form id=”login”>
<input name=”username” type=”text”/>
<input name=”password” type=”password”/>
<input name=”submit” type=”submit” value=”Continue!”/>
</form>
</body>
</html>
Valid locators for this snippet are :
  • identifier=login
  • identifier=username
  • submit
Id
The Id strategy looks for an element in the page having an id attribute corresponding to the specified pattern. <label id=”my_id” /> will be matched by a locator like id=my_id or just my_id
 Name
Like the Id strategy, but on the name attribute. You can also specify a filter to refine your locator. Currently, there are two filter types :
  • Value : matches elements with a name attribute and where the value follows a pattern. The following example illustrates the interest of filters :
  • <html>
  •  <body>
  •    <div id=”pancakes”>
  •      <button type=”button” name=”pancake” value=”Blueberry”>Blueberry</button>
  •      <button type=”button” name=”pancake” value=”Banana”>Banana</button>
  •      <button type=”button” name=”pancake” value=”Strawberry”>Strawberry</button>
  •    </div>
  •  </body>
</html>
Link
This strategy is intended to select links only and selects the anchor element containing the specified text: link=The text of the link
DOM
The DOM strategy works by locating elements that matches the javascript expression refering to an element in the DOM of the page.
  • dom=document.div['pancakes'].button[0]
  • document.div[0].button[2]
  • dom=function foo() { return document.getElementById(“pancakes”); }; foo();
XPath
While DOM is the recognized standard for navigation through an HTML element tree, XPath is the standard navigation tool for XML; and an HTML document is also an XML document (xHTML). XPath is used everywhere where there is XML. Valid XPath locators can be:
  • xpath=//button[@value="Blueberry"]: matches the Blueberry button
  • //div[@id="pancakes"]/button[0]: same thing
CSS
The CSS locator strategy uses CSS selectors to find the elements in the page. Selenium supports CSS 1 through 3 selectors syntax excepted CSS3 namespaces

Commands In Selenium

Commands

The Selenium API defines dozens of commands that can be categorized into the following:
  • Actions
  • Accessors
  • Assertions

 Actions

  • Actions are commands that change the state of the application like clicking links or buttons, select an option in a <select> or type a character sequence in a given textbox.
  • Actions are available in different flavors. For instance, click(locator) will trigger a click on an element locator but you can also find:
    • clickAndWait(locator) command which will trigger a click and stop the test until the browser has finished loading a new page.
    • clickAt(locator, offset) command that also triggers a click but takes another argument: a X and Y tuple that offset the actual clicking location by X and Y pixels.
    • A combination of the above : clickAtAndWait(locator,offset) that combines the specification of an offset for the click location and waits for a new page to load.
    test with actions
    ?
    type id=search Donuts near my home
    ?
    • type modifies the state of the application (it modifies a test field) and so is considered as an action

    Accessors

    • Accessors inspect the state of the application and store values in variables.
    • For instance, storeCookies(variableName) stores all the cookies in use in the current page in the variable variableName.
    • To use stored variables, the syntax is ${variablename} (or storedVars['variableName'] if in a JavaScript context):
      Test with variables
      store my_search_string searchString
      ?
      type id=search ${searchString}
      ?
      and if in a JavaScript code section:
      if (storedVars['variableName'] == '') {
        ...
      }

     Assertions

    • Assertions are also able to inspect the current page but:
      • They are made to return a boolean value
      • This boolean represents the conformity of the element to a desired pattern
      • Usually, the pattern represents the state of an element.
    • Assertions come into 3 flavors:
      • assert : if assertion fails, test is aborted and marked as failed : assertTitle(pattern) will fail if the title of the page doesnot correspond to the pattern argument.
      • verify : if a verification fails, the test doesnot stop but a trace will be printed in the log.
      • waitFor : these commands pause the test until a condition is satisfied or a timeout is reached.