Thursday, April 28, 2011

Dynamic access of EClipse workbench resources

Access active editor from Eclipse workbench :
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();

Acquire the Ifile in the avtice editor accessed above:
IFile ifile = (IFile) editor.getEditorInput().getAdapter(IFile.class);

Access File from the Ifile accessed above:
File file = ifile.getLocation().toFile();

Sunday, April 3, 2011

JUnit in Eclipse

Reference Link: http://www.vogella.de/articles/JUnit/article.html

Unit testing is done for small pieces of Code to test the correct working of its functionality.

JUnit is a test framework with a set of APIs which is used to make it unit testing more simple. This API uses annotation to identify the methods which contain tests. JUnit assumes that all test methods can be performed in an arbitrary order. Therefore tests should not depend other tests.

Steps to write a JUnit testclass:
1)Annotate a method with @org.JUnit.Test
example: here a tester class with annotation test
------------
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
------------
2) Use a method provided by JUnit(say - tester...) to check the expected result of the code execution versus the actual result

To run a JUnit test case you can either use :

A) Eclipse (the run as.. option to execute Junit tests)

(or)

B)the class "org.junit.runner.JUnitCore"


In both cases, you will need the Junit framework jar file which you will need to download from the link : https://github.com/KentBeck/junit/downloads

Once downloaded, you need to add this jar file into the Project's Buildpath. This is done as :

**rt click on the project>>select 'build path'>>select 'libraries' tab >> 'add the Junit downloaded jar file.

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

A)Considering the first option :To run a JUnit test case

(i)Create a Java project with a method which needs testing which implements a simple 'multiply' operation as a class file with code as below:

***********

package testing.junit;

public class MultiplyClass {
public int multiply(int x, int y) {
return x / y;
}
}

***********

(ii)Now create a JunitTest for this class. Rt click on this class, select JUnit Test from the JUnit category. But remember to change the Source folder from 'src' to 'test'.

(iii)Press 'Next' and select the method which you want to test. INour case, we are testing the 'Multiply' method as below.

(iv)If you have not yet JUnit in your classpath, Eclipse will ask you if it should be added to the classpath.

(v)Once created, modify the code of the Junit test case with the below code:

****

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyClassTest {

@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}

****

(vi) Now run the test case....rtclick on the testcase class>>run as...>>JUnit test

the assertEqual method in the above code will check with the expected result value (50) and the actual result obtained by calling the method intended for testing.

If the test case fails, a red light will glow.. In this case, the codes needs to be rechecked.. and corrected. Once corrected, the execution will return a green glow.

In this way we can create multiple JUnit test cases. However, if you want to test all cases at once.. you could use the

JUnit test case: Once you have created multiple test cases, rtclcik on selected testclasses>>new>>JUnit test suite>> select all the methods for testing.

Now modify the testSuite class as below,

*******

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses( { MyClassTest.class })
public class AllTests {
}
*******
If you later develop another test you can add it to @Suite.SuiteClasses
--------------------------------------------------

B)Considering the first option :To run a JUnit via code

The class "org.junit.runner.JUnitCore" provides the method runClasses() which allows you to run one or several tests classes.

As a return parameter you receive an object of type "org.junit.runner.Result". This object can be used to retrieve information about the tests and provides information about the failed tests.

To create a JUnit test case via code, follow the same steps as above from (i) through creating a src folder for the test classes

Then, Create in your "test" folder a new class "MyTestRunner" with the following coding:

****
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyTestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MyClassTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
}
}

****

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

Static imports with Eclipse

JUnit uses a lot of static methods and Eclipse cannot automatically import static imports. You can make the JUnit test methods available via the content assists.

Open the Preferences via Window -> Preferences and select Java > Editor > Content Assist > Favorites. Add then via "New Member" the methods you need. For example this makes the assertTrue, assertFalse and assertEquals method available.

You can now use Content Assist (Ctrl+Space) to add the method and the import.

I suggest to add at least the following new members.

  • org.junit.Assert.assertTrue

  • org.junit.Assert.assertFalse

  • org.junit.Assert.assertEquals

  • org.junit.Assert.fail


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

Assert statements/available test methods in JUnit testing:

StatementDescription
fail(String) Let the method fail, might be usable to check that a certain part of the code is not reached.
assertTrue(true);True
assertsEquals([String message], expected, actual) Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays
assertsEquals([String message], expected, actual, tolerance) Usage for float and double; the tolerance are the number of decimals which must be the same
assertNull([message], object)Checks if the object is null
assertNotNull([message], object) Check if the object is not null
assertSame([String], expected, actual) Check if both variables refer to the same object
assertNotSame([String], expected, actual) Check that both variables refer not to the same object
assertTrue([message], boolean condition) Check if the boolean condition is true.

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

Annotations in Junit

AnnotationDescription
@Test public void method() Annotation @Test identifies that this method is a test method.
@Before public void method() Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class)
@After public void method() Test method must start with test
@BeforeClass public void method() Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database
@AfterClass public void method() Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database
@Ignore Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted or if the runtime of this test is just to long to be included.
@Test(expected=IllegalArgumentException.class) Tests if the method throws the named exception
@Test(timeout=100) Fails if the method takes longer then 100 milliseconds

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


Current Junit version is 4.9.... dated 5th Apr, 2011

________________________________________________________________


Apache Ant in Eclipse

Reference Link: http://www.vogella.de/articles/ApacheAnt/article.html

Ant is a simple Build tool in the form of an XML file used in executing repeatetive build tasks using a single xml document.

Build task such as , Compiling, creating a jar, Running Junit tests, etc...
_____

Installation
:
Ubuntu : On Debian /Ubuntu use "apt-get install ant" to install it.
Windows :

- Download Apache Ant from http://ant.apache.org/ .

- Extract the zip file and Set the "ANT_HOME" environment variable to this location and include the "ANT_HOME/bin" directory in your path.

- Make sure that JAVA_HOME environment variable is set to the JDK, which is required for running Ant.

_____

Test the Installation:

Check your installation by opening a command line and typing "ant -version" into the commend line.

_____

Creating the Ant, build.xml:

-Create a java project with a simple java class file.. say (test.java), which is in a package 1.2.3.test
-Now create an xml file, build.xml , which is your ant file and paste the xml source(in figure below) from section 3.2 of the reference link page into this xml document within this project.

In the source below, the 'Target' tag specifies the task that needs to be executed.

A single build fil ecan have multiple task within it. If your observe the below source, you can see that each target tag consists of a certain execution such as , "Javac" - Compiling java source, "mkdir" - creating directories, etc.

The "depends" attribute of the target tag specifies the other targets that needs to be existing or executed prior to the current specified targets.

Last but not the least, the Ant file can also be used in executing JUnit test.

********************
************************
















































Main target




********************