Schlagwort-Archive: JUnit

Compile, Run And Develop Java in the Console, Setup for TDD with JUnit

When you want to learn Java it is good to know about the basics.

Requirements

  1. Text editor
  2. Java installed

check if java is installed.

java -version

Should be displayed something like that:

java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07-348-9M3406a)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-348, mixed mode)

Creating Development Structure

expected we want to create a project folder and in it an src,bin,lib,test folder.
src = here you create source files (packages)
bin = Output folder
lib = for Libraries e.g. JUnit.jar
test = mirroed the package structure from src, here you develop your tests.

mkdir project
cd project
mkdir src
mkdir bin
mkdir lib
mkdir test

Write a first very simple program

cd src
vim Main.java

type the following:

public class Main{
 public static void main(String[] args){
  System.out.println("Hello User");
 }
}

Back to console compile! Just to see it runs. (You are still in folder src)

javac Main.java
ls

You should see now 2 Files Main.java and Main.class
To run the program just type

java Main

You should see

Hello User

Now delete the Main.class file.

Use Packages

It is recommend to use packages.
create a package (mkdir mypackage)
Java conventions says package names is always lowercase and have no special characters.
move Main.java into the package

mv Main.java mypackage/

Now compile (you are still in src)

javac mypackage/Main.java

You can run the program with 2 Ways

cd mypackage
java Main

Or back in folder src we have to set the classpath (-cp)

java -cp mypackage Main

Set output folder

delete mypackage/Main.class

javac -d ../bin mypackage/Main.java

Now the Main.class file should be in bin folder.
Run the program

cd ../bin
java Main

Or go to project folder and call the Main with classpath

cd ..
java -cp bin Main

Set CLASSPATH

Programmers are lazy so set the classpath.
To view the classpath type

echo $CLASSPATH

If the output is Nothing then the variable isn’t set.
ensure that you are in project folder

export CLASSPATH=./bin

Now you can start the program from here with

java Main

Install JUnit

Download newest version from https://github.com/KentBeck/junit/downloads
Copy the download junit.jar file to your lib folder.
Add the jar to CLASSPATH

export CLASSPATH=$CLASSPATH:./lib/junit-4.9b2.jar

Test wether you reach the JUnitCore class

java org.junit.runner.JUnitCore

You should see something like this.

JUnit version 4.9b2
Time: 0,001
OK (0 tests)

For more information take a look at http://junit.sourceforge.net/doc/faq/faq.htm#started_2

Write a Simple Test

Go to test folder and create a Class SimpleTest with the following content

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
 
public class SimpleTest{
    @Test
    public void testEmptyCollection(){
        Collection collection = new ArrayList();
        assertTrue(collection.isEmpty());
    }   
}

Go back to project folder, compile and run the test.

cd ..
javac -d bin test/SimpleTest.java
java org.junit.runner.JUnitCore SimpleTest

Should be output

JUnit version 4.9b2
.
Time: 0,006
 
OK (1 test)

Annotation

The example SimpleTest.java is taken from http://junit.sourceforge.net/doc/faq/faq.htm#started_2

The Cost of Testing or You don’t Know what You are Missing

The Cost of Testing or You don’t Know what You are Missing

Twice this week people challenged my belief in automated testing and Test Driven Development. The argument that was brought forward was simply: Unit tests are too expensive.

I actually believe the opposite is true. Let me tell you about a little dialog that happened in my development team after two developer where working on a feature for about an hour or two.

First Developer: “I think we got everything. Lets start the application and see if it works.” (starts the application)

Second Developer: “Hmm, doesn’t work.”

First: “Oh, I know, we forget to actually invoke the new feature” (fixes that and restarts the application)

Second: “Looks great. It works. Lets commit it to SVN”

What’s so special about this? They didn’t start the application a single time during the development process for over an hour. Can you do that without writing tests? Of course you can and you will spend restarting the application during the rest of the day until you fixed all the bugs. How long does your application need to restart? Including the time you need to navigate to the state where you can test your application. How long does that take?

Not having to do that. Or at least not very often is a huge time saver. And it’s not only the direct cost of restarting the application. Waiting for the application is often an interruption of your concentration. Do you really think about the next aspect of the feature to implement? Or do you check mail? Get a coffee? In my experience going Test Driven in Pairs is a way more concentrated type of working.

And that is not even considering that your tests will run over and over again, making sure later changes don’t break anything. This alone saved my butt a couple of times.

If you reached that level of TDD it will save money for you and your team. I promise.

But I’ll admit, I didn’t believed that a couple of years ago. I was using tests only when implementing rather abstract stuff. And I thought it wouldn’t be possible to efficiently automate tests for most of the code we wrote. I had to learn a lot. Testing isn’t easy. Most of the code we produce isn’t fizz buzz, but is concerned with GUIs and databases, both make testing hard and expensive. But these problems can be solved, so you can gain the benefit of TDD even for these cases.

And as a side effect you will have to come up with a really nice and clean design of your code in order to test it. This in itself will make future changes more easy and cheap.

Therefore I urge you: Start learning how to test today. If you don’t you will never know what you are missing.

And if promises don’t motivate you: I’m convinced that in a couple of years from now the places where you can just puke code into your IDE will get rare. So if you still have a couple of years to cover until retirement: Beef up your testing skills. It’s one of the best investments you can make in your own future as a software developer.

via Schauderhaft » The Cost of Testing or You don’t Know what You are Missing.

JUnit 4 Tutorial

Nachdem Junit 4 in eclipse eingebunden wurde kann es benutzt werden, um Methoden automatisiert zu testen.

Eine einfache Klasse mit einer sehr einfachen Methode.
BasicArithmetics – Klasse.

package ingoreschke;
 
public class BasicArithmetics {
	/*Just a method to calculate the sum of 2 ints*/
	public static int sumInt(int val1, int val2){
		return val1 + val2;
	}
}

Die statische Methode sumInt(int val1, int val2) der Klasse soll 2 beliebige int Werte addieren.
Ob diese Methode korrekt funktioniert muß getestet werden.
7 = 3+4;
Erwartet wird, wenn der Methode 3, und 4 übergeben wird, dass sie 7 zurückliefert.
Nun die Testklasse und Testmethode dazu.
BasicArithmeticTest

package ingoreschke;
 
import org.junit.Assert;
import org.junit.Test;
 
public class BasicArithemticsTest {
	/*test whether the method sumInt() calculates the sum of 3+4=7*/
	@Test
	public void testSumInt(){
		Assert.assertEquals("Result of Sum", 7, BasicArithmetics.sumInt(3, 4) );
	}
}

Um den JUnit Test durchzuführen

  • rechte Maustaste auf die Testklasse (BasicArithmeticsTest)
  • Run As wählen
  • JUnit Test

In der JUnit View sollte so etwa zu sehen sein.

Grün = Test bestanden.

Nun erweitern wir die BasicArithmetic – Klasse um eine Methode die 2 int Werte differenziert.
Da die Differenz 2er natürlicher Zahlen auch gebrochene Zahlen hervorbringen kann geben wir double zurück.

/*Just calculate the difference between 2 ints*/
public static double diffInt(int val1, int val2){
	return val1/val2;			
}

Eine Testmethode dazu 5=10/2;

 /*test the method diffInt() */
@Test
public void testDiffInt(){
	Assert.assertEquals("Difference between 10 and 2", 5, BasicArithmetics.diffInt(10, 2),1);
}

Dies ist einfach und sollte auch mit grün druchlaufen.
Da auch gebrochene Zahlen entstehen können wird auch das getestet.

@Test
public void testDiffInt2(){
	Assert.assertEquals("Difference between 9 and 2", 4.5, BasicArithmetics.diffInt(9, 2),1);
}

Diese Methode wird auch mit Grün = Bestanden quittiert.
Hier sehen wir nun schon den Vorteil von automatisierten Tests gegenüber der “standard main – Methode.Wo manuell das Ergebniss kontrolliert werden muß. Diese JUnit tests können beliebig of durchgeführt werden.

Um gute Tests zu schreiben gehört es dazu, so genannte Bad Tests zu schreiben.
D.h. Ein Test gilt als bestanden wenn die zu testene Methoden einen vorhergesagten Fehler schmeißt.
In unseren Beispiel bei der Division durch 0.

@Test
public void testDiffInt3(){
	BasicArithmetics.diffInt(10,0);
}

schlägt also wie erwartet Fehl (Rot).
Im Fehler Trace – View kann man übrigens den Stacktrace sehen.

Damit der Test als bestanden gilt muß der Testmethode gesagt werden das wir diese Exception erwarten.
Dies tut man in der Annotation
@Test(expected = ArithmeticException.class)

@Test(expected = ArithmeticException.class)
	public void testDiffInt3(){
		BasicArithmetics.diffInt(10,0);
	}

Nun ist auch dieser Test bestanden.

Hier nochmal der komplette Sourcecode
BasicArithmetics

package ingoreschke;
 
import javax.print.attribute.standard.Finishings;
 
public class BasicArithmetics {
 
	/*Just a method to calculate the sum of 2 ints*/
	public static int sumInt(int val1, int val2){
		return val1 + val2;
	}
 
	/*Just calculate the difference between 2 ints*/
	public static double diffInt(int val1, int val2){
		return val1/val2;			
	}
}

BasicArithmeticsTest.java

package ingoreschke;
 
import org.junit.Assert;
import org.junit.Test;
 
public class BasicArithemticsTest {
 
	/*test whether the method sumInt() calculates the sum of 3+4=7*/
	@Test
	public void testSumInt(){
		Assert.assertEquals("Result of Sum", 7, BasicArithmetics.sumInt(3, 4) );
	}
	/*test the method diffInt() */
	@Test
	public void testDiffInt(){
		Assert.assertEquals("Difference between 10 and 2", 5, BasicArithmetics.diffInt(10, 2),1);
	}
 
	@Test
	public void testDiffInt2(){
		Assert.assertEquals("Difference between 9 and 2", 4.5, BasicArithmetics.diffInt(9, 2),1);
	}
	@Test(expected = ArithmeticException.class)
	public void testDiffInt3(){
		BasicArithmetics.diffInt(10,0);
	}
}

sourcecode als zip – Datei

weiterführende Links:

JUnit in eclipse aktivieren

JUnit ist bei einer Standardinstallation für Javaentwickler schon mit an board. Will man es benutzen so muß man nur die Libary in den Buildpath importieren.

Also

  • rechte Maustaste auf den Projektordner
  • Properties auswählen (ALT Enter)
  • linke Maustaste auf Java Build Path
  • Reiter Libraries auswählen

  • linke Maustaste auf Add Library

  • JUnit auswählen
  • und im darauf folgenden Fenster JUnit Version auswählen

  • Finish drücken
  • ok drücken

Jetzt sollte die JUnit 4 Library eingebunden sein.