Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, July 10, 2016

Comparison of C# and Java for testers

was talking with few test professionals for C# automation. Team is reluctant to change from Java background to C# technologies. I have used many scripting and programming languages. There is not much variation between Java & C# at core langulage level.

Differences and similarities

DescriptionJavaC#
Program Entry Pointmain(String ...args) Main() or Main(string [] args)
Smallest Deployment UnitJarEXE/DLL, Private Assembly, Shared Assembly
SigningJar SigningAssembly Signing
Namespacepackage namespace
Including Classesimportusing
Inheritanceclass (extends), interface (implements)class and interface (:)
Visibilityprivate, package,protected, publicprivate, protected, internal,internal protected, public
Abstract Classabstract class X { ... }abstract class X { ... }
Non-Extensible Classfinal class X { ... }sealed class X { ... }
Non-Writable Fieldfinalreadonly
Non-Extensible Methodfinalsealed
Constantstatic finalconst
Checking Instance Typeinstanceofis
Enumsenum, can have fields, methods and implement interfaces and are typesafeenum, cannot have methods,fields or implement interfaces, not typesafe
for-each constructfor (item : collection)
{ ... }
foreach(item in collection)
{ ... }
Switch-Casenumeric types (int,float...) enums, and now strings (in Java 7)numeric types, enums and strings
Method ParametersObject References are passed by Value onlyObject reference are passedby Value(default), ref & out
Variable Argumentsmethod(type... args)Method(params type[] args)
Catching Exceptionstry { ... } catch (Exception ex) {...}try { ... } catch (Exception ex) {...}
Meta TypeClass klass = X.class;Type type = typeof(X);
Meta Information@Annotation[Attribute]
Static classSimulated by private Ctor and static methodsStatic class and ctor with static methods
PropertiesgetProperty(),setProperty()Property { get; set; } compiler generated get_Property() and set_Property() methods


Selenium script on Java & C#
Developed a sample selenium scripting using Java and ported to C#.




Reference Links

Moving to C# for Java Developers
Java Vs C#

Sunday, January 29, 2012

JVM Monitoring

Couple of our applications are using Tomcat server. JMeter was used as load testing tool. To monitor Java memory, I used two options. One is JMX(Java Management Extensions) console and Psi-Probe.

To implement those options, you should add following entries into catalina.sh

set CATALINA_OPTS=-Dcom.sun.management.jmxremote \
-Dcom.sun.management.jmxremote.port=9005 \
-Dcom.sun.management.jmxremote.ssl=false \
-Dcom.sun.management.jmxremote.authenticate=false

To access JMX console,Enter command ==> [java_installation]\bin\jconsole hostname:port
To use Probe, you need to deploy in tomcat server instance and then access the probe application.

Saturday, November 26, 2011

JMeter - JDBC Driver issue

I was trying JDBC query execution through JMeter. I was getting the error like java.sql.SQLException: No suitable driver found . I have given ojdbc6.jar on classpath and installed Oracle client. Still JMeter has thrown error. The solution is, ojdbc6.jar should be copied under JMeter Lib folder (<JMeter installation directory>\lib).

Later, the same script was copied into a server and executed the script. Got the same error. Server does not have Oracle client installation and ojdbc6.jar in JMeter lib folder. Just copied the ojdbc6.jar and able to run the script successfully.
Note:
ojdbc6.jar should be used for Oracle 11 version. Also it is supported only Java1.5 and above.

Saturday, January 30, 2010

Indian Stock Quotes through Selenium

I thought to get the current indian (NSE) stock quotes by using Selenium tool. I chose Selenium RC and Java language. I have developed a java class for all file related tasks. Another java program used to get the stock values from set of given scrips.

Selenium RC required set of configuration to run the tests. We need to give the proxy details (with or without proxy) for internet connection. I'm planning to cover the configuration in upcoming posts. Below I have given the java code to get current stock values.

Current Stock quotes - Selenium RC with Java
Note: FileHandlerLib class - file related tasks.

/* To get all stockquotes * To Compile: javac GetAllStockQuotes.java -Xlint:unchecked * To Run: java junit.textui.TestRunner com.palani.tests.GetAllStockQuotes * To Run: java GetAllStockQuotes * Note: Recompile with -Xlint:unchecked for details. * javac FileHandlerLib.java -Xlint:unchecked */ package com.palani.tests; // import FileHandlerLib; import com.palani.utils.*; import com.thoughtworks.selenium.*; import junit.framework.*; import java.util.regex.Pattern; import java.io.*; import java.util.*; import java.text.DateFormat; import java.text.SimpleDateFormat; public class GetAllStockQuotes extends SeleneseTestCase { private Selenium selenium; private FileHandlerLib fhNew = new FileHandlerLib(); // @Before public void setUp() throws Exception { selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.nseindia.com/"); selenium.start(); } // @Test public void testGetAllStockQuotes() throws Exception { // Variables String sScripsFile; String sQuotesFile; String sUrlPart; String sCurrentDate; String sQuote; String sQuoteValue; String sOutput; ArrayList aData = new ArrayList(); // Initialization // sCurrentDate = "20100101" ; sCurrentDate = fhNew.getDateTime(); sQuotesFile = "D:\\Stocks\\"+sCurrentDate+"_stocks.txt"; fhNew.DeleteFile (sQuotesFile); sScripsFile = "D:\\Stocks\\StockScrips.txt"; sUrlPart="/marketinfo/companyinfo/companysearch.jsp?cons="; aData = fhNew.ReadFileToArray (sScripsFile); Object[] elements = aData.toArray(); System.out.println ("SCRIPs File: " + sScripsFile); System.out.println ("Quotes File: " + sQuotesFile); selenium.open("/content/equities/cmquote.htm"); Thread.sleep(2000); for(int iIndex=0; iIndex < elements.length ; iIndex++) { sQuote=(String)elements[iIndex]; sQuote=sQuote.trim(); sQuoteValue = "0"; System.out.println("Quote:"+elements[iIndex]+ " ,index: " + iIndex); if (!(sQuote.equals("") ) ) { if (selenium.isElementPresent("companyname")) { selenium.type("companyname", sQuote); } else { selenium.type("company", sQuote); } selenium.click("submit1"); Thread.sleep(2000); for (int second = 0;; second++) { if (second >= 150) System.out.println("timeout"); try { if (selenium.isElementPresent("//div[@id='PI4']/b")) { sQuoteValue = selenium.getText("//div[@id='PI4']/b"); System.out.println ("Quote Value: " + sQuoteValue); sOutput=sQuote.trim()+","+sQuoteValue.trim(); fhNew.FileWrite (sQuotesFile,sOutput); break; } // end if } catch (Exception e) { System.out.println("Selenium Run: " + e.getMessage() + "\n"); e.printStackTrace(); } Thread.sleep(1000); } } // End If } // end for loop } // @After public void tearDown() { selenium.stop(); } // To run Selenium Testcase using JUnit public static Test suite() { return new TestSuite(GetAllStockQuotes.class); } // To run Selenium Testcase public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } }

Tuesday, September 15, 2009

Java and myself

In my first job, I have used VB and Java. At that time, I was new to Internet. I used to develop programs in VB6 and Java2 around Internet programming. I wrote java programs using notepad and Emacs editors. After that many years I ran behind GUI automation tools such as VisualTest, WinRunner, QTP and Silktest. Sometimes I'm using VBScript for few testing tasks.

Recently many tools are supported to use Java as test language. Again I'm going to re-look at java. I was looking into my old java code. I tried to compile few java programs with recent Java version 1.6.0.14. Few classes are deprecated. I have used this command javac ZDownloadURL.java -Xlint:deprecation to compile java program.

In Sun Developer network, one tutorial was there for Basic Java. Link :Essentials of the Java Programming Language

Below program can be used to download any web page. I tried my blog and it still works.
To Compile - javac ZDownloadURL.java -Xlint:deprecation
To run the program - java ZDownloadURL



// $Id$

/**
*
*
* Created: Tue Oct 24 18:51:26 2000
*
* @author palani selvam
* @version $Revision$
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;


/* To Run this file, put command as
java -Dhttp.proxyHost=192.168.27.2 -Dhttp.proxyPort=3128 ZDownloadURL
*/


public class ZDownloadURL extends JFrame implements WindowListener,ActionListener {
String URL; //Given URL
// String inputLine; //To read Line by line
String title="Downloading Trial"; //To give title of the URl

static JFrame frame; //Parent Level Container
JButton save; //Save Button
JButton down; //Declare Download Button
JButton exit; //exit Button
JTextField url; //To enter URl
JTextArea contents; //Contents of specific file
//JPanel panel; //Second level Container
Container panel;
//JPanel temp;
Container temp;


public ZDownloadURL() {
//frame=new JFrame();
super.setTitle(title);
super.setForeground(Color.blue);
super.setBackground(Color.yellow);

panel=getContentPane();
temp=new JPanel();
temp.setLayout(new BorderLayout());
temp.setSize(10,20);

GridBagLayout grid=new GridBagLayout(); //Set GridBagLayout
GridBagConstraints c=new GridBagConstraints();
c.fill=GridBagConstraints.HORIZONTAL;

panel.setLayout(grid);
// grid.setConstraints(c); //Add GridbagConstraints

url=new JTextField(20);
contents=new JTextArea(30,30);
contents.setLineWrap(true); //To Wrap lines in TextArea

/***
* To create ScrollBars to JTextArea
*
*/

JScrollPane pane = new JScrollPane(contents);
temp.add(pane);



/***
contents.setColumns(20);
contents.setRows(10);
contents.setLineWrap(true);
contents.setWrapStyleWord(true);
contents.setSize(10,20);

temp.add(contents);
**/



down=new JButton("DownLoad");
save=new JButton("Save");
exit=new JButton("Exit");
JLabel label=new JLabel("Enter valid URL");

c.gridx=0;
c.gridy=0;
c.insets=new Insets(5,0,0,0);
grid.setConstraints(label,c);
panel.add(label);

c.gridx=1;
c.gridy=0;
c.gridwidth=1;
//c.gridheight=2;
c.insets=new Insets(5,0,0,0);
grid.setConstraints(url,c);
panel.add(url);

c.gridx=2;
c.gridy=0;
c.insets=new Insets(5,0,0,0);
grid.setConstraints(down,c);
panel.add(down);

c.gridx=0;
c.gridy=1;
c.gridwidth=20;
c.gridheight=10;
c.insets=new Insets( 20,0,0,0);
grid.setConstraints(temp,c);
panel.add(temp);


c.gridx=0;
c.gridy=12;
c.gridwidth=1;
c.insets=new Insets(10,0,0,0);
grid.setConstraints(save,c);
panel.add(save);

c.gridx=1;
c.gridy=12;
c.gridwidth=1;
c.insets=new Insets(10,0,0,0);
grid.setConstraints(exit,c);
panel.add(exit);

exit.addActionListener(this);
save.addActionListener(this);
down.addActionListener(this);
// frame.addActionListener(this);

// frame.add(panel);


}


public void windowActivated(WindowEvent we) {

}

public void windowDeactivated(WindowEvent we) {

}

public void windowIconified(WindowEvent we) {

}

public void windowDeiconified(WindowEvent we) {

}

public void windowOpened(WindowEvent we) {

}

public void windowClosed(WindowEvent we) {

}

public void windowClosing(WindowEvent we) {

System.exit(10);

}


/***
* pass the URL as string
*/


public void Download(String _url) {
try {
URL myURL=new URL(_url);
BufferedReader in=new BufferedReader(new InputStreamReader(myURL.openStream()));

String inputLine;
contents.setText("");

while((inputLine=in.readLine()) != null) {
//contents.setText(contents.getText()+"\n"+inputLine);
contents.append("\n"+inputLine);

}
} catch(Exception ex) {

System.out.println(ex.toString());
}

}

public boolean checkURL(String _url) {
if((_url.indexOf("http"))!=0) {
return true;
}
else {
return false;
}
}


public void actionPerformed(ActionEvent ae) {
//String action=ae.getActionCommand();

URL=url.getText();
Object action=ae.getSource();

//To Download

if(action.equals(down)) {
/** if(checkURL(URL)) {
Download(URL);
}
else
JOptionPane.showMessageDialog(new JFrame(),"Enter Valid URL in TextField!","Information",JOptionPane.INFORMATION_MESSAGE);

**/

Download(URL);


}


//To save that URL's contents
//Not implemented

if(action.equals(save)) {
JFileChooser fc=new JFileChooser();
int returnVal=fc.showSaveDialog(new JFrame());

if(returnVal==JFileChooser.APPROVE_OPTION) {
File file=fc.getSelectedFile();
super.setTitle(file.getName());
}
}

if(action.equals(exit)) {
System.exit(0);
}

}

public static void main(String args[]) {
frame=new ZDownloadURL();

frame.setSize(500,400);
frame.pack();
frame.show();

}

} // ZDownloadURL

/*
* $Log$
*/

Sunday, August 2, 2009

Selenium Overview

Selenium is a suite of tools to automate web app testing across many platforms. It is a GUI based automation tool. Initially it is built by ThoughtWorks. It supports various browsers on various platforms.

Selenium Home Page
Selenium Projects
Tool History
Platform Support

Selenium Projects
Selenium has many projects. Following projects are mostly used by testers.


  1. Selenium IDE (IDE)
    Selenium IDE can be used only in FireFox. It is an add-on for FireFox. User can record the actions and can edit and debug the tests. It can be used to identify IDs, name and XPath of objects. Only one test at a time.

  2. Selenium Core (CORE)
    Selenium Core is the original Javascript-based testing system. This technique should work with any JavaScript enabled browser. It is the engine of both, Selenium IDE and Selenium RC (driven mode), but it also can be deployed on the desired application server. It is used specifically for the acceptance testing.
    User can record the tests using Selenium IDE and can use the same tests to run in other browsers with minimal modifications. It provides support to run the tests in HTA (HTML Applications) Mode. This mode works only in IE.

  3. Selenium Remote Control (RC)
    Selenium Remote Control is a test tool that allows user to write automated web application UI tests in few programming languages against any HTTP website using any mainstream JavaScript-enabled browser. User can write the tests (More expressive programming language than the Selenese HTML table format) in Java, DotNet, Perl, Ruby and PHP. Also it supports few testing frameworks.

  4. Selenium Grid
    Selenium Grid allows easily to run multiple tests in parallel, on multiple machines, in an
    heterogeneous environment by cutting down the time required for test execution. Using this, user can run multiple instances of Selenium Remote Control in parallel.

Supported browsers
Selenium tools can run in following browsers.
  • Internet Explorer
  • FireFox
  • Opera
  • Safari
  • Seamonkey

Supported Operating Systems
Users can execute the selenium tests in following OS.
  • Windows
  • Linux
  • Solaris
  • OS X

Supported Programming languages
Below languages are supported by Selenium RC.
  • C# (DotNet)
  • Java
  • Perl
  • Ruby
  • Python
  • PHP

Lot of presentations and documents about Selenium are shared in SlideShare. You can do simple search and get many docs.

Recorded Selenese code through IDE
 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>GoogleSearch2</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">GoogleSearch2</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>/</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>q</td>
<td>silk4j tutorial</td>
</tr>
<tr>
<td>click</td>
<td>btnG</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>30000</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>q</td>
<td>Silktest extension kit</td>
</tr>
<tr>
<td>click</td>
<td>btnG</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>30000</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>btnG</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>30000</td>
<td></td>
</tr>

</tbody></table>
</body>
</html>

Java code - Selenium RC
 

package com.example.tests;

import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;

public class NewTest extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://www.google.com/", "*chrome");
}
public void testNew() throws Exception {
selenium.open("/");
selenium.type("q", "silk4j tutorial");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
selenium.type("q", "Silktest extension kit");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
System.out.println("New Test is completed.");
}
public void tearDown() {
browser.stop();
}
}

Sunday, July 5, 2009

Silk4J Overview & Analysis

Silk4j was introduced from Silktest 2008. Hereafter user can use Java as test scripting language with the help of Silk4J Package. It is supported only with Open Agent. I hope that Borland might target developers too. User can write java unit tests as well as GUI tests.

From Silktest Help - Silk4J Eclipse Plugin

Silk4J enables user to create functional tests using the Java programming language. Silk4J provides a Java runtime library that includes test classes for all the classes that Silk4J supports for testing. This runtime library is compatible with JUnit, which means you can leverage the JUnit infrastructure and run and create tests using JUnit. You can also use all available Java libraries in your testcases.

The testing environments that Silk4J supports include:

  • Adobe Flex applications
  • Java SWT applications
  • Windows Presentation Foundation (WPF) applications
  • Windows API-based client/server applications
  • xBrowser applications


Silk4J with Open Agent - Google Search testcase

I have gone through documents such as Silk4J_QuickStartGuide_en.pdf and Silk4J_AdvancedUserGuide_en.pdf. I created the sample code and it works fine.

package com.palani;
import org.junit.Before;
import org.junit.Test;

import com.borland.silktest.jtf.Desktop;
import com.borland.silktest.jtf.TechDomain;
import com.borland.silktest.jtf.xbrowser.BrowserWindow;
import com.borland.silktest.jtf.xbrowser.DomButton;
import com.borland.silktest.jtf.xbrowser.DomTextField;

public class GoogleSearch {
private Desktop desktop = new Desktop();
private BrowserWindow browser;

@Before
public void setUp() throws Exception {

browser = (BrowserWindow)desktop.executeBaseState(
"C:/Program Files/Internet Explorer/iexplore.exe", null, null,
".//BrowserWindow", TechDomain.XBROWSER);
browser.navigate("http://www.google.co.in/");
}

@Test
public void testSimpleGoogleSearch() throws Exception {

DomTextField searchText = (DomTextField)browser.find (".//DomTextField[@title='Google Search' and @name='q']");
searchText.setText("");
searchText.setText("silk4j tutorial");
DomButton btn = (DomButton)browser.find(
".//DomButton[@type='submit' and @name='btnG']");
btn.click();
}
}


4Test with Open Agent - Google Search testcase
The same case is written in 4Test. SilkTest supports a subset of the XPath query language. It gives dynamic object recognition.

[ ]
[-] testcase GoogleSearch1 () appstate none //DefaultBaseState
[ ] STRING sUrl="http://www.google.co.in/"
[ ]
[-] if (! InternetExplorer.Exists(2))
[ ] InternetExplorer.Invoke ()
[ ] InternetExplorer.SetActive ()
[ ] InternetExplorer.Maximize ()
[ ]
[ ] WINDOW wMain = Desktop.Find(".//BrowserApplication")
[ ] WINDOW wBrowser = wMain.Find(".//BrowserWindow")
[ ]
[ ] wMain.SetActive()
[ ] wBrowser.Navigate (sUrl)
[ ] WINDOW wText1=wBrowser.Find(".//DomTextField[@title='Google Search' and @name='q']")
[ ] wText1.SetText("Silk4j Tutorial")
[ ] wBrowser.Find(".//DomButton[@name='btnG' ]").Click ()
[ ]
[ ] WINDOW wText2=wBrowser.Find(".//DomTextField[@name='q']")
[ ] wText2.SetText("Silktest Extension Kit")
[ ] wBrowser.Find(".//DomButton[@name='btnG' ]").Click ()
[ ]
[ ]


Selenium RC Java format - Google Search testcase

Selenium is a open source tool and can be used only web based applications. But user can choose different languages to develop the suite. Selenium tests can be written with Selenese, PHP, Perl, Python, Ruby, DotNet and Java.

import org.openqa.selenium.server.SeleniumServerTest;
import com.thoughtworks.selenium.*;
import junit.framework.*;
import org.openqa.selenium.server.SeleniumServer;

public class TestSearch extends SeleniumServerTest {
private Selenium browser;
public void setUp() throws Exception {
SeleniumServer seleniumServer = new SeleniumServer();
browser = new DefaultSelenium("localhost", 5555, "*firefox", "http://www.google.com");
seleniumServer.start();
browser.start();
}

public void testGoogle() {
browser.open("/webhp?hl=en");
browser.type("q", "hello world");
browser.click("btnG");
browser.waitForPageToLoad("5000");
assertEquals("hello world - Google Search", browser.getTitle());
}

public void tearDown() {
browser.stop();
}
}


Few Questions

Now Silktest and selenium both supports in Java language. Silktest supports many type of applications. In other end, Selenium supports many Operating Systems and browsers. I have few questions on Silk4J.
  1. Can Silk4J utilize silktest features such as TestcaseEnter,TestcaseExit,scriptEnter and ScriptExit?
  2. Target audience?
  3. Any Success stories (implementations)?