Rage Against the Android – Nearly solved! #eclipse #netbeans

After ranting against Android in my previous post I have mainly solved now the untestable situation Android is producing.

Thanks to Robolectric all my tests are finally fast and do not unpredictable hang or similar!

The tests execute nearly as fast as in a normal Maven project – plus additional 2 seconds to bootstrap (dex?). Robolectric was initially made for maven integration on IntelliJ. But it works without Maven and under Eclipse as described here. I didn’t get robolectric working via Maven under Eclipse – and it was overly complex e.g. you’ll need an android maven bridge but when you use a normal Android project and a separate Java projects for the tests then it works surprisingly well for Eclipse.

Things you should keep in mind for Eclipse:

  • Eclipse and Robolectric description here
  • In both projects put local.properties with sdk.dir=/path/to/android-sdk
  • Android dependencies should come last for the test project as well as in the pom.xml for the maven integration (see below)

But now even better: when you are doing your setup via Maven you can use NetBeans! Without any plugin – so even in the latest NetBeans version. But how is the setup done for Maven? Read this! After this you only need to open the project with NetBeans (or IntelliJ).

Things you should keep in mind for Maven and NetBeans:

  • Use Maven >= 3.0.3
  • Again: put the android dependencies last!
  • Specify the sdk path via bashrc, pom.xml or put it into your settings.xml ! Sometimes this was not sufficient in NetBeans – then I used ANDROID_HOME=xy in my actions
  • Make sure “compile on save” is disabled for tests too, as I got sometimes strange exceptions
  • deployment to device can be done to:
    mvn -DskipTests=true clean install      # produce apk in target or use -Dandroid.file=myApp.apk in the next step
    mvn -Dandroid.device=usb android:deploy # use it
    mvn android:run
  • If you don’t have a the Android plugin for NetBeans just use ‘adb logcat | grep something’ for your UI to the logs

Thats it. Back to hacking and Android TDD!

Test-Driven Teaching – 4. User Interface / 5. More Game Features

This post belongs to some previous posts of this tutorial about “test-driven teaching”:

0. Overview article

1. Hello World

2. Initial Box Game

3. Object Oriented Programming – Refactoring!

Now will go on with the last two sections.

In Section 4

you can learn a bit how to code with Swing and how to draw lines etc. with the Graphics class. This section can be securely skipped.

It is only necessary for the reader to have fun; not to get lost in Swing development. Get the project under the following URL


The handling and painting will be improved a bit in the next section.

In Section 5

you will learn

  • Why and how to use inheritance
  • the keyword this
  • the switch-case construct

Get the project under the following URL


Let us examine the project. If you run it you will get a window with several black boxes and two colored one. The red is the enemy and the other could be controlled by the arrow keys (up, down, left, right) … its you. Try to capture the enemy like it is shown below:

There are some new classes and one interface called ‘Item’. Let me first explain the reason why I introduced a new Board class and then why we need this Item interface. Superclasses (and sub-classes) and also interfaces are directly supported in Java with its related keywords extends and interface, although you could write in an object oriented way even without native support of the language (e.g. in C), but this is for another topic…

Board Class

Instead of the borders I am using one object of the class Board where the different items will have its positions (of course there are other solutions to store different items at different positions, try thinking about them; email me if you think that you found one). Within the Board class a 2-dimensional array is used to hold all the objects at different locations. We need to duplicate the information of the position (x,y) within the Man class not only within the Board class, because this way the Board class does not need to know how to paint the different items: it just calls item.paintComponent().

Another change was to remove the move method from the Man class and put it into Board, because moving now does not only mean to change the position, it is necessary to check if the new position is empty etc.

Item Interface

As you can see in the project an interface has actual no function, it only provides a contract of methods (and static fields) which all classes should implement and other classes could rely on. A class can implement several interfaces via the implements keyword.

All objects implementing the interface ‘Item’ (here Man and Block) can be placed on the board.

I introduced the interface to avoid sth. like:

if(item instanceof Block) {
 drawTheBlockThisWay((Block) item, g);
} else if(item instanceof Man) {
 drawManThatWay((Man) item, g);

instead the Board class just needs:


And as explained earlier the additional setters/getters for x and y are necessary within the paintComponent of each item: “the man or the block must know its position to draw itself”.


To avoid re-implementing the “x and y”-functionality for every Item-implementation again and again, I chose to write a common super class called ItemImpl which provides this functionality for all Item subclasses. Look into the code to understand that now the variables x and y are available in the Man and Block class although they do not declare them directly. This leads to less duplicated code. This extension mechanism is called inheritance.

Note three things here:

  1. Not always the object oriented way is the golden way, e.g. in this case it leads to more classes and could lead to more problems in other areas (e.g. database schemas).
  2. Testing the class ItemImpl is ok, but not necessary as I think: “Test only what will go wrong or what went wrong”. In this case we only have to getters and setters – all should be fine.
  3. Inheritance should be avoided where composition or sometimes delegating could be used.

This, Switch and More

Some setter-methods use the this keyword. E.g. in the setX method of ItemImpl it is necessary to distinguish between the method parameter x and the local variable this.x. The keyword this means that you want to refer to the current object. You could also refer explicitly to the super class’ methods or variables via the keyword super: ‘super.someMethod()’

Now look at the code in the BlockGameSwing class (method Thread.run) there I used the switch-case construct. Instead of several if-then-else statements I prefer using this construct if the type is integer or char. Please look in the class SwitchCaseTest under the test package to get the exact syntax and to directly compare with an if-then-else statement.

Two side-notes:

Future Tasks

The open task will be to decrease the energy if the man is colliding with an enemy.

  1. Introduce the energy variable within the BlockMan class and
  2. Uncomment the line with the energy in the method paintComponent of the BlockGameSwing class
  3. Additionally you should introduce movable blocks to catch the enemy without loosing energy

Other important concepts that are not covered in this tutorial:

In this section you have learned a lot of things. Maybe not as good explained as elsewhere, but with unit testing 😉 And please comment on this post to show where more explaination should be added!

If you like programming ‘the man’ you will love programming a robot. Warning: within the robocode project is very difficult to write unit-tested code. Although there exist other approaches to test a robot, I think the unit-testing would be very important.

Test-Driven Teaching – 3. Object Oriented Programming


In the previous sections we learned how to create a simple Java program and tested it. We mainly did procedural programming, while now we will learn how to better encapsulate functionality and data with the help of object oriented programming (OOP). The aim of OOP is mainly to provide better code re-use than it would be the case with procedural programming. With OOP it is easier to write large software and personally I think, it leads to better readable code.

A nice introduction to OOP with Java could be given via:

An object is a self-contained entity which has its own collection of properties (ie. data) and methods (ie. operations) that encapsulate functionality into a reusable and dynamically loaded structure. After a class definition has been created as a prototype, it can be used as a template for creating new subclasses (via extends keyword) that add functionality. … Applications can request new objects of a particular class on demand via the new keyword.

What you will learn in this section:

  • Get closer to object oriented programming
    • we don’t want static methods and variables
    • we don’t need a reset method for different tests
    • we don’t want public properties
    • private, public, protected and package access
    • different comparison mechanisms in Java
  • IDE:
    • Refactor: rename
    • Diff-tool to compare these versions
    • refactor public field to private and create getter
  • Explain via tests:
    • references (aka pointers) compared to values
    • loops

Get Started

So check out the previous example at the following URL with subversion:


Open it in your favourite IDE and we will now apply some necessary refactorings (code changes) to transform a procedural program into a more object oriented one.

Refactoring (static)

What is refactoring? Code refactoring means code changes, which have the aim to make the code better readable or introduce a cleaner design. But refactoring does not change how the applications works.

First: let us get rid of the static keyword:

  1. Rename the InitialBlockGame class to BlockMan, for that you have to rename the file name too. This procedure is very easy with an IDE. In NetBeans just place your cursor under the class name right click->Refactor->Rename or just press CTRL R
  2. Remove the static keyword from all occurences of the BlockMan class, except from the main(String[]) method
  3. Remove the entire reset() method. We don’t need it, because we simple create a new object for every test
  4. The line with ‘BlockMan.start();’ should be replaced with
    BlockMan man1 = new BlockMan();

    or with a shorter version:

    new BlockMan().start();
  5. Now we need to refactor the test cases and after the test compiles, it should pass as well. This shows one advantage and one disadvantage of test-driven development: you have to refactor all tests after refactoring which costs some time, but at the same time you can run those tests and make sure that all works as before.

Instead of calling the static start method of the BlockMan class we can now create a BlockMan object and invoke the start method of this object. Now it is simple to create and manage not only one man but several men:

BlockMan man1 = new BlockMan();
man1.move(0, 1);
BlockMan man2 = new BlockMan();
man2.move(0, 2);

The first man man1 is located after this operation at x=0 and y=1 (0; 1) but man2 is located at a different location (0; 2) after the move method call.

We should have added a test case before some code. So here it is:

BlockMan man1 = new BlockMan();
BlockMan man2 = new BlockMan();

man1.move(0, 1);
man2.move(0, 2);

assertEquals(1, man1.y);
assertEquals(2, man2.y);

man2.move(0, 2);

assertEquals(1, man1.y);
assertEquals(4, man2.y);

(A good but not ideal comparison of Class/Object in the real world: A class could be compared to a rubber stamp and an object to the resulting images on the paper.)

Access Modifier

Additionally we should change the public access of the x and y variable. What does access mean? We learned in the previous post that we can use variables like x only in its block and sub-blocks, where it was defined. Now we used public before the variable declaration so that we can access (or ‘see’) the variable from all external code, which is called world in the following table. A short overview of this can be given:

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no keyword == package access
private Y N N N

This table was taken from sun, where you can get more information about this topic.

With public acces we can retrieve y (the same is true for x)

assertEquals(1, man1.y);

and even initialize y:

man1.x = -100;

This is not good in the most cases and as you see here: the y value is not in its correct domain [0; 10). External code could change the variables without knowing the bounds or sth. else. E.g. the move-method is a better approach to change the variables x and y.

So, just make all variables private and provide public methods to manage initialization and retrieval of such a variable via setter and getter. Instead ‘public int x;’ you should do:

 private int x;

 // the getter is used for the retrieval
 public int getX() {
   return x;

 // the setter is used for the initialization
 public void setX(int someX) {
   x = someX;

Now you can simply remove the setX method and ‘external code’ is not able to change x without the appropriate move method.

The x and y variables are sometimes called properties. To create such property-access-methods (getter and setter) with NetBeans press ALT INS and select Generate ‘Getter and Setter…’

Compare Your Project

We are near the finish of refactoring so check out the code of this third section to compare your refactored code with my code:


More details on subversion was given in the second section.

To compare the files go to the Projects window and select both files (hold CTRL). Then right-click->Tools->Diff

You will notice that I introduced two methods too: moveX and moveY to make our class easier to use. Also the border values could be now accessed from outside via getBorderX and getBorderY

equals != ==

For Java exists different comparison operations. The first most obvious comparison with the == operator isn’t always the correct one, because this operator compares only the references stored in an variable. For that please look into the class DifferentComparisonTest and you will see the statements:

System.out.println(new MyHouseWithoutEquals("House1"));
System.out.println(new MyHouseWithoutEquals("House1"));

which results e.g. in


So it is obvious that the following will pass:

MyHouseWithoutEquals var1 = new MyHouseWithoutEquals("House1");
MyHouseWithoutEquals var2 = new MyHouseWithoutEquals("House1");
assertFalse(var1 == var2);

But even with the call of the equals method you won’t get happy:


Only if you implement the equals method correctly like it is done in the class MyHousWithEquals, then you can write the following

MyHouseWithEquals var3 = new MyHouseWithEquals("House1"); // instance1
MyHouseWithEquals var4 = new MyHouseWithEquals("House1"); // instance2


Keep in mind that also with a proper equals method the normal comparison would fail, because everytime the new operator is called a new object will be created!

assertFalse(var3 == var4);

Now I would like to show when the == operator is true and when the equals is false even if proper implemented:

MyHouseWithEquals var5 = var3;
MyHouseWithEquals var6 = new MyHouseWithEquals("House2"); // instance3
assertTrue(var3 == var5);

Please look at the following picture where some of the previous variables are listed. The picture represents a simplified, logical view of the ‘current RAM‘ (the order of the variables and instances is not important).

The difference between the comparison mechanisms is also important in unit tests. Sometimes you will use:

assertTrue(obj == anotherObj);

But most of the time you will use


or even better the assertEquals method which is already shipped by junit and which invokes the equals method under the hood:

assertEquals(obj, anotherObj);


  • If your IDE is clever it will mark the equals method of your MyHousWithEquals class, because if you override equals you will normally need to override hashCode for a proper functionality of some datastructures. Under NetBeans press ALT ENTER to fix this automatically.
  • There exists even more comparison mechanisms as you can read in the javadoc here and here. Those interfaces are important for sorted datastructures like TreeSet or TreeMap.

Look at Unit Tests

In the unit tests of the third example


the following things will be further explained:

  • Value vs. reference (‘pointers’) are explained in the ValueOrReferenceTest class
  • Loop constructs in the LoopExamples class


As the last important information I would like to say that object oriented programming is not the heaven of programming. Please keep in mind that every approach has its drawbacks.

For example I would not introduce a Point variable within the BlockMan class instead of the two variables x and y. Why? Hmmh .. I think it is more convenient to directly access the x or y instead of getPoint().x or getPoint().y.

Another drawback is that for every object some memory overhead is introduced. Not a lot and it does not always matter, but you should keep this in mind for later projects!

Test-Driven Teaching – 2. Initial Box Game

Now that you are a bit comfortable with your IDE and Java itself we will code the initial lines of the game in this tutorial.

What you will learn in this section:

  • Get the source code with subversion: ‘check out’
  • Variables of different type
  • Java methods with parameters
  • Variables with different visibility
  • Creating junit tests and run them
  • IDE:
    • debug the application
    • autocompletion
  • if-then-else constructs

Get The Project

This project won’t be available as zip file. You need to install a subversion client (e.g. TortoiseSVN for windows and KDESvn for linux) or use subversion in your IDE. For NetBeans go to the Team menu->Checkout…

Then type in the following url:


No login or password is required only specify the ‘Local Folder’ to match your needs. Open the project if NetBeans asks you. For some screenshots look here.

Right click the project->and click Test. The unit test window should pop up and all tests should pass (green).

Get The Knowledge

Open the class InitialBlockGame which is located under the package called de.tdtut.section2. Look around a bit. You might have already noticed in the first part that there are special characters which looks grey in NetBeans: the comments which do not effect the program execution.


int myVariable;

This is an integer variable, which can hold only integer values, such as 1,2, -3 etc. the maximal value is stored under Integer.MAX_VALUE. If you want to initialize a variable do:

myVariable = 3;

You can do declaration and initialization at the same time:

int myVariable = 3;

Now it is important that you look into the test case shipped with the second project to get a better understanding of the various types and possible operations. To run the test right click into the file and click ‘Test File’ or press CTRL F6.

Hint for later usage: If you create an additional Java class within the package via right click on the package->New->Java Class…, then you can easily generate a new test file for it: CTRL SHIFT U


You now know variables and comments but also note that there are blocks like the for-loop in the previous post defined by curly brackets:

public class InitialBlockGame {

and e.g. the method definition

public static void start() {

The first block is the definition of a class called InitialBlockGame and the second block is a method called start without a return type, so: void start(). There are also methods like move which requires method parameters.

Variables – Visibility/Access

If you declare a variable it will be accessible only from within that block and also sub-blocks. The following code fragment should illustrate this:

public class InitialBlockGame {
 public int x;
 public void start() {
   int test;
   // here we can use the test and x variables

 public void move(int dx, int dy) {
   // here we can use the x, dx, and dy variables
   // but not the test variable declared within the start() method

We cannot easily create a test case for this, because e.g. the usage of test within the move method wouldn’t compile at all! But in scripting language like Ruby or Groovy this could be done.

Another important approach to manage the access of variables or even methods via the public, protected and private keywords will be explained in the next section.


To debug a Java class right click into the file (e.g. InitialBlockGame) and click ‘Debug File’ or CTRL SHIFT F5. But before you should set a breakpoint e.g. on the line

Random rand = new Random(123);

Then go through the code step by step via F8. Investigate the value of the variable lifeCounter through holding the mouse over it.

Another approach is to open the Watches window via Window->Debugging->Watches and add lifeCounter to it (right click->New Watch…)


Simply press CTRL SPACE e.g. after ‘InitialBlockGame.’ and all variables and methods will be listed:

This makes it very easy and fast to learn and explore unknown code (e.g. a library). This is the most powerful command an IDE provides you compared to a simple text editor. Try to invoke this command (CTRL SPACE) within the class definition block or after you typed ‘int’ within a method to see what the IDE provides you to make development easier.

Another powerful command every IDE provides is CTRL mouseclick. E.g. try to click on the move method (hold CTRL while that) in the start method (line ~50) you will see that the IDE leads you to the move method declaration. Or click on ‘Random’ in the start method (line ~45) this will open the Random class automagically! The same will work with your own classes and method. Try clicking around 😉


If you look into the move method you will see some if-statements e.g.:

if (x + dx >= 0 && x + dx < 10)
 x = x + dx;

Where dx is the change of move in x-direction. If dx is now too large or too negative it won’t be applied.

Look into the test case testMove() to get a better understanding and play around a bit with the code.


Do not hesitate to comment below!

Test-Driven Teaching – 1. Hello World

The first part of this tutorial for beginners is the ordinary ‘Hello World’ example which won’t be tested. Hey why not? Because this simple example is only used to check if the set-up works.

What you will learn in this section:

  • Set-up of a simple Java project
  • IDE: run the application
  • Methods with parameters
  • for loop

The reader will learn how to set-up the example in his integrated development environment (IDE) of choice, build and run it. He will see that the ‘Hello World’ will be printed in the console output window of the IDE.

I will explain the set-up for NetBeans only. But there are other free and very powerful IDEs as well. E.g. Eclipse and IntelliJ Idea can be used as good alternatives.


As the very first step download and install the Java Development Kit (JDK) from Sun (not Java Runtime Environment = JRE). Then get the latest NetBeans here where the ‘Java SE’ package is sufficient.

Get the example as zip file here and extract it into your local folder using NetBeans:

Open the favourite window under Window->Favourites. Right click into this window and add the download folder (with the zip file) to favourites:

Expand the zip file (left triangle) and copy the folder via right click:

Then paste it where you like. Open the project via right click->Open Project ‘TestDrivenTeaching1’ or open it via File->Open Project…

All the code is free software and stands under the GPL v3.0. All sources are located under the src folder; all subfolders of this folder are equivalent to Java packages and are used to better organize your code. You will see the logical ‘Java package’-view on this project within the ‘Projects Window’ and the ‘ordinary folder’-view in the ‘Files Window’:

So look into the package de.tdtut.section1 to open the HelloWord class with double click:

Then click on ‘Run File’ or press SHIFT F6 within this HelloWorld file and you will see in the ‘Output Window’ sth. like:


Hello World



(The first and last statement are generated from NetBeans and should be ignored!)

Congrats for your first Java program!

If you compile the Java sourcecode, which is done by the IDE, it will generate bytecode (several files ending with .class). This bytecode could run on every operating system by the Java interpreter (java) and is automatically bundled to one jar file from your IDE. The Java interpreter creates plattform-specific machine code from the bytecode and extremely optimizes it.

Now more details how the Hello-Word-example works:

Under the hood the character-band (called String) “Hello World” will be passed as the single parameter to the method println (‘print line to standard output’) of the single object called ‘System.out’.

Every standalone Java application can be started outside of NetBeans e.g. from command line. Go to the folder of the project and type:

java -cp dist/TestDrivenTeaching.jar de.tdtut.section1.HelloWord

As output you should see ‘Hello World’ only. The last argument must be a class with the main method:

public static void main(String[] args)

Advanced Information

If you append some arguments on the command line e.g. via:

java -cp dist/TestDrivenTeaching.jar de.tdtut.section1.HelloWord arg1 arg2

You will see

Hello World

This is because of the for-loop, which looks into the list of strings and picks one after another.

for (String arg : args) {

This list is called array and was initialized from the command line arguments and has a static lenght, which cannot be changed afterwards. If you want to access one element of an array you can do this via args[0] and args[1]. Be sure that the number (called index) starts from 0 and goes only until args.length – 1. So if you want to have full control of the iteration use this version with an explicit counter of type int:

for (int i = 0; i < args.length; i++) {

The counter i is declared (and visible) only within the block of the for-loop. With the line

int i = 0;

i was declared and initialized with 0. After each step i will be incremented by one. The loop will execute its block only if the counter i is smaller than args.length.

If this part is a bit overwhelming for your head: no problem! Just try a bit around or go ahead to the next section!


Just try other things to get a deeper knowledge of Java! E.g. you could declare some other variables and print them or try to iterate in inverse order through the array args. The most important step to learn programming or a new programming language is to think what you want and try to implement this.

If you have problems, questions or suggestions, then do not hesitate to comment below!

Test-Driven Teaching!


0. This overview article

1. Hello World

2. Initial Box Game

3. Object Oriented Programming – Refactoring!

4. User Interface – Swing!

5. More Game Features


The idea of test-driven development (TDD) is not a new one and also the idea of test-driven teaching is not new (see also at springer or here).

The main idea is to write working code examples based on TDD for beginners. The students should then be able to code (unit) tests and to read them from the very beginning. Most people learned TDD some years after learning ‘programming itself’, although I think TDD is already part of every coding. Most programmers ‘code’ + ‘test’ + ‘bug fix’ + ‘test’ + etc. But with TDD you have the benefit that your tests can be executed later automatically and very fast, which ensures that early requirements are valid

  • even if the same programmer forgot them or
  • if several programmers working on the same project at the same time or also
  • if a programmer must resume the work of another one.

I won’t give a lot details of TDD here, but the main advantages of TDD are:

  • If applied correctly (=early!) you can often code faster with TDD
  • Later refactorings are much more faster and less error prone (!!)
  • Testable code is often ‘better’ code; in terms of readability and re-useability
  • You indirectly document the functionality
  • The (unit) tests can be used as feature request or bug reports

The ‘real’ development cycle for TDD is outlined at wikipedia. My subjective suggestion to you my fellow reader is:

  1. think and initial code
  2. think …
  3. test a little (write test)
  4. code a little
  5. test passed?
    • yes => repeat with 2. (if all other tests passed too)
    • no  => find the mistake and repeat with 4. or 3.

Within all steps refactoring could be involved.

Unit Test ‘Add-on’ to Normal Teaching

Additionally to the explanation what different primitive types in Java are, there will unit tests like the following:

public void testLongAndInteger() {
 // an important difference of a long value to an integer value is the range:
 int  expectedInt  = 2147483647;
 // L indicates a long value
 long expectedLong = 9223372036854775807L;
 assertEquals( expectedInt, Integer.MAX_VALUE);
 assertEquals(expectedLong, Long.MAX_VALUE);

 // here is the problem what happens to an integer variable which
 // exceeds its domain: increasing the maximal value will cause the
 // variable to be negative!
 int intVal = Integer.MAX_VALUE + 1;
 assertTrue(intVal < 0);

This simple tutorial will not replace a good old Java textbook e.g. the JavaInsel (German) or other, but could be used in parallel. It is a pity that even those big and great books do not teach such important hand toolings (TDD).

Newbies will learn more …

Other important learning steps should be involved while teaching a programming language:

  • Version control (subversion, bazaar, mercury, git, …)
  • IDE handling (run, debug, test, refactor, format, … )
  • Using external libraries or link to resource lists (e.g. this one)

So, how should we structure such a beginner course where test-driven development is involved?

As a beginner I would prefer a ‘real life’ project. We should develop an idea and implement this while teaching (with refactoring!). It should be an idea which does not require a lot of set-up or external resources (such as an internet connection, web app etc). And it should be either useful (sth. like a xml conversion tool), a game or sth. that looks nice.

In this tutorial we will implement a simple game with Swing as the graphical user interface (GUI) to make it visually more appealing than an ordinary console output. The Swing coding chapters should and can be skipped at the first time of reading. Although user interface code can be tested (e.g. with FEST) they won’t, because of the lack of time of myself. The game itself should look like this but actually won’t (again lack of time).

BTW: I’m the author of GraphHopper, a fast open source route planner