Tuesday, 9 October 2012

JUnit - Tutorial


1. Introduction to unit testing

1.1. Unit testing

A unit test is a piece of code written by a developer that executes a specific functionality in the code under test. Unit tests ensure that code is working as intended and validate that this is still the case after code changes.

1.2. Unit testing with JUnit

JUnit 4.x is a test framework which uses annotations to identify methods that are test methods. JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not depend on other tests.
To write a test with JUnit
  • Annotate a method with @org.junit.Test
  • Use a method provided by JUnit to check the expected result of the code execution versus the actual result

You can use Eclipse or the org.junit.runner.JUnitCore class to run the test.

2. Installation of JUnit

If you use Eclipse you can use the integrated JUnit in Eclipse for your testing.
If you want to control the used JUnit library explicitly, download JUnit4.x.jar from the JUnit website at http://www.junit.org/ . The download contains the "junit-4.*.jar" which is the JUnit library. Add this library to your Java project and add it to the classpath.

3. Exercise: Using JUnit

3.1. Preparation

Create a new project de.vogella.junit.first. We want to create the unit tests in a separate folder. The creation of a separate folder for tests is not mandatory. But it is a good practice to keep the code separated from the regular code. You might even create a separate project for the test classes, but we skip this step to make this example simpler.
Create a new source folder test via right-clicking on your project, select "Properties" and choose the "Java Build Path". Select the "Source" tab.

Create new source folder for the tests

Press the Add folder button, afterwards press the Create new folder button. Create the test folder.

Creating a new folder

Alternatively you can add a new source folder by right-clicking on a project and selecting New Source Folder.

3.2. Create a Java class

In the src folder, create the de.vogella.junit.first package and the following class.

package de.vogella.junit.first;

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

3.3. Create a JUnit test

Right click on your new class in the Package Explorer and select NewJUnit Test Case. Select "New JUnit 4 test" and set the source folder to test, so that your test class gets created in this folder.

Create new test class

Press the Next button and select the methods which you want to test.

Selecting the methods to test

If the JUnit library in not part of your classpath, Eclipse will prompt you to do so.

Eclipse prompt for adding JUnit to the project class path

Create a test with the following code.

package de.vogella.junit.first;

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));
  }
} 

3.4. Run your test via Eclipse

Right click on your new test class and select Run-AsJUnit Test.

Run JUnit test via Eclipse

The result of the tests will be displayed in the JUnit View.

Result of running a unit test

The test should be failing (indicated via a red bar).
This is because our multiplier class is currently not working correctly (it does a division instead of multiplication). Fix the bug and re-run test to get a green bar.
If you have several tests you can combine them into a test suite. Running a test suite will execute all tests in that suite.
To create a test suite, select your test classesright click on itNewOtherJUnitTest Suite.

Create a test suite

Select the Next button and select the methods for which you want to create a test.
Change the code to the following to make your test suite run your test. If you develop another test later you can add it to @Suite.SuiteClasses.

package mypackage;

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

@RunWith(Suite.class)
@Suite.SuiteClasses({ MyClassTest.class })
public class AllTests {
} 

Java enum examples


Simple enum. The ; after the last element is optional, when this is the end of enum definition.



public enum Color {
 WHITE, BLACK, RED, YELLOW, BLUE;  //; is optional
}
Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.

public class Outter {
 public enum Color {
   WHITE, BLACK, RED, YELLOW, BLUE
 }
}
Enum that overrides toString method. A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found here.
?

public enum Color {
 WHITE, BLACK, RED, YELLOW, BLUE;  //; is required here.
 @Override public String toString() {
   //only capitalize the first letter
   String s = super.toString();
   return s.substring(0, 1) + s.substring(1).toLowerCase();
 }
}
Enum with additional fields and custom constructor. Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.


public enum Color {
 WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
 private int code;
 private Color(int c) {
   code = c;
 }
 public int getCode() {
   return code;
 }
Enum that implements interfaces. Enum can implement any interfaces. All enum types implicitly implements java.io.Serializable, and java.lang.Comparable.


public enum Color implements Runnable {
 WHITE, BLACK, RED, YELLOW, BLUE;
 public void run() {
   System.out.println("name()=" + name() +
       ", toString()=" + toString());
 }
}
A sample test program to invoke this run() method:


for(Color c : Color.values()) {
 c.run();
}
Or,


for(Runnable r : Color.values()) {
 r.run();
}

Putty Commands

Putty only displays command prompt of a remote Linux computer in Windows.
The commands that you type in are simply Linux commands. They are not putty commands

ls - to list files in a directory:


Code:
ls
handbook-draft.pdf  iso
ls -lh
total 3.4M
-rw-r--r-- 1 pavlo pavlo 3.4M 2007-05-15 05:53 handbook-draft.pdf
drwxr-xr-x 2 pavlo pavlo 4.0K 2007-04-10 00:25 iso
ls iso/
rhel-5-client-x86_64-disc6.iso
cd - change directory (navigate to some directory):
Code:
cd iso
cp - copy a file:
Code:
cp ../handbook-draft.pdf .
mv - move a file (also used to rename files):
Code:
mv handbook-draft.pdf howto.pdf
rm - remove a file:
Code:
rm handbook-draft.pdf
mkdir - make directory:
Code:
mkdir new
pwd - show your current location:
Code:
pwd
/home/pavlo/example/iso
whoami - find out which user you are:
Code:
whoami
pavlo
date - display date and time
Code:
date
Tue May 15 06:07:45 UTC 2007
some commands are distribution specific, such as apt in Debian. Example:
Code:
apt-get install expect
which downloads and installs "expect" package.

man - most important of all commands (opens manual pages for other commands):
Code:
man expect