Posts Tagged ‘Java’

Simple WordPress Embedded Content, JUnit Updates and introducing Tohu!

Monday, December 21st, 2009

With my dad and step-mum currently visiting from the UK I have found it hard to find blogging time of late. A lot has been going on in my technical areas of interest lately, Java has announced closures in Java 7, WordPress and JUnit have been updated, JUnit has also had a bug release update pushed out already! In this entry I will outline the best WordPress functionality added by the update, the main reason for the JUnit releases and let you know about exciting developments at work.

WordPress has recently been updated to version 2.9. This new version includes a super easy way to include embeddable media in posts via Embeds. Thought I would give this new feature a work out by embedding one of my favourite television moments of all time…from classic BBC Comedy Only Fools and Horses – Del Boy prepares to make a move on some hot chicks whilst out on the town with Trigger…

Am sure I will find more uses for this great new feature. To find out what other new features are included check out the release blog post.

JUnit has also recently been updated to version 4.8.1. This version  follows close on the heals of the 4.8 release which introduced Categories to JUnit. Check out the Category changes and implementations  in the release notes.  The Categories implementation is marked by the authors as preliminary, not sure what is meant by that – as surely it would be difficult to remove it once people start using it! 4.8.1 fixes bugs in the Categories documentation and implementation reported by early implementors. I shall be taking a look at the implementation ASAP.

Lately I have been working on an interesting project at work that implemented a Grails/Groovy server and a .NET Extraction client. Most of my time was spent on the .NET client extractor which has been an interesting, if somewhat frustrating experience.

Today I got moved to a new project which looks like it could be really interesting. It involves the use of Tohu, an open source JBoss Drools based library for use in dynamic questionnaire based implementations. Solnet Solutions are the main developers of this open source implementation. I have been interested in making commercial use of Drools for a long time, and this project will give me the opportunity to get some real experience in this area. Tohu also currently only supports a JQuery UI. With JQuery being another of the technologies I have dabbled in but never really used in earnest as yet.

I have set myself a few goals for the coming months. Among them is blogging about the JUnit Categories updates and completing my review of the 3.7 changes. I will outline more of my plans and goals for the year in upcoming blog posts.

JUnit Goodness

Friday, November 13th, 2009
Testing: The Dark Side?

Testing: The Dark Side?

It feels like an eternity since I last sat down to write some blog content!!

The last month or so I have been busy updating a ‘JUnit Goodness’ presentation for use at the Auckland JUG October 2009 meeting. The presentation focuses on 3 aspects of JUnit 4 that I feel may have slipped under the radar of developers introduced to JUnit at version 3. Parameterized tests, matcher assertions and the @Ignore annotation were the 3 aspects I chose to include in this presententation.

The parameterzied test section of the presentation attempts to outline a process that may lead a developer to utilize a parameterized test. The realization that duplicated code can be replaced by a looping test leads the devloper naturally in  the direction of a parameterized test. The presentation aims to offer answers regarding why and when to use parameterized tests and how to write them. Also included in the presentation is a named parameterized test extension and an XML data driven parametrized test extension that I had recently implemented.

Matcher assertions arrived in JUnit 4 via JMock. The presentation aims to demonstrate the advantages of using matcher assertions compared to the legacy JUnit assertions. Matcher assertion readability, clarity of failure messages, combination matcher usage and the benefits of list matchers are all presented. The creation of custom matchers is also present, albeit through a crude over simplified example.  To finish the presentation there is a look at the somewhat under utilized IMHO @Ignore annotation and how it can fit in to improved testing practices.

Auckland JUG Duke

Auckand JUG Duke

The majority of those present at the presentation were still using JUnit even though TestNG has built up quite a following and viewed by some as the next generation test tool. TestNG has useful features such as parallel testing and data driven testing using the @DataProvider annotation that JUnit does not. Why has there not been a shift to this next generation test tool? Is it down to the lazy developer syndrome? The we know this tool, why waste time learning a similar tool attitude? Some of the attendees were aware of TestNG and the benefits it offers when writing certain types of tests – yet still used JUnit for there project test needs.

Many of those present were unaware of the benefits that the 3 aspects presented provided. There was the odd attendee who had dabbled with one or two of the aspects, but none had really dug too deep. Hopefully I provided everyone with something to think about whenever they are writing JUnit tests in the future.

I had expected the parameterized tests section, particularly the named and XML data-driven extensions would be the ‘WOW’ factor of this particular presentation. This was not the case though. The actual ‘WOW’ factor turned out to be the clarity of the matcher assertion failure messages compared to their legacy equivalents. Flicking between the two versions on the big projector screen seemed to exacerbate the clarity.

I would be surprised to see any of the developers present not using matcher assertions from now on based on what they saw. The @Ignore annotation usage did lead into a group discussion regarding how useful it was, how it could be abused and the best ways to use it.

I plan to upload a slightly updated version of the presentation to SlideShare later this week.

Purchase JUnit In Action 2nd Edition MEAP Edition

Purchase JUnit In Action 2nd Edition MEAP Edition

JUnit 4.7 Verifier Core Rule

Saturday, October 10th, 2009

Mommy's Little Test Developer

Mommy's Little Test Developer

Continuing with my look at the new core rules in JUnit 4.7 this blog entry will look at the Verifier core rule. This rule is the base class for rules like the ErrorCollector rule which I looked at in a previous post. Using the Verifier core rule it is possible to turn tests which would otherwise pass into failing tests based on a verification state.

There is a single method in the Verifier class that implementors of this rule need to override. The verify method is declared with a throwable exception which should be thrown to indicate verification failure. Here is the method declaration from the Verifier class:

/**
 * Override this to add verification logic.
 * Overrides should throw an exception to indicate that verification failed.
 */
protected void verify() throws Throwable {}

When the Verifier rule is applied the following apply method is used.

public Statement apply(final Statement base, FrameworkMethod method,
  Object target) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        base.evaluate();
        verify();
      }
   };
}

As can be seen once the base statement evaluation is completed the overriden verify method will be run. This enables the implementation class to fail tests which would otherwise pass.

So how could this be employed in a useful manner? Under what circumstances would it make sense to fail a passing test based on an object state ending up in an incorrect state. John Smart recently wrote an article about Testing Exceptions in JUnit 4.7 in which he implements the verify method in order to check a user is not logged in.

John states that his implementation is probably not the intended use of the Verifier rule, but I don’t think he was far from an intended use. John did provide me with a use case for the Verifier rule though. So my implementation will be used to verify that a user is still in the session once the test has run.

All John failed to implement in his example is a version of the verify method that throws an exception. Following the same pattern as the ErrorCollector rule for my UserInSessionVerifier class that extends Verifier I implemented a verify method that throws a NoUserInSessionException. Below is my UserInSessionVerifier class code:

import javax.servlet.http.HttpSession;
import org.junit.rules.Verifier;

public class UserInSessionVerifier extends Verifier {

  HttpSession session;

  public UserInSessionVerifier(HttpSession session) {
    this.session = session;
  }

  @Override
  protected void verify() throws Throwable {
    NoUserInSessionException.assertNotEmpty(session);
  }
}

As can be seen this is a fairly simple class which extends the Verifier rule class and overrides the verify method. This overriden method throws a NoUserInSessionException if the session user state verification fails, that happens if the session does not contain a user. The session property is initialized in the constructor, which is then passed by parameter to the assertNotEmpty static method of the NoUserInSessionException class. Lets take a look at that class now:

import javax.servlet.http.HttpSession

public class NoUserInSessionException extends Exception {

  private static final long serialVersionUID = 1L;
  private final HttpSession session;

  public NoUserInSessionException(HttpSession session) {
    this.session = session;
  }

  public HttpSession getSession() {
    return this.session;
  }

  public static void assertNotEmpty(HttpSession session) throws Throwable {
    if (session.getAttribute("userName") == null
          || session.getAttribute("userName").equals("")) {
      throw new NoUserInSessionException(session);
    }
  }
}

This standard exception class extends a Throwable subclass, it also  implements the static assertNotEmpty method that contains the user state verification code. In this trivial example if the userName attribute in the session is empty or null a NoUserInSessionException is thrown – as the user state is not what we expected it to be. If the user state is as we expect – that is to say it is populated then this method will not throw an exception and the verify method in UserInSessionVerifier will not cause any tests to fail.

Having looked at our Verifier rule (UserInSessionVerifier) and its associated exception (NoUserInSessionException), lets now look at a test that uses our new UserInSessionVerifier rule.


import static org.junit.Assert.assertTrue;

import javax.servlet.http.HttpSession;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.mock.web.MockHttpSession;

public class UserInSessionVerifierExample {

 public HttpSession session = new MockHttpSession();

 @Rule
 public UserInSessionVerifier verifyUserInSession = new UserInSessionVerifier(session);
 @Rule
 public ExpectedException thrown = ExpectedException.none();

 @Test
 public void userInSessionPasses() {
   // Add user to the session.
   session.setAttribute("userName", "testUser");
   assertTrue(true);
 }

 @Test
 public void userNotInSessionFails() {
   // No user added to session
   assertTrue(true);
 }

 // This fails
 // - Because the exception is not returned by base.evaluate() but
 // by the verify() call in the Verifier class apply() method.
 @Test(expected = NoUserInSessionException.class)
 public void userNotInSessionUncaught() {
   // No user added to session
   assertTrue(true);
 }

 @Test
 public void userNotInSessionCaught() {
   // No user added to session
   thrown.expect(NoUserInSessionException.class);
   assertTrue(true);
 }

 @After
 public void removeUserFromSession() {
   if (session.getAttribute("userName") != null) {
         session.removeAttribute("userName");
   }
 }
}

Looking at this class you will notice that there are  2 JUnit 4.7 rules, 4 tests and an @After annotated method in it. Lets look closer at these aspects of the test class now.

The first rule declared is the UserInSessionVerifier rule that we implemented. We pass this rule the MockHttpSession as an argument to the constructor. This rule will be evaluated after each test is run, so if there is no user in the session at the end of a test the rule will fail verification. The second rule used is an ExpectedException rule which will be used to test that when the verification fails we actually recieve a NoUserInSessionException.

The 4 tests all contain a simple passing assertTrue(true) statement which means they should all run successfully. The difference comes in the verification state once the tests complete.  The userInSessionPasses test places a user into the session, thus when the verification rule is applied the state is verified and the test passes successfully. The userNotInSessionFails test does not place a user in the session and although the base statement passes the test fails due to the verification state.

The other 2 tests show how the NoUserInSessionException thrown by the  UserInSessionVerifier method gets handled. The userNotInSessionUncaught method shows that using the expected exception attribute to catch the NoUserInSessionException fails. This fails as the base evaluate method does not throw the exception – which is what the expected exception attribute checks. The exception is thrown by the verfiy method. Using the ExpectedException rule which catches exceptions even during the verification state we can catch this exception. The userNotInSessionCaught test passes as the ExpectedException rules expect method rule is met – the NoUserInSessionException is thrown.

The @After method simply clears the user from the session. As can seen this runs after the verification rule, otherwise the userInSessionPasses test would fail. I included it to test when the verification rule gets fired. I wanted to check that the rule was being fired before any clean up methods.

I belive that John could  update his verifier to check if a user was logged in based on the example presented here. I would be interested to know if he thinks such an implementation would prove to be scalable or not. Shall follow up with him.

Hopefully this has provided you with some ideas on how to use the Verifier rule. Would be great to hear about implementations of it you create and how it gets used. I shall move on to investigate the  TestWatchman rule  in my next installment, so hopefully you will be back for more!