Tuesday 23 August 2011

Writing to a properties file with Ant

I find this useful when I want to change how the application works depending on where and why it is being deployed. This blog post assumes you have Ant installed!

In the build.xml file;

<!-- Add the property file -->
<property file="project.properties"/>

<!--  Write a property to the file with a value based on the target -->
<target name="liveExample">
     <echo message="This target example has the live properties"/>
     <propertyfile
          file="project.properties"
          comment="Setting important system procedure variable to 100">
          <entry key="importantVariable" value="100"/>
          </propertyfile>
</target>

<target name="testExample">
     <echo message="This target example has the test properties"/>
     <propertyfile
          file="project.properties"
          comment="Setting important system procedure variable to 10 for testing purposes">
          <entry key="importantVariable" value="10"/>
          </propertyfile>
</target>

How it works

The properties file (project.properties) has a key/value pair written to it. Based on what target is run, the key has a different value. This allows us to control how the application works based on how we deploy it. For further reading on Ant's PropertyFile task see their manual.

Thursday 18 August 2011

Writing a unit test using JUnit

To do JUnit tests on your code you first need to include the JUnit libraries which can be retrieved from the JUnit web site (licensed under GNU).

Now you can create your test files. These should be created in the test packages package folder to keep them separate from the actual project code.

package yourprojects.somepackage;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class ExampleTest {

    // Create objects needed to perform the test i.e. mock objects
    private static ObjectToTest testObject;

    @BeforeClass
    public static void setUpClass() throws ConnectionException, SQLException {
        testObject = new ObjectToTest(); // Initialise object to test
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        // Any connections made (e.g. such as database) should be closed here
    }

    @Test
    public void testSomeMethod() throws ForumException {
        assertTrue(testObject.someMethod());
        assertIsEmpty(testObject.someMethod());
        assertNotNull(testObject.someMethod());
        assertEquals(true, testObject.someMethod());
        assertSame(new ObjectToTest(), testObject.someMethod());
    }

}

How it works

This class is testing a method (someMethod) in an object (ObjectToTest).

We start off by including all the JUnit libraries we need for the tests.

We then override the setUpClass and tearDownClass methods which organise the test environment for us. In the set up class we initialise the mock objects we need to test. In the tear down class method we close any connections we made during the testing.

Then we write the tests; I typically write one test for each result I expect e.g. testAMethodWithNullArguement(). Keeping the test methods separate makes it clearer what has failed.

The test method in the above example lists many of the more common assert methods I use depending on what kind of output I am expecting from the method being tested.

Wednesday 17 August 2011

Writing a web unit test using JWebUnit

Firstly, you will need to include the JWebUnit library in your Java project which is available to download (and is licensed under the GNU) here. You will also need the JUnit libraries as JWebUnit is built upon it which can be downloaded here (also under the GNU license).

Then in your test packages create the web test file. I recommend putting the web test file(s) in a web test package to separate them from any JUnit test files you may also have in your test packages.

package yourproject.webtest;

import net.sourceforge.jwebunit.junit.WebTestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class WebUnitExample extends WebTestCase {

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        // set up where JWebUnit should look
        setBaseUrl("http://localhost");
        beginAt("/webapp/thenameofyourproject/");
    }

    @After
    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Test
    public void testAFeatureOfYourProject() {
        System.out.println("Testing a feature of the project");
        // Add some method calls to the JWebUnit API here then call asserts to see if
        // the output is correct      
    }

}

How it works

As you can see this file is very incomplete and will not do anything at the moment but for this example that doesn't matter!

setUp and tearDown are important methods as you can set up what is needed before each test and obviously, 'tear down' i.e. remove those conditions after.

As for the tests themselves, JWebUnit has many methods that can be used to traverse the page (e.g. clickButton, clickLink) and methods to manipulate page elements (e.g. setTextField, selectOption). Just as in JUnit, asserts are used to check that things are how they should be. For a list of JWebUnit methods see their API listings.

Wednesday 3 August 2011

Using ResourceBundle

I use ResourceBundles to hold my project's properties so that I can make widespread changes to the project by changing only one value.

Examples of what I may use this for could be the project name, email address, directory structures etc. I would not use ResourceBundlesfor constants.

Below is a code example;

File: project.properties
projectName=AnExampleProject

File: Properties.java
package example.properties;
import java.util.ResourceBundle;

public class Properties {
  
   private static ResourceBundle rb = ResourceBundle.getBundle("example.properties.project");

   public static String getProjectName() {
     return rb.getString("projectName");
   }
}

How it works

All properties are put into a .properties file which can be retrieved using ResourceBundle's API. We get a ResourceBundle object by using the ResourceBundle method getBundle, using the path to the properties file as a parameter. With that object, we can then retrieve the properties using the getString method (other types are also available e.g. getInt).

The methods are made static so the properties can be retrieved without instantiating the Properties class every time.

The project name would be retrieved using Properties.getProjectName();

Tuesday 2 August 2011

MySQL NOT IN query

I had to do this today to find all references that did not appear in a table. Here's a basic example;

SELECT player_id FROM tbl_player WHERE player_id NOT IN (SELECT player_ref FROM tbl_team);

How it works

The above example retrieves a list of all the players (player_ids) that do not appear in the team table (tbl_team) using the reference (player_ref).