Tag Archives: IntelliJ

Whoops! IntelliJ broke my JAAS config…

One of IntelliJ’s features is maintenance of copyright headers in source and text files. The update of the header can be selected to run upon commit (so that your commited code always has the latest copyright!).

/*
* SomeClass.java - 11 Nov 2010
* Copyright (c) 2010 - My Organisation
*/

Kind of cool and useful depending on your coding standards.

I’m updating a module of ours that uses Java Authentication and Authorization service (JAAS) to hook into LDAP.

The JAAS configuration file, unlike most properties and config files, uses Java-style block comments (such as the example above), and not hash comments. IntelliJ has recognized my jaas.config as a properties file, and upon committing to source control, inserts the copyright as a hash-comment block:

#
# jaas.test.config - 11 Nov 2010
# Copyright (c) 2010 - My Organisation
#

The result – My tests fail because JAAS config loader throws an exception!

Solutions?

I hoped that I could somehow indicate that a JAAS config file should be matched to the same style used in Java files.

I can set up a file type for the file easily enough:

But I can’t find a way to apply a copyright template to the file type…damn! The copyright templates seem static.

We could, in theory, apply one of those static file types to out JAAS config file; Add “jaas*.config” to Java or Javascript file types – but you’d have to be willing to put up with the errors and warnings!

For now, using the custom file type will do – IntelliJ doesn’t modify the copyright since it doesn’t know what the file is anymore. At least it won’t update to the wrong format by accident this way..!

Building a simple project using behavior-driven development with JBehave

IMPORTANT!
This post has moved to http://blog.brasskazoo.com!

In a previous post introducing BDD I outlined a simple bus ticket application. Since then I’ve been looking at JBehave, and thought I’d try building a simple version of the bus tickets project, using JBehave to support behavior-driven development of the application.

About JBehave

JBehave is a testing framework that takes the BDD concepts and applies it to JUnit tests, so you can effectively test your acceptance criteria directly using automated unit tests.

It uses BDD acceptance criteria as steps in a test case, and each Given/When/Then statement is interpreted and executed as a method. The acceptance criteria is simply stored in a text file which is read by JBehave when the test case is run.

Setting up JBehave

Download the distribution jars from http://jbehave.org (at the time of writing, version 2.3.2 is the latest), and extract it to a convenient location!

Set up references to the jars in your project (you need to reference at least hamcrest, junit-dep and jbehave-core for this example to work).

New project: ‘bus-tix’

For the purposes of this example, I’m creating a project I’ll call ‘bus-tix’, with production and test code packages.

The scenarios

Lets take one of the scenarios from my previous post (slightly modified):

Scenario: Inserting initial coins

Given that the application is operating
When a coin is inserted
Then ensure the time indicator displays the purchased time

I will use this as the behavioural spec for the initial work on the application. From the description of the scenario, we can instantly tell that we’re going to need a coin handler and time indicator as part of the application.

Now before I put this into a text file, I must point out that the default configuration of JBehave requires that the scenario files are named to match the class names of the test case – so if we had the test case InsertingInitialCoins, then the scenario text file must be named inserting_initial_coins (with no extension). I don’t particularly like this, so as you’ll see I modify the constructor so that I can call my scenario ‘inserting_initial_coins.scenario‘, to make it clear the purpose of the file.

We’ll need to create a test case, which extends org.jbehave.scenario.Scenario, and a ‘step’ class which extends  org.jbehave.scenario.steps.Steps. The step class will contain all the corresponding steps for the scenario file(s).

Scenario: Inserting initial coins

Given that the application is operating
 When a coin is inserted
 Then ensure the time indicator displays the purchased time

Create the test case class InsertingInitialCoins

package com.brass.bustix;

import org.jbehave.scenario.PropertyBasedConfiguration;
import org.jbehave.scenario.Scenario;
import org.jbehave.scenario.parser.ClasspathScenarioDefiner;
import org.jbehave.scenario.parser.PatternScenarioParser;
import org.jbehave.scenario.parser.ScenarioDefiner;
import org.jbehave.scenario.parser.UnderscoredCamelCaseResolver;

public class InsertingInitialCoins extends Scenario {
    public InsertingInitialCoins() {
        this(Thread.currentThread().getContextClassLoader());
    }

    public InsertingInitialCoins(final ClassLoader classLoader) {
        super(new PropertyBasedConfiguration() {
            public ScenarioDefiner forDefiningScenarios() {
                return new ClasspathScenarioDefiner(
                    new UnderscoredCamelCaseResolver(".scenario"),
                    new PatternScenarioParser(this), classLoader);
                }
            }, new BustixSteps());
        }
    }

The default constructor calls the custom scenario file loader, so that we can append ‘.scenario’ to your scenario files. If I were creating several of these test scenarios, I would pull all that up to an abstract class to avoid re-writing those constructors.

Steps class (empty for now):

package com.brass.bustix;

import static org.jbehave.Ensure.ensureThat;
import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class BustixSteps extends Steps {
    // TODO – fill in steps
}

Make sure that the .scenario file is copied to your compile directory! Otherwise you will get the error like:

org.jbehave.scenario.errors.ScenarioNotFoundException: Scenario com/brass/bustix/inserting_initial_coins.scenario could not be found by classloader sun.misc.Launcher$AppClassLoader@133056f

When you run the test for the first time, you will see this output:

Scenario: Inserting initial coins
Given that the application is operating (PENDING)
When a coin is inserted (PENDING)
Then ensure the time indicator displays the purchased time (PENDING)

Perhaps confusingly, the test has passed despite the steps not being executed – PENDING means that the step hasn’t been executed because no corresponding method has been found.

Defining Steps

JBehave uses annotations to mark a method as a particular step. The annotation is the first word of the step we’re using, with the rest of the text as a parameter to that annotation. So for our first step ‘Given that the application is operating’ we reformat it as an @Given annotation:

@Given(“that the application is operating”)

And then JBehave knows that the function following that annotation is what needs to be executed for that step.

So now in BustixSteps we add:

@Given(“that the application is operating”)
public void startApplication() {
    ensureThat(false);
}

The assertion statement ensures that the test will fail – an empty test will pass (as it usually does with JUnit). The ‘ensureThat’ function comes from JBehave’s wrapping of hamcrest matchers – an interesting alternative to Junit’s assert statements. I won’t go into them right now.

Rerunning the test, we get the failure we want!

Scenario: Inserting initial coins
Given that the application is operating (FAILED)
 When a coin is inserted (PENDING)
 Then ensure the time indicator displays the purchased time (PENDING)

java.lang.AssertionError:
Expected: is <true>
got: <false>
...

Lets fill in the rest of the steps for this scenario while we’re here:

package com.brass.bustix;

import static org.jbehave.Ensure.ensureThat;
import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;

public class BustixSteps extends Steps {

    @Given("that the application is operating")
        public void startApplication() {
        ensureThat(false);
    }

    @When("a coin is inserted")
    public void insertCoin() {
        ensureThat(false);
    }

    @Then("ensure the time indicator displays the purchased time")
    public void testThatTimeIsDisplayed() {
        ensureThat(false);
    }
}

At this stage, we’ve got our steps outlined for our basic scenario, and we can begin the test-driven  development of the application!

Note: when you have a scenario step that begins with an ‘And’, it is still considered as one of given/when/then, e.g.

Given that the application is operating
  And the time indicator displays nothing

..are both @Given annotations.

Next: check out the hamcrest matchers to make sure you’re getting the full potential from your asserts!

References

Getting started with Android in IntelliJ 9

JetBrains currently has a milstone release, version 9 of their awesome IDE IntelliJ. One of the included features is support for Google’s Andriod mobile platform.

I’ve been a big fan of JetBrains’ products for a long time, especially their TeamCity build server…but more on that later!

To get started on Android development, head over to Google and download the SDK (version 1.6 at time of writing). Extract it to a location of your choice!

New Project

Create a new project in IntelliJ, selecting an Android module and give it an appropriate name.

Module Types

Module Types

On the next screen, the default os to create a ‘hello world’ activity. The default package is com.example, which you’ll want to change for future projects (I’ve yet to track down where it is set in the preferences..).

The hello world activity is a useful starting block when learning how the basic Android components work, or just starting a new Android project, since it will set up the basics for you.

You’ll also need to set up the Android SDK against the project in the top section, add and browse to the location of your downloaded SDK. I suggest setting the platform level to Android 1.6 (you’re able to select 1.5 or Google APIs as the platform  if you wish. Google APIs gives you some extra functionality such as the Maps external library).

The generated project structure looks a little like this:

'Hello World!' Project

'Hello World!' Project

The R.java class is auto-generated each time you build the project. It contains references to the resource files in your project, contained under the res directory.

It is not intended to edited (any changes you make would be overwritten on the next compile).

The resources directory, res, contains all the non-java resources that make up you application, including image and string resources, layout definitions and other configuration xml files.

For example, main.xml under the layout directory contains an xml definition of the screen layout. Pretty simple really, just a layout container and a text label (see xml below). The TextView element specifies its text attribute as “@string/hello” – a reference to strings.xml, and the value of the hello element.

The java file MyActivity contains just enough code to tell the application to write the contents of main.xml to the screen.

main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
    <TextView
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/hello"
     />
</LinearLayout>

strings.xml:

<resources>
 <string name="hello">Hello World, Lop!</string>
 <string name="app_name"></string>
</resources>

Android AVD

To run your shiny new application, you have to set up a virtual device to run it on.

The SDK prvides a tool – <SDK>/tools/android – that works as a GUI and command line interface to manage devices.

You can manage the devices through IntelliJ also – edit the run configuration (which was automatically generated for you), and click the ellipses to the right of the drop-down.

Side-by-side: IntelliJ's configuration screen and Google's AVD utility

Side-by-side: IntelliJ's configuration screen and Google's AVD utility

I prefer to use the Google utility, because I find the AVD will take a minute or two to start up, and so I’ll launch it when I open my project, not when I want to run my application the first time.

Running..

Once your AVD is configured and running, you should be able to launch your application, and see your friendly message!

Your running application!

Your running application!

Next..

Check out some of the tutorials in the developer guide of other basic components that are available.

And also, read the application fundamentals to get your head around the Android architecture!

References:

Developing Android applications in maia

Google Developer GuideHello World example