englishteeth.co.uk

… the weblog of Ian “English Teeth” Robinson
  • rss
  • Home

Autoboxing could catch you out

July 22, 2008 | 5:20 pm

A colleague pointed out an aspect of auto boxing in Java 5 that could catch you out. Which I have hopefully captured in the following contrived little unit test.

	@Test
	public void shouldTakeCareWithAutoBoxing() throws Exception {

		Map<String, Integer> myMap = new HashMap<String, Integer>();

		String letters = "Gotchas";
		Integer count = 0;

		myMap.put(letters, count);

		// count the letters
		for (int i = 0; i < letters.length(); i++) {
			count++;
		}

		assertSame(letters.length(), count);

		assertNotSame(letters.length(), myMap.get(letters));
		assertNotSame(count, myMap.get(letters));

	}

Auto boxing allows you to do seemingly convenient things, such as manipulate your Integer object like you would a primitive. However, Integers are immutable and what incrementing count is doing behind the scenes is referencing a new instance of an Integer with the updated value. Therefore count no longer references the object placed in the Map, that’s the old object…

Putting the each incremented value in the map would at least give you what you might be trying to achieve…

		// count the letters
		for (int i = 0; i < letters.length(); i++) {
			myMap.put(letters, ++count);
		}

		assertSame(letters.length(), count);
		assertSame(letters.length(), myMap.get(letters));
		assertSame(count, myMap.get(letters));

…but it’s not nice.

Following a quick google search I found Autoboxing Considered Harmful which provided an even more interesting aspect, which I have reproduced here as a simple JUnit test.

import org.junit.Test;
import static org.junit.Assert.*;

public class FurtherExperimentsInAutoBoxing {

	@Test
	public void twoObjectsWithTheSameValueShouldNotBeTheSame() throws Exception {

		Integer a1 = new Integer(150);
		Integer a2 = new Integer(150);

		assertNotSame(a1, a2);

	}

	@Test
	public void withAutoboxingTheyCanAppearToBe() throws Exception {

		Integer a1 = 100;
		Integer a2 = 100;

		assertSame(a1, a2);

	}

	@Test
	public void sometimesAnyway() throws Exception {

		Integer a1 = 150;
		Integer a2 = 150;

		assertNotSame(a1, a2);

	}

}

As the original author points out in his post, this is not the way you would want to write these, but for someone trying to grasp the concepts of what an object is and how to deal with them, these language features wouldn’t exactly help.

Comments
No Comments »
Categories
development
Tags
java, junit
Comments rss Comments rss
Trackback Trackback

Please test responsibly

April 24, 2008 | 12:57 pm

As my dentist is persistently asking me, “is it safe?”…

Having been asked to make some enhancements to an existing on-line application, I checked out the code from source control and made my way to the tests. Well you would wouldn’t you!

Selecting the root of the test source, I right clicked and selected run as JUnit test.

It was horrible; like a train crash or something.

After about an hour, I’d removed the errors my correcting path’s and references in the configuration. Unfortunately, I wasn’t in a position to address all the failures since I didn’t know what was bad tests and what was bad code. (Though since the application was live, with no outstanding bugs, it seemed reasonable to assume that the tests were stale.)

Within the tests I was disappointed, though not overly surprised, to find database dependencies to a database on some server. Luckily, the server and the database instance still existed, but I wasn’t really sure what it was used for.

A couple of days after tiding up the tests I was tracked down by team maintaining the mail servers. It appeared that the application I was looking into had been firing emails off to now defunct addresses that were collecting in their dead letter box.

Mixing unit and integration tests is not big and it’s not clever. Dependencies like these may seem reasonable to the developer in the heat of implementation, but they are not safe and make the subsequent support or enhancement of that software much more difficult.

Please test responsibly.

I’ve borrowed the Marathon Man image from this post from Freddo Fungus.

Comments
No Comments »
Categories
development
Tags
java, junit, testing
Comments rss Comments rss
Trackback Trackback

JUnit 4

March 11, 2008 | 12:23 pm

Not least because it is so much simpler, but regular usage will result in this will becoming ingrained, (this is covered in greater detail here), but being as I’m so used to the previous incarnations of JUnit it might be worth noting the usage for quick look-up…

package junit4;

import mypackage.ClassToTest;
import org.junit.Before;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;

public class MyJUnit4Test {

  private static ClassToTest classToTest = new ClassToTest();

  @Before
  public void whatUsedToBeInSetup() {
    // test set up type activities
  }

  @Test
  public void first() {
    classToTest.doWhatYouDo();
    assertEquals(classToTest.getWhatItDid(), result);
  }

  @Test(expected = SomeParticularException.class)
  public void shouldCauseExceptionInTestClass() {
    classToTest.doThatThingYouDontLike();
  }

  @Ignore("not ready yet")
  @Test
  public void multiply() {
    classToTest.doThatThingYouWillDo();
    assertEquals(classToTest.getWhatItDid(), futureResult);
  }

  @After
  public void whatUsedToBeIntearDown() {
    // test tear down type activities
  }

}

Minor Eclipse Annoyance - organise imports changes import static org.junit.Assert.* to whatever asserts you’ve actually referenced. This being an annoying when you’re developing iteratively and may not yet have used all the asserts you might wish to use.

Comments
No Comments »
Categories
development, software
Tags
java, junit, testing
Comments rss Comments rss
Trackback Trackback

Author

Ian Robinson is a relatively agile software engineer interested in things both sides of the object relational divide and beyond.

Categories

  • development (35)
  • miscellaneous (20)
  • music (7)
  • software (13)

Blogroll

  • Dan North
  • Dave Astels
  • Dave Wood
  • eirikso.com
  • Matt Raible
  • Object Mentor Blog
  • The Ancient Art of Programming
  • The Wisdom of Ganesh

Tags

active-mq architecture bauhaus blu-ray css db eclipse esb festivals freesat gorm grails groovy hd hd-dvd hibernate java jboss jms junit links mce media center mini music oracle osgi patterns pirsig plugins satellite soa software spring sql struts2 testing themes tools tv web wordpress xml xpath xslt
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox