Monday 7 October 2013

Maveen Central Repository & Download from Reposotoriy

When you build a Maven’s project, Maven will check your pom.xml file, to identify which dependency to download. First, Maven will get the dependency from your local repository Maven local repository, if not found, then get it from the default Maven central repositoryhttp://repo1.maven.org/maven2/
This is how the Maven central repository website looks like


According to Apache Maven :
Downloading in Maven is triggered by a project declaring a dependency that is not present in the local repository (or for a SNAPSHOT, when the remote repository contains one that is newer). By default, Maven will download from the central repository.
In Maven, when you’re declared library does not exist either inlocal repository nor Maven center repository, the process will stop and output error messages to your Maven console.

1. Example

The org.jvnet.localizer is only available at Java.net repository.
pom.xml
    <dependency>
        <groupId>org.jvnet.localizer</groupId>
        <artifactId>localizer</artifactId>
        <version>1.8</version>
    </dependency>
When you build this Maven project, it will fail and output dependency not found error message.
Updated 12/12/2012
The
org.jvnet.localizer is now available in Maven center repository.

2. Declare Java.net repository

To tell Maven to get the dependency from Java.net, you need to declared a remote repository in your pom.xml file like this :
pom.xml
    <repositories>
        <repository>
            <id>java.net</id>
            <url>https://maven.java.net/content/repositories/public/</url>
        </repository>
    </repositories>
Now, Maven’s dependency library look-up sequences is changed to :
  1. Search in Maven local repository, if not found, go step 2, else exit.
  2. Search in Maven central repository, if not found, go step 3, else exit.
  3. Search in java.net Maven remote repository, if not found, prompt error message, else exit.
Maven’s dependency mechanism help to download all the necessary dependency libraries automatically, and maintain the version upgrade as well.



Changing the Maven Local Repository




The maven local repository is a local folder that is used to store all your project’s dependencies (plugin jars and other files which are downloaded by Maven). In simple, when you build a Maven project, all dependency files will be stored in your Maven local repository.
By default, Maven local repository is default to .m2 folder :
  1. Unix/Mac OS X – ~/.m2
  2. Windows – C:\Documents and Settings\{your-username}\.m2

1. Update Maven Local Repository

Normally, I will change the default local repository folder from default .m2 to another more meaningful name, for example, maven-repo.
Find {M2_HOME}\conf\setting.xml, update localRepository to something else.
{M2_HOME}\conf\setting.xml

<settings>
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
 
<localRepository>D:/maven_repo</localRepository>

2. Saved it

Done, your new Maven local repository is now changed to D:/maven_repo.

2. Saved it

Done, your new Maven local repository is now changed to D:/maven_repo.

Four simple reasons why Automation projects fail

Automated testing tools were supposed to make things easier. Getting them to execute pre-scripted tests — instead of relying on QA pros to carry out tests by hand — saves time and money. Moving to automated testing is a no-brainer, right?
In theory, the case for automated testing tools makes sense. And yet, in years of writing about software testing, I haven’t heard a single test manager say that automation saves time and money and boosts software quality.
What I hear over and over again are variants on the same theme: Test automation projects are far more challenging than they initially appear. They require scripting skills, which some testers lack. And while the initial stage of setting up tools and writing test scripts is the most demanding phase of an automation project, the most successful projects never really go on autopilot. They are never done.
Don’t get me wrong, I am not building a case against automated testing. Nor am I saying that automation doesn’t make sense for the long run. Virtually all QA pros I talk to believe it does, and they also say there is a certain inevitability about making the move to automation. Certain tests are better left to computers rather than to human testers.
In this installment of Quality Time, I discuss four reasons why automated testing projects are challenging. Understanding these challenges can help QA managers avoid some common pitfalls, accurately assess their readiness for automated testing and set more realistic expectations for upcoming projects.

Reason 1: Test automation projects are software development projects.
 Failure to fully grasp this notion is a recipe for disaster. You can’t set up automated testing tools without team members who can write code. As Lisa Crispin, a resident SearchSoftwareQuality expert, explained in her tip on devising a test automation strategy, “automating tests is software development. It must be done with the same care and thought that goes into writing production code.”
This poses a significant hurdle for testers who lack coding skills. That challenge is best met by mastering those skills, not by shying away from projects that demand them. “Learn how to script tests — learn a scripting language like Ruby,” Coveros CEO Jeff Payne said, addressing an audience of software testers at STAREAST 2013 earlier this year. Companies are looking for testers who can automate, and those without coding skills will ultimately be left behind, he said.

Reason 2: You can’t succeed at automated testing until you succeed at manual testing.
The success of any test project, manual or automated, ultimately hinges on testing the set of things most likely to deliver the highest-quality software to the user. If you don’t know what to test, you are not ready to automate the testing process, according to expert Mike Kelly, in our story, When to use manual vs. automated software testing tools: “I see a lot of teams focus on automation, as a cost-lowering technique, when what they really need to focus on first is testing the right things.”
Kelly’s commonsense rule reminds me of a rule art students are often asked to follow in painting 101: No abstract paintings until you prove your ability to paint realistically. In other words, don’t tackle the variation on the theme until you have mastered the theme itself.

Reason 3: Test automation does not mean testing with automation added.
A key misconception about test automation is that it’s easy, said test expert Hans Buwalda, addressing an audience of software testers in the “Lightning Strikes the Keynotes” session at STAREAST 2013. “But I am still waiting for my easy project,” said Buwalda, chief technology officer for software testing service firm LogiGear in San Mateo, Calif. He believes automated testing is harder than manual testing. You can’t simply add automated tests to an existing test process. Instead, you have to rethink your entire approach. Which tests are best automated? Which ones should remain manual? Answering those questions requires creative thinking, he said. “Don’t lose your creativity [when you move to automated testing],” he told the audience.

Reason 4: Avoid automated testing autopilot.

When teams successfully complete the initial stage of setting up automated testing, there is a tendency to keep on running the same tests over and over again. Test expert Robert Galen of RGalen Consulting Group in North Carolina, said this is a big mistake. Running more tests faster does not result in higher-quality software. Better software is the result of running the right tests and continually re-evaluating which tests are the right ones, Galen explained in our story, Test automation ROI commoditizes testers, hurts test organizations.
In other words, the most successful automated testing projects are never complete. You keep on asking which tests will help produce the best software, and then script them accordingly. This approach helps ensure success with automated testing tools. But when you start running the same old tests in autopilot mode, trouble lies ahead.



Code to Restart and Shutdown the System in QTP

strComputer = "dscp xxxxx“         ' Mention machine name / IP address
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\" & strComputer & "\root\cimv2")

Set colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOperatingSystem In colOperatingSystems
    objOperatingSystem.Reboot()
//objOperatingSystem.Win32Shutdown(1)    ‘ “1” is for Shut Down -->for shudowning

Next

Code To Know Complete System Information In QTP

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
                        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
           
Set colSettings = objWMIService.ExecQuery _
                        ("Select * from Win32_OperatingSystem")
           
For Each objOperatingSystem in colSettings
            Msgbox "OS Name: " & objOperatingSystem.Name
            Msgbox "Version: " & objOperatingSystem.Version
            Msgbox "Service Pack: " & _
                                    objOperatingSystem.ServicePackMajorVersion _
                                                & "." & objOperatingSystem.ServicePackMinorVersion
            Msgbox "OS Manufacturer: " & objOperatingSystem.Manufacturer
            Msgbox "Windows Directory: " & _
                                    objOperatingSystem.WindowsDirectory
            Msgbox "Locale: " & objOperatingSystem.Locale
            Msgbox "Available Physical Memory: " & _
                                    objOperatingSystem.FreePhysicalMemory
            Msgbox "Total Virtual Memory: " & _
                                    objOperatingSystem.TotalVirtualMemorySize
            Msgbox "Available Virtual Memory: " & _
                                    objOperatingSystem.FreeVirtualMemory
            Msgbox "Size stored in paging files: " & _
                                    objOperatingSystem.SizeStoredInPagingFiles
Next
           
Set colSettings = objWMIService.ExecQuery _
                        ("Select * from Win32_ComputerSystem")
           
For Each objComputer in colSettings
            Msgbox "System Name: " & objComputer.Name
            Msgbox "System Manufacturer: " & objComputer.Manufacturer
            Msgbox "System Model: " & objComputer.Model
            Msgbox "Time Zone: " & objComputer.CurrentTimeZone
            Msgbox "Total Physical Memory: " & _
                                    objComputer.TotalPhysicalMemory
Next
           
Set colSettings = objWMIService.ExecQuery _
                        ("Select * from Win32_Processor")
           


For Each objProcessor in colSettings
            Msgbox "System Type: " & objProcessor.Architecture
            Msgbox "Processor: " & objProcessor.Description
Next
           
Set colSettings = objWMIService.ExecQuery _
                        ("Select * from Win32_BIOS")
           
For Each objBIOS in colSettings
            Msgbox "BIOS Version: " & objBIOS.Version
Next






Friday 20 September 2013

Difference b/w Set,List and Map

Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method
Set s = new HashSet();
Iterator iter = s.iterator();

List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method
List li = new ArrayList();
Iterator iter = li.iterator();

Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys
  • In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()


    Map m; // insert values
    Set s = m.keySet();
    // Get Map keys into the Set and then iterate this Set object normally
    // m.keySet() returns Set object with Map keys
    Iterator iter = s.iterator();

Collections Interview Questions


Q1) What is difference between ArrayList and vector?
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Q2) How can Arraylist be synchronized without using Vector?
Ans)
 Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Ans)
 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
Q4)What is difference between HashMap and HashTable?
Ans) 
Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.Fail-safe - â€Å“if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationExceptionâ€?
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
Q5) What are the classes implementing List interface?
Ans)
There are three classes that implement List interface:
1)
ArrayList : It is a resizxable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2)
Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3)
LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.
Q6) Which all classes implement Set interface?
Ans)
 A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
Q7) What is difference between List and a Set?
Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?
Ans)
 Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :
    1. int [] intArray= new int[6];
    2. intArray[7]   // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
  1. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
  1. ArrayList is one dimensional but array can be multidimensional.
            int[][][] intArray= new int[3][2][1];   // 3 dimensional array    
  1. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
Q9) When to use ArrayList or LinkedList ?
Ans)
  Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.
Source : Read More - from java.sun
Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
Ans) 
It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.
Q11) Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
Ans)
 For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.
Q12) Is it better to have a HashMap with large number of records or n number of small hashMaps?
Ans) It depends on the different scenario one is working on:
1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.
Q13) Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new ArrayList<String>();
Ans)
 It is preferred because:
  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible
Q14) What is difference between iterator access and index access?
Ans) Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the 'n' location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.
Q15) How to sort list in reverse order?
Ans) 
To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)
Q16) Can a null element added to a Treeset or HashSet?
Ans) 
A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.
Q17) How to sort list of strings - case insensitive?
Ans)
 using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Q18) How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) 
A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.
Q19) What is ConcurrentHashMap?
Ans) 
A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.
Q20) Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
Q21) Which data structure HashSet implements
Ans)
 HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.
Q22) Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
Q23) What is identityHashMap?
Ans)
 The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
Q24) What is WeakHashMap?
Ans)
 A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.





























Thursday 19 September 2013

Selenium WebDriver Interface

The interface WebDriver represents the main interface for testing a web browser instance. If you are using Selenium 2 then it is highly recommended to use the WebDriver instance because of the benefits suggested in my previous posts.
This interface provides most of the basic requirements for testing a web application. Normally the testing of a web application requires either one or all of the following three functions:

  • Controling The browser
  • Selecting the WebElement
  • Debugging aids
The methods in this class provide solutions to the requirements in all the three categories mentioned above:
· Control of the browser:
    • get(): Loads the web page rendered by the URL string passed to this method. Similar results can be obtained by using WebDriver.Navigation.to(String)
    • navigate():Loads the web page rendered by the URL and access browser history
    • close(): Closes the ‘Current’ browser window
    • quite(): Closes ‘All’ browser windows associated with the webDriver instance
    • switchTo(): Changes current window and redirects all commands to the new ‘current’ window (example: switchTo().window(String))
    • manage(): Enables access to browser menu items, such as add cookies, logs etc 
        
· Selection of WebElement:
    • findElement(): Returns the first ‘Webelement’ found
    • findElements(): Returns all the ‘WebElements’ found in the current web page
· Debugging aids:
    • getCurrentUrl(): Returns the current URL loaded in the browser session
    • getPageSource(): Returns HTML source of the current page loaded in the browser
    • getTitle(): Returns the title of current page
    • getWindowHandle(): Return unique string identifier of the current window in the driver instance
    • getWindowHandles(): Return identifiers of all the windows in the driver instance

Comparative analysis of the WebDrivers’ Drivers

While working with selenium webdriver you have an option to choose from multiple webdrivers, such as HtmlUnitDriver, FirefoxDriver, InternetExplorerDriver, ChromeDriver and OperaDriver. Each one of them is a separate implementation of the WebDriver interface provided by Selenium. All of them have unique advantages and disadvantages because of the implementation differences for catering to different requirements. It is good to know the comparative advantages and disadvantages of each one before picking one of them.
The first major point to note is that there are two groups of driver implementations. One of those that invoke the actual browser installed on your system and the other that emulates the behavior of another browser. FirefoxDriver, InternetExplorerDriver, ChromeDriver and OperaDriver invoke the actual browser installed on the machine; however the HtmlUnitDriver emulates other browsers JS behavior. 

HtmlUnitDriver

 HtmlUnit is a java based framework for testing webApps basically a wrapper around ‘HttpClient’ by Jakarta. HtmlUnit provides UI-Less emulation of browsers to test web applications. The HtmlUnit APIs let you do the typical functions performed in an actual web browser, such as click links, fill forms, invoke web pages, submit values etc. HtmlUnit supports java script and complex AJAX libraries. Javascript is disabled in the HtmlUnitDriver by default, however if it can be enabled if required. The mechanism to enable javascript with the HtmlUnitDriver is as follows:

HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver();
 MyhtmlDriver.setJavascriptEnabled(true);
OR
HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver(true);

When enabled, the HtmlUnitDriver emulates the java script behavior of Internet Explorer by default. However we can direct the HtmlUnitDriver to emulate the JavaScript behavior of the browser of our choice by invoking the constructor that accepts the browser version. This can be done as follows:
HtmlUnitDriver MyhtmlDriver = new HtmlUnitDriver(BrowserVersion.Firefox_2);

Internet Explorer Driver

 The IE driver class ‘InternetExplorerDriver.class’ is located at ‘\org\openqa\selenium\ie\’ directory in the ‘selenium-server-standalone-2.7.0.jar’. To use the InternetExplorerDriver all you need to do is to have the selenium-server-standalone-2.7.0.jar in your CLASSPATH.  The IE driver runs only on windows and supports both 32-bit and 64-bit operations. Depending on the thread that instantiates the InternetExplorerDriver corresponding version of the IE is launched i.e. if the thread instantiating driver is running in 32-bit then the 32-bit version of the IE will be launched and if the thread instantiating driver is running in 64-bit then the 64-bit version of the IE will be launched.

The Internet Explorer driver uses the native or OS-level events to perform various functions on the browser, such as inputs from keyboard and mouse. This approach has both advantages and limitations both. The advantages are that it bypasses the limitations of the Javascript sandbox but there can be issues like the browser window under test might be out of focus.

Firefox Driver

selenium-server-standalone-X.X.X.jar’ contains all the drivers implementing the WebDriver interface of selenium. Hence the 'FirefoxDriver.class' can be found in the ‘\org\openqa\selenium\firefox directory in the selenium-server-standalone-X.X.X.jar. The driver when instantiated is added as an extension to the firefox profile. You can specify the profile with which you want to load firefox session. If no profile is specified then the driver creates an anonymous profile by default.
A profile can be created for the firefox driver as follows:

FirefoxProfile myProfile = new FirefoxProfile();

Multiple operations can be performed on the newly created profile, such as:

myProfile.addExtension(File);
myProfile.clean();
myProfile.getPort();
myProfile.setPort(int port);
myProfile.enableNativeEvents();
myProfile.setPreference(String key, String value); etc...

After creating the your profile you can pass the profile while creating the driver instance as follows:
WebDriver myFireFoxDriver = new FirefoxDriver(myProfile);

This driver is faster than the InternetExplorerDriver and executes the test in real Firefox web browser.

Wednesday 4 September 2013

SeleniumQuestions..


  1. Which of these WebDriver interface methods is used to open a URL in the browser?
    A)get
    b)navigate().to
    c)Any of the above
    d)None of the above
    ans c
  2. What is the difference between WebDriver close and quit methods?
    a)Nothing, these methods are interchangeable.
    b)close method clears the browser memory and the quit method closes the browser window.
    c)close method closes the browser but the quit method additionally removes the connection to the server.
    d)close method closes the main browser window but the quit method closes all the browser windows including popups.
    Ans :d


  1. When invoked on a web element, what does the submit method do?
a)It is used to submit a form and it works on any web element.
b)It is used to submit a form but it works only on the web element whose type is "submit".
c)It is the same as the click method.
d)There is no submit method for a web element.
Ans:a
4. Which WebDriver method is used to change focus to an alert, a web element or a browser window?
a)changeFocus
b)switchTo
c)goTo
d)setFocus
Ans:b
5 . What functionality does WebDriver support on browser cookies?
a)add and delete an individual cookie
b)delete all cookies
c)any of the above
d)none of the above
ans:c
6. What is the scope of an implicit wait?
a)All instances of WebDriver
b)Current WebDriver instance
c)Current expected condition
d)Current web element
ans:b
7. What kind of application is the Selenium IDE?
a)Windows application
b)Web application
c)Firefox add-on
d)None of these
ans:c

8. A Selenium IDE test case has three columns, Command, Target and Value. What data is stored in the Target column?
a)Element or location where the command is executed
b)Test step execution result
c)[Optional] purpose of the test step
d)None of these
ans: a
9. By default, in which format does the Selenium IDE save a test case?
a)In proprietary format
b)As HTML
c)As Java source code
d)As Ruby or Python or C# code depending on user options selected during installation
ans:b
9. What features are available in Selenium IDE to debug an automated test case?
a)Toggle Breakpoint
b)Pause/ Resume
c)Step
d)All of these
ans:d
10. What is the Selenium print command?
a)echo
b)print
c)alert
d)System.out.println()
ans: a
11. What is the difference between a command and the same command with "AndWait" (e.g. click and clickAndWait commands)?
a)Selenium waits indefinitely for the result of the "AndWait" command.
b)It waits for the result of the "AndWait" command but only for 30 seconds (default timeout).
c)It waits for the result of the "AndWait" command but only up to a maximum of 30 seconds (default timeout).
d)Some commands do not have an "AndWait" command, so this question is incorrect.
Ans: c
12. What is the correct syntax to access the value of a Selenium variable called name?
a)name
b)$name
c){name}
d)${name}
ans:d
13. What is the difference between assert and verify commands?
a)Assert commands are more uncommon than verify commands.
b)Typically, an assert command is followed by verify command(s).
c)A failed assert command stops the test but a failed verify command does not do so.
d)All of the above
ans: d
14. In which associative array does Selenium store all of a test case's variables and their respective values?
a)Array
b)storedVars
c)var
d)There is no such array in Selenium.
Ans b

15. Where can you create your own Selenium commands?
a)This is not possible.
b)In user-extensions.js file
c)In any JavaScript file, but the preferred name is user-extensions.js for consistency
d)In any Java, C#, Python, Ruby, PHP or Perl file
ans:c
16. What URLs does the Selenium open command allow?
a)Only the base URL
b)Any URL relative to the base URL
c)Any absolute URL
d)Any of the above
ans: d
17. What is the purpose of the Find button?
a)Highlight the element that is given in the locator
b)Search the appropriate command for the given target
c)Find the current value of the target
d)None of the above
ans:a
18. Which one of the following statements is incorrect?
a)Breakpoint and Start point cannot both exist on the same command.
b)The shortcut key for Breakpoint is B and for Start point is S.
c)A Breakpoint or a Start point cannot be put on a comment line.
d)Both Breakpoint and Start point are used in debugging the test case.
Ans:c

19. Which add-on is commonly used with Selenium IDE to identify individual elements on a web page?
a)FirePath
b)Firebug
c)XPath
d)No add-on is required. You can view the Page Source and locate any element within the HTML code easily.
Ans b(Firebug is the required add-on. FirePath is only a Firebug extension that shows XPath.)

20. Why are relative XPaths preferred over absolute XPaths as locators?
a)For non-root elements, absolute XPaths are longer and slow down the test automation.
b)Absolute XPaths fail if any part of the path changes even slightly.
c)Relative XPaths are the default in Selenium.
d)None of the above
ans: b

21. Which of the following is an incorrect target for pattern matching as in verifyTextPresent command?
a)glob:Customer*Subscriber
b)You entered the character, ?
c)regexp:[JFM]
d)exact:* Summary
ans:D(The exact pattern does not use any special character for patterns.)

22. What is the best way to handle asynchronous data retrieval from the server as in AJAX applications?
a)Run the test case at the slowest speed.
b)Use the pause command.
c)Use the "AndWait" commands.
d)Use the "waitFor" commands.
Ans:d

23. What happens when the application creates a JavaScript alert during test case play?
a)The alert is suppressed by Selenium..
b)If there is no command to handle the alert, the play is stopped with an error.
c)If the alert is handled with assertAlert, assertAlertPresent or verifyAlert, no alert is displayed and there is no error.
d)Each of the above
ans :D

24. What is data parameterization?
a)Using variable test data in place of fixed test data values
b)Using different number of test data values when executing the same test case
c)Putting pre-requisites for the test case to execute
d)Limiting the test case execution only when certain conditions exist
ans:a

25. Which of the following statements is correct for a Test Suite?
a)A Test Suite is a comma separated values file.
b)A Test Suite is an HTML file containing a table with a single column.
c)The test cases of a Test Suite must be placed in the same folder as the Test Suite.
d)A new Test Suite can have only new test cases.
Ans:b
26. What are the different modes that Selenium uses?
a)*iehta
b)*firefox and *iexplore
c)*chrome
d)All of the above
ans:d
27. How do you start the browser?
a)selenium.Start()
b)get start()
c)selenium.server start()
d)None of the above
ans :a
28. Do you need to have Selenium .jar files as a dependency of your tests?
a)Yes
b)No
c)Yes, but as a good practice only
d)No Selenium jar file is provided with Selenium RC.
Ans:a
29. How many parameters does the Selenium object take when using DefaultSelenium?
a)2
b)3
c)4
d)6
ans:c
30. How do you start selenium rc server with user extensions?
a)java -jar selenium-server.jar
b)java -jar selenium-server.jar -userExtensions user-extensions.js
c)java -jar selenium-server.jar user-extensions.js
d)java -jar selenium-server.jar user-extensions.js -h
ans:B

31. Which Selenium command do you use to run commands in slow motion in Selenium RC?
a)selenium.setSpeed()
b)selenium.speed()
c)selenium.serverSpeed()
d)None of the above
ans:a
32. Which command is used to get the alert box?
a)assertequals(selenium.getAlert())
b)selenium.getAlert()
c)selenium.alertBox()
d)selenium.click()
ans:b
33. Which command is used for verifying if a web element exists?
a)selenium.isElementPresent(String locator)
b)assertTrue(Selenium.isElementPresent())
c)selenium.ElementPresent()
d)None of the above
ans:a
34. Which command is used for typing in a textbox?
a)selenium.input()
b)selenium.type(String locator, String value)
c)assertequals(selenium.getValues())
d)selenium.textInput()
ans:b
35. What is the command to load a page?
a)selenium.waitForPageToLoad(String timeoutInMilliseconds)
d)selenium.waitForPageToLoadInt timeoutInMilliseconds
c)selenium.waitForPageToLoad(timeoutInMilliseconds)
d)selenium.waitForPageToLoad()
ans a



Wednesday 28 August 2013

Naming Conventions while writing the QTP Script

Naming Conventions

Automation Components:


• Modules:
  For modules, we should give a name as
  Syntax: Module_<TestCaseName> (Here Module name is one which Calling the Test case from Main Test Case)
  Ex: Module_ Book_Flight (It's a reusable script)
   
• Business/Main Scripts:
  Syntax: Script_<TestCaseName>
  Ex:  Script_ Flight_Application


• Functions:
  Syntax: Function_<Function Name>
  Ex: Function_Login
• Shared Repository:
  Syntax: Repository_<Module Name>
  Ex: Repository_Flight_Applications.tsr
• Test Data( For Excel file):
  Syntax: TestData_<ModuleName>
  Ex: TestData_Flight_Applications.xls