Showing posts with label Java General. Show all posts
Showing posts with label Java General. Show all posts

Wednesday, November 24, 2010

JUnit

JUnit is a regression-testing framework that developers can use to write unit tests as they develop systems.
JUnit provides also a graphical user interface (GUI) which makes it possible to write and test source code quickly and easily.

public class Calculator{
int sum(int num1,int num2){
return num1+num2;
}
}

Coding Convention :
1. Name of the test class must end with "Test".
2. Name of the method must begin with "test".
3. Return type of a test method must be void.
4. Test method must not throw any exception.
5. Test method must not have any parameter.

import junit.framework.TestCase;

public class CalculatorTest extends TestCase { //each of our testing class should extend TestCase class
Calculator cal=new Calculator();

public CalculatorTest(String name) { //every test is given name. The constructor of the class provides this functionality by passing this parameter to the constructor of the parent class
super(name);
}

public void testSum() {
assertEquals(2,cal.sum(1,1));
}
}

If the method did not perform as expected then it will cause assertEquals() to fail.
Now we need to fix the problem and run the test again .
We need to repeat this process until the test is passed.

How to run JUnit in text mode :

Execute > java junit.textui.TestRunner CalculatorTest.
The passing test results in the following textual output:

Time: 0
OK (1 test)


public class TestRunner
extends BaseTestRunner
A command line based tool to run tests.
java junit.textui.TestRunner [-wait] TestCaseClass

TestRunner expects the name of a TestCase class as argument. If this class defines a static suite method it will be invoked and the returned test is run. Otherwise all the methods starting with "test" having no arguments are run.
When the wait command line argument is given TestRunner waits until the users types RETURN.
TestRunner prints a trace as the tests are executed followed by a summary at the end.
======================================================================================================================

public class Subscription {

public int price; // subscription total price in euro-cent
public int length; // length of subscription in months

/**
* A constructor to create a subsription.
*/
public Subscription(int p, int n) {
price = p;
length = n;
}

/**
* Calculate the monthly subscription price in euro, rounded up to the
* nearest cent.
*/
public double pricePerMonth() {
if (length <= 0 || price <= 0) return 0; double r = (double) price / (double) length; double fraction = Math.IEEEremainder(r, 1.0); if (fraction > 0)
return Math.floor(r) + 1;
else
return Math.floor(r);
}

/**
* Call this to cancel/nulify this subscription.
*/
public void cancel() {
length = 0;
}
}

TEST CASES:
package test;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class SubscriptionTest {

Subscription s1;
Subscription s2;

@Before
public void setUp() throws Exception { //Called everytime before a testCase function is executed. Life-Cycle method
s1 = new Subscription(100, 2);
s2 = new Subscription(200, 3);
}

@After
public void tearDown() throws Exception { //Called everytime after a testCase function is executed. Life-Cycle method
s1 = null;
s2 = null;
}

@Test
public void testPricePerMonth() {
assertTrue(s1.pricePerMonth() == 50);
assertTrue(s2.pricePerMonth() == 66.0);
}

@Test
public void testCancel() {
s1.cancel();
assertTrue(s1.length == 0);
assertFalse(s2.length == 0);
}

}

prompt> javac -cp .; SubscriptionTest.java
prompt> java -cp .; org.junit.runner.JUnitCore SubscriptionTest

Time: 0,015

There were 2 failures:

1) test_returnsEuro(SubscriptionTest)
java.lang.AssertionError:
...
at SubscriptionTest.test_returns_Euro(SubscriptionTest.java:13)
...

2) test_roundUp(SubscriptionTest)
...
at SubscriptionTest.test_roundUp(SubscriptionTest.java:19)
...

Tests run: 2, Failures: 2

We keep fixing it until we get no more failures.


TestSuite

If you have two tests and you'll run them together you could run the tests one at a time yourself, but you would quickly grow tired of that. Instead, JUnit provides an object TestSuite which runs any number of test cases together. The suite method is like a main method that is specialized to run tests.

Create a suite and add each test case you want to execute:

public static void suite(){
TestSuite suite = new TestSuite();
suite.addTest(new BookTest("testEquals"));
suite.addTest(new BookTest("testBookAdd"));
return suite;
}


Since JUnit 2.0 there is an even simpler way to create a test suite, which holds all testXXX() methods. You only pass the class with the tests to a TestSuite and it extracts the test methods automatically.

Note: If you use this way to create a TestSuite all test methods will be added. If you do not want all test methods in the TestSuite use the normal way to create it.

Example:

public static void suite(){
return new TestSuite(BookTest.class);
}


Run JUNIT using Ant
< target name="test">
<junit fork="yes" printsummary="no" haltonfailure="no">
<test name="${test.class.name}" />
<formatter type="plain" usefile="false" />
<classpath refid="test.classpath" />
</junit>
</target>


ant test

#

Define the Ant task for running JUnit and generating reports:

<target name="test-html">
<junit fork="yes" printsummary="no" haltonfailure="no">
<batchtest fork="yes" todir="${test.reports}" >
<fileset dir="${classes}">
<include name="**/*Test.class" />
</fileset>
</batchtest>
<formatter type="xml" />
<classpath refid="test.classpath" />
</junit>

<junitreport todir="${test.reports}">
<fileset dir="${test.reports}">
<include name="TEST-*.xml" />
</fileset>
<report todir="${test.reports}" />
</junitreport>
</target>

JDBC

import java.sql.*;
Load Driver Class
Class.forName("jdbc-driver"); //initializes static block d/b variables initialized
4 types of Drivers:
type 1: ODBC Bridge
type 2 & 3: Needs client s/w to be installed at client d/b
type 4: Direct recommended by Sun
type 2 ---- developed in Native Code
type 3 & 4 ---- developed in java
Connection con = DriverManager.getConnection("jdbc:myDriver:d/bSource", "Login","Password");
The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. An application to use a logical name for a data source instead of having to supply information specific to a particular driver. (preferred)
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
ds.setPort(1527); ds.setHost("localhost"); ds.setUser("APP"); ds.setPassword("APP");
Connection con = ds.getConnection();

a DataSource can usually be configured and managed by the application server instead of your application. It means that the connections you get from a DataSource can come from a connection pool for performance. It means that the connections may participate in a container-managed distributed transaction without you having to worry about the nitty gritty of it.
------------------------------------------------------------------------------------
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { sop ( rs.getInt("a") + rs.getString("b") + rs.getFloat("c"));
con.close(); //finally block
To update d/b Table
int count = st.executeUpdate("insert int Table1 values (123, b, 123.111)"); //returns rows updated in d/b

Using Prepared Statement -- each time sql statement compilation is not required
PreparedStatement pstmt = con.prepareStatement("insert into Table1 values(?, ?, ?)");
pst.setInt(1,123); pst.setString(2, "xxx"); pst.setFloat(3, 123.111);
int count = pst.executeUpdate();
pst.setInt(1,456); pst.setString(2, "yyy");
int count = pst.executeUpdate();

---------------------------Meta Data------------------------------
ResultSetMetaData metaData = rset.getMetaData();
int count = metaData.getColumnCount();
for( int i=1; i<=count; i++)
{ sop ( metaData.getColumnLabel(i) + metaData.getColumnTypeName(i) + metaData.getColumnTypeSize(i) );

-------------------Commit and Rollback--------------------------
con.setAutoCommit(false); //true by default
con.rollback;
con.commit();

--------------------execute Batch (reduces d/b hits)--------------
PreparedStatement pstmt = con.prepareStatement("insert into Table1 values(?, ?, ?)");
pst.setInt(1,123); pst.setString(2, "xxx"); pst.setFloat(3, 123.111);
pst.addBatch();
pst.setInt(1,456); pst.setString(2, "yyy"); pst.setFloat(3, 123.111);
pst.addBatch();
pst.executeBatch(); //only one d/b hit

----------------Callable Stmt--------------------------------------
Used for d/b stored procedures and functions execution
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

DAO - data access object (encapsulates all d/b related functionalities)

Friday, January 22, 2010

Core Java Tutorials - General Concepts

byte 8bit, short 16bit, int 32bit, long 64bit, float 32bit, double 64bit, char 16bit, boolean

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement
ArrayList a = new ArrayList() ;
a.add("1");
a.add(new Test());
for (Object item:a){
System.out.println(item);
//Output 1 Test@4523
}


You can use a construct called varargs to pass an arbitrary number of values to a method.
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name.

public void test(int a, String...strings){//varargs should be last parameter
System.out.println(strings[1]);
}
obj.test("a","b","c");

//Output b

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.
Reference data type parameters, such as objects, are also passed into methods by value.This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

NOTE:
public void swap(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
swap(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}


//OUTPUT:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0



Point originOne = new Point(23, 94);



Covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

You can declare an inner class within the body of a method. Such a class is known as a local inner class. You can also declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes.
The enum declaration defines a class (called an enum type). All enums implicitly extend java.lang.Enum

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

There are three annotation types that are predefined by the language specification itself: @Deprecated, @Override, and @SuppressWarnings.
Annotations have a number of uses, among them:
Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.

Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
Runtime processing — Some annotations are available to be examined at runtime.

An assertion is a statement in the JavaTM programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
javac -source 1.4 Foo.java
the implements clause follows the extends clause

Marker Interface have no methods defined within them.

You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.

An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

public final Class getClass() : Returns the runtime class of an object.
By definition, if two objects are equal, their hash code must also be equal.
The syntax for these two java.io.PrintStream methods (format and printf) is the same:
public PrintStream format(String format, Object... args)
System.out.format("The value of the float variable is %f, while the value of the integer variable is %d, and the string is %s", floatVar, intVar, stringVar);
System.out.format("%f%n", java.lang.Math.PI);
// --> "3.141593"
System.out.format("%10.3f%n", java.lang.Math.PI); /
/ --> " 3.142"

java.text.DecimalFormat class to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator.
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(new java.text.DecimalFormat("###,###.###").format(123456.789));
// -->123,456.789

Note : Using the static import language feature, you don't have to write Math (all methods are static) in front of every math function (say MATH.cos(angle)):
import static java.lang.Math.*;
The random() method returns a pseudo-randomly selected number between 0.0 and 1.0.
The MIN_VALUE and MAX_VALUE constants contain the smallest and largest values that can be contained by an object of that Number (abstract class) type.


A wrapper class that "wraps" the char in a Character object
if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character (or any primitive wrapper classes) for you. This feature is called autoboxing—or unboxing, if the conversion goes the other way.

Character ch = 'a'; // the primitive char 'a' is boxed into the Character object ch
the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

String str = String.format(String format, Object... args);
String[] split(String regex)
//split on regex match
String trim()
//trim whitespaces
The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf().

A StringBuffer class that is exactly the same as the StringBuilder class, except that it is thread-safe by virtue of having its methods synchronized.
new StringBuilder();//creates empty builder, capacity 16
Generics add stability to your code by making more of your bugs detectable at compile time.
first create a generic type declaration by changing the code "public class Box" to "public class Box"; this introduces one type variable, named T, that can be used anywhere inside the class.

public class Box {
private Object object;
public void add(Object object){this.object = object;}
public Object get(){return object; }
}


Since its methods accept or return Object, you're free to pass in whatever you want (Integer, String etc.), provided that it's not one of the primitive types. However, should you need to restrict the contained type to something specific (like Integer)

public class Box<> { //Generic version of the Box class
private T t;
// T stands for "Type"
public void add(T t){this.t = t;}
public T get(){return t;}
}


From Client main method use it as, so errors can be detected at compile time
Box integerBox = new Box();
Box integerBox = new Box(); //also allowed
integerBox.add(new Integer(10));
Integer someInteger = integerBox.get();
public class Box { ...} would be allowed.
public class Box {...}
//Bounded type parameter

Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors.
public <> void inspect(U u){ ... }
public <> void inspect(U u){ ... }

To specify additional interfaces that must be implemented, use the & character, as in:
<>
You can perform a generic type invocation, passing Number as its type argument, and any subsequent invocation of add will be allowed if the argument is compatible with Number: (this is Subtyping)
Box box = new Box();
box.add(new Integer(10));
// OK
box.add(new Double(10.1));
// OK

To specify a cage capable of holding some kind of animal: (Wildcards)
Cage someCage = ...;
Read "? extends Animal" as "an unknown type that is a subtype of Animal, possibly Animal itself".

The code , therefore, would be read as "an unknown type that is a supertype of Animal, possibly Animal itself".

An unbounded wilcard, which simply looks like . An unbounded wildcard is essentially the same as saying .
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
For instance, Box is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments.
This means that you can't find out what type of Object a generic class is using at runtime.

You could import Rectangle and its public nested classes by using the following two statements.
import graphics.Rectangle;
import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle.