Musings about this and that

March 12, 2009

Java Pearls: Why not copy the attribute’s value onto itself

Filed under: Java Pearls — ajesse @ 2:47 pm
Tags:

I like it, when values are set into attributes from where they have been fetched. Makes for readable code.

UserBean deputyChange = myTransferObject.getDeputy();
if (deputyChange != null && deputyChange.getUid() != null) {
  if (!checkUserRole(deputyChange.getUid(), FunctionGroups.ROLE_TO_CHECK.getRole())) {
    throw new IllegalArgumentException("Deputy user-id not valid: " + deputyChange.getUid());
  }
  myTransferObject.setDeputy(deputyChange);
  myContext.getMyBean().getMyOtherTransferObject().setAssistanceUserDetail(deputyChange);
}

Apart from the fact that the webapplications user gets a nice looking Exception Message in his browser if he selected the wrong user from a list… It really makes sense to set the originating attribute to the value it delivered just a few lines above…

March 5, 2009

JSFUnit 1.0.0.GA available

Filed under: JSF, JSFUnit, Unit Testing, UnitTest — ajesse @ 9:47 am

According to the projects website JSFUnit has gone live with release 1.0.0.
Time to get serious about JSF unit testing again.

February 16, 2009

Java Pearls: Pick the first and only item of a collection

Filed under: Java Pearls — ajesse @ 12:40 am
Tags:

Every now and then I stumble upon real nice examples of Java code…

Like this pick method It should return the only item in a collection:

package some.pkg;

import java.util.Collection;
import some.pkg.Helper4Exceptions;

/**
 * Helper for Collections.
 */
public class Helper4Collections {
	public static  E pick(Collection coll) {
		Helper4Exceptions.assertNotNull(coll); // throw a runtime exception if coll is null
		if(1!=coll.size()){
			throw new RuntimeException("zero or more than one element found");
		}
		Helper4Exceptions.assertEquals(1,coll.size()); //runtime exception if not exactly 1 member in coll
		return coll.iterator().next();
	}

	// and other methods
}

Obviously the package and the class comment have been messed with to protect the original author

What impressed me first was the impossibility to reach the call of assertEquals in this method. Then I went further to look at the two used methods…

package some.pkg;

import some.pkg.Helper4Comparison;

/**
 * This helper class contains several static methods that allows to do advanced
 * exception handling. Furthermore it provides certain assertion method similar
 * to the uses methods within junit test. (this has been done becaus the junit
 * test environment is not part of the produtive deployment.
 */
public class Helper4Exceptions {

	/**
	 * Assert equals.
	 *
	 * @param i
	 *            the i
	 * @param j
	 *            the j
	 */
	public static void assertEquals(int i, int j) {
		assertEquals(new Integer(i), new Integer(j));
	}

  /**
   * Assert equals.
   *
   * @param expectedValue
   *            the expected value
   * @param currentValue
   *            the current value
   * @param
   *            element type
   */
  public static  void assertEquals(T expectedValue, T currentValue) {
    assertEquals(expectedValue, currentValue, "");
  }

  /**
   * Assert equals.
   *
   * @param expectedValue
   *            the expected value
   * @param currentValue
   *            the current value
   * @param
   *            element type
   * @param msg
   *            the msg
   */
  public static  void assertEquals(T expectedValue, T currentValue,
      String msg) {
    boolean isEqual = Helper4Comparison.equals(expectedValue, currentValue);
    if (!isEqual) {
      String message = "objects are not equal";
      Helper4Exceptions.assertTrue(isEqual, message + ":\nexpected <"
          + expectedValue + "> \nbut was   <" + currentValue + "> \n"
          + msg);
      thisLineShouldNeverBeReached();
    }
  }

  /**
   * Assert true.
   *
   * @param condition
   *            the condition
   * @param string
   *            the string
   */
  public static void assertTrue(boolean condition, String string) {
    if (!condition) {
      throwRuntimeException("Assertion:\n" + string);
    }
  }

	/**
	 * Assert not null.
	 *
	 * @param object
	 *            the object
	 * @param msg
	 *            the msg
	 */
	public static void assertNotNull(Object object, String msg) {
		if (object == null) {
			throwRuntimeException("assertion: object is null but was expected not to be null. \n"
					+ msg);
		}
	}

	/**
	 * Assert not null.
	 *
	 * @param object
	 *            the object
	 * @param
	 *            element type
	 * @return the not null object
	 */
	public static  T assertNotNull(T object) {
		if (object == null) {
			assertNotNull(object, "");
			throw thisLineShouldNeverBeReached();
		} else {
			return object;
		}
	}

	/**
	 * throws runtime exception "This line should never be reached".
	 *
	 * @return the runtime exception
	 */
	public static RuntimeException thisLineShouldNeverBeReached() {
		return thisLineShouldNeverBeReached(null);
	}

	/**
	 * throws runtime exception "This line should never be reached".
	 *
	 * @param msg
	 *            the msg
	 *
	 * @return the runtime exception
	 */
	public static RuntimeException thisLineShouldNeverBeReached(String msg) {
		return throwRuntimeException("this line should never be reached"
				+ (msg == null ? "" : ":\n" + msg));
	}

	/**
	 * Throw runtime exception.
	 *
	 * @param msg
	 *            the msg
	 *
	 * @return the runtime exception
	 */
	static public RuntimeException throwRuntimeException(String msg) {
		throw new RuntimeException("\n" + msg);
	}

  // and other methods
}

and the method called in this second class

package some.pkg;
/**
 * This class provides several static helper methods for topic Comparison.
 */
public class Helper4Comparison {

	/**
	 * Equals.
	 *
	 * @param value1
	 *            the value1
	 * @param value2
	 *            the value2
	 *
	 * @return true if both values are equal, and considers the different null
	 *         combinations
	 */
	public static boolean equals(Object value1, Object value2) {
		Boolean equals = isEqualCausedByNulls(value1, value2);
		if (equals != null) {
			return equals.booleanValue();
		} else {
			// now we know that both values are not null
			return value1.equals(value2);
		}
	}

	/**
	 * return true if both values are identical or both null, 

	 * false if one value is null and the other is not null, 

	 * returns null if both values are not null.
	 *
	 * @param value1
	 *            the value1
	 * @param value2
	 *            the value2
	 *
	 * @return true, if checks if is equal caused by nulls
	 */
	private static Boolean isEqualCausedByNulls(Object value1, Object value2) {
		if (value1 == value2) {
			// identical values return true (also checks for both null)
			return new Boolean(true);
		} else if (value1 == null || value2 == null) {
			// this means one value is null but the other is not null
			return new Boolean(false);
		} else {
			// means both values are not null, but not identical
			return null;
		}
	}
}

Well, I’m impressed. Especially because this developer told us once, when we proposed some simple solution to another problem, that we would be stone age developers and he was doing better…

I’d really like to hear hat other developers think about these coding samples.

January 27, 2009

Let’s meet in Vienna again – JSFDays 2009

Filed under: JSF, JSFDays — ajesse @ 2:20 pm
Tags: ,

Last years JSFDays in Vienna have been a huge success. The organization was superb and the event definitely focused on JSF. This year the event will be bigger and contains now two tracks. One of them is focused on JSF while the second track has a larger enterprise Java focus. Check out the website.

With JSF 2 on the horizon you definitely should consider making the trip to Vienna. Several of the sessions for JSF will concentrate on that. And who could you tell better about JSF 2 than the guys that shaped it working for the Expert Group. And JSFDays will feature several expert Group members giving you the information from the source.

Let’s meet there and have some fun too. Vienna definitely is a city to enjoy, so consider staying for the weekend as well and discover its many features.

Already booked?

December 4, 2008

JUnit-testing BigDecimals: watch your JUnit version

Filed under: Unit Testing, UnitTest — ajesse @ 11:55 am

Consider this test:

  public void testBigDecimalAssertEquals() {
    BigDecimal number1 = new BigDecimal("0.01");
    BigDecimal number2 = new BigDecimal("0.99");

    System.out.println("number1.equals(number2)= " + number1.equals(number2));
    assertEquals(number1, number2);
    System.out.println("  but JUnit thinks its equals...");
    assertTrue(number1.equals(number2));
    System.out.println(  "  only testing for BigDecimal.equals() == "
                       + "true will yield the correct result.");
  }

I definitely expected the assertEquals condition to report a failure, but…

In my Eclipse environment I had JUnit 4.3.1 loaded and the test only failed on the assertTrue condition.

After some download- and debug-sessions I learned that some JUnit-versions (> 3.8.x and < 4.4) had some code in the Assert.isEquals() method which caused this behaviour:

private static boolean isEquals(Object expected, Object actual) {
  if (expected instanceof Number && actual instanceof Number)
    return ((Number) expected).longValue() == ((Number) actual).longValue();
  return expected.equals(actual);
}

Versions before and after 4.4 do not check for a Number-instance, they just call the objects equals method.

June 30, 2008

Jazoon Presentation Online Available

Filed under: Uncategorized — ajesse @ 11:44 am
Tags: , , ,

At this years Jazoon I presented an introduction to JSFUnit. The presentation is now online.

Jazoon turned out to be, once more, a great conference. The presentations are held in movie-theaters with comfy seats and good acoustics. All over the place a free WLan is available. In the exhibition the speakers and other esperts from the sponsors are easily approachable. Those that were there, I think, will agree to this opinion. And those that were not there surely missed a nice conference and definitely should note the already published date of next years Jazoon.

See you next year in Zurich at Jazoon 2009

April 28, 2008

Jazoon 08 looming ahead

Filed under: JSF, JSFUnit, Unit Testing, UnitTest — ajesse @ 4:46 pm
Tags: , , ,

Time for the next big Java conference… the Jazoon 08.

I’m gonna talk about JSFUnit. It will be an introduction to this JSF testing framework (presentation info).

Hope to see you there and have a chat together… my company’s (Credit Suisse) booth seem to e close Netcetera’s, let’s hope their coffee is as great as last year (was a really good coffee, even by italian standards). From our coordinator I heard, that we will distribute our good chocolate goodies… That should make a good combo: good coffe and good chocolate.

March 14, 2008

JSF Days 08 – almost over

Filed under: JSF, JSFDays, JSFUnit, Selenium, Unit Testing — ajesse @ 3:44 pm

To all those that forgot to come to Vienna: You definitely missed something really great.

3 days with many important people in the JSF ecospace (Kito: good definition of that) in a very relaxed context. Irian did a great job to organize this second JSFDays in a perfect way, which definitely helps to create this friendly mood.

For those not yet used to be able to get in “touch” with the great names of JSF were pleasently surprised how easy those persons behind the names are. This feature is definitely something I like in the JSF ecosphere. Despite being a difficult environment (todays webapp-development,…) JSF brings along a bunch of nice guys that are very approachable and helpfull. A great community. And this you can really feel here in Vienna at the JSFDays.

Almost a pity those 3 days are almost over… It will be a long time till JSFDays 2009.

The presentations will be available through Irian’s website. As soon as this happens I will report back.


I did a presentation on Testing JSF applications and components. Although one of my laptops started to misbehave… it went quite well. I got some nice feedback, questions and hints and wait impatiently for the official feedback analysis.I concentrated on Selenium and JSFUnit.The preparation for this talk are also the reason for the long time since my last post… but it also gave me some input for further posts ;)

November 12, 2007

Simple walkthrough testcase using SeleniumTestCase

Filed under: JSF, Selenium, Unit Testing, UnitTest — ajesse @ 7:17 pm

After all the preparations its time to write some tests. Imagine a sample-application that contains a page per component from a component set. For our nightly build we want to know whether all pages work. So a first test would be to use the browser and click through all pages. Annoying and always the same. Calls for an automated test, doesn’t it?

@Test public void checkCatalog() {
  openAndWaitWebAppRoot();
  clickAndWait("link=CATALOG");
  assertPageTitleEquals("JSF Components Catalog");
  clickAndWait("link=CATALOG");
  clickAndWait("link=Layout components");
  assertPageTitleEquals("Layout components");
  clickAndWait("link=Layout");
  assertPageTitleEquals("Layout Component");
  clickAndWait("link=Container");
  assertPageTitleEquals("Container Configurator");
  clickAndWait("link=GroupBox");
  assertPageTitleEquals("GroupBox Component");
  clickAndWait("link=Tabbed Pane");
  assertPageTitleEquals("TabbedPane Component");
  clickAndWait("link=MessageArea");
  assertPageTitleEquals("MessagesArea Component");
};

Looks easy, doesn’t it? Looks and feels just like the instructions for a human tester. And that’s the writing test should be: simple.

Such a test can also survive a revamp of the menu-structure of the application, as long as the texts of the menu-items remain constant, the testcase, just like the human tester, still find the links to click on. Was very usefull when we did such a refactoring of the sample-application. Every now and then someone from teh team would do the “cvs update”-redeploy-”let the testuite run”-cycle and just report which areas needed some massaging.

New tricks for SeleniumControl and SeleniumTestCase

Filed under: JSF, Selenium, Unit Testing, UnitTest — ajesse @ 6:47 pm

Since the original post introducing SeleniumControl and SeleniumTestCase these two classes learned some more tricks.

The most annoying thing I noticed about that code was, that I had to trigger the SeleniumTestSuite to be able to run a testcase. So I added a simple method to SeleniumControl (isStarted() returning true if server != null) to allow a testcase to query for that and, in case of need, to start the SeleniumServer on its own. The TestCase class checks for this in its setupBeforeClass()-method…

Now I can start either a SeleniumTestSuite, which results in the server started only once for the whole testsuite, or a SeleniumTestCase, which starts the server just for that single testcase. At the beginning the restriction did not hurt, only with the evolution of the test-suite (about 125 tests so far…) this started to itch.

After a few testcases I also added a method to SeleniumTestCase to open the web-applications root:

public boolean openAndWaitWebAppRoot() {
boolean result = false;
try {
selenium.open(getWebAppRoot());
selenium.waitForPageToLoad(pageTimeOut);
result = true;
} catch (Throwable t) {
result = false;
System.err.println("--- received an exception: " + t);
}

return result;
}

public String getWebAppRoot() {
return testHost + testAppl;
}
Next Page »

Blog at WordPress.com.