Rich Web Experience

NFJS / Java World Podcast

Private Events

Blogs

View all Blogs >>
  • Nathaniel Schutta

    Author, speaker, software engineer focused on user interface design.

    Clearly I’ve kicked off a trend - one day, I post about pro cess, a more»

  • Richard Monson-Haefel

    VP of Developer Relations, Curl Inc.

    more»

  • Erik Doernenburg

    Principal Consultant @ Thoughtworks

    For a few releases the Apple development tools have included OCUnit and many developers have now started to write unit tests. There are lots... more»

  • Ryan Shriver

    Business and Technology Consulting

    more»

  • Ted Neward

    Enterprise, Virtual Machine and Language Wonk

    The Pragmatic Programmer says, "Learn a new language every year". This is great advice, not just because it puts new tools into your mental... more»

  • Andrew Glover

    Co-author of "Continuous Integration"

    Dan North, the veritable progenitor of behavior driven development (or BDD), more»

  • Brian Pontarelli

    Brian Pontarelli - founder of Inversoft

    Found a good shortcut for getting access to hidden folders in OS X file dialogs and the Finder. It requires some typing and it doesn’t... more»

  • Neal Ford

    Application Architect at ThoughtWorks, Inc.

    Last weekend, I spoke at the Ag ile Experience in Reston. It was a great con more»

  • Mike Levin

    Software Developer specializing in Web2.0 websites

    GMail complains that the 44 Kbps internet dial up connection I'm using may be too slow. It suggests that I switch to HTML view. I reload the... more»

  • Jason Rudolph

    Author of Getting Started with Grails

    Tests increasingly serve multiple roles in today’s projects. They help us design APIs through test-driven development. They provide... more»

  • Jared Richardson

    Agile coach and co-author of Ship It

    For those of you who are wondering if Ruby is enterprise worthy, then eRubyCon is for you. The speaker list is a "W more»

  • Vladimir Vivien

    Software Engineer / Consultant

    Judging from the list of features that will be included in NetBeans 6.5, more»

  • Alex Miller

    Sr. Engineer with Terracotta Inc.

    Looks like the JavaOne team now has most of the audio up from the JavaOne 2008 conferen more»

  • David Bock

    Principal Consultant, CodeSherpas Inc.

    I just spent this weekend speaking at the Ag ile IT Exchange conference i more»

  • Howard Lewis Ship

    Creator of Tapestry and HiveMind

    Just hit a NullPointerException in some code: public boolean isOwner() { return authManager.getUser().equals(blog.g etOwner( more»

  • Michael Nygard

    Agile technology leader and dynamicist

    A couple of years ago, the Minneapolis-St. Paul airport introduced self-pay parking gates. Scan a credit card on the way in and on the way... more»

  • Scott Leberknight

    Chief Architect at Near Infinity

    I ran into a situation the other day with Groovy that baffled me at first. Let's create a range from 0.0 to 10.0 and then use it to check if... more»

  • Matt Raible

    Creator of AppFuse and author of Spring Live

    From the Link edIn Engineering Blog: more»

  • Venkat Subramaniam

    Founder of Agile Developer, Inc.

    This morning I got an email "I thought you might get a kick to see that your (and Andy���s) book was named one of the Top 100 Software more»

  • Guillaume LaForge

    Groovy Spec Lead & Project Manager

    more»

  • Jeff Brown

    G2One Director Of North American Operations - Groovy and Grails Developer

    I am pleased to announce that we have worked up a Grails plugin for Hudson. more»

  • Kirk Knoernschild

    Software Developer & Mentor

    I’ve published a summary of the OSGi survey results on the APS blog more»

  • Stuart Halloway

    CEO of Relevance

    I was talking to Tim the other day about auditing Rails projects, a more»

  • Graeme Rocher

    Project Lead of the Grails Project & CTO of G2One

    Brian Guan, one of the pioneers of Grails use within Link edIn, has started a more»

  • Brian Goetz

    Author of Java Concurrency in Practice

    This surprised the heck out of me.�� We recently finished a new TV room down in the basement.�� We have a 50″ plasma TV, mounted on the... more»

  • Pramod Sadalage

    Co-author of "Refactoring Databases:Evolutionary Database Development"

    So we version control/source control everything on our project.. code/data/artifacts/diagrams etc. yesterday I said why not extend it to my... more»

  • Jason Harwig

    Software Engineer

    I was reading a blog entry at more»

  • Craig Walls

    Author of Spring in Action

    For quite some time I've been pondering OSGi and how it fits into enterprise Java. And that interest has been magnified over the past month... more»

  • Keith Donald

    Lead of Spring Web and Creator of Spring Web Flow

    Today I am delivering a presentation entitled more»

  • Pratik Patel

    Software Architect

    Shake off that St. Patrick's day hang-over by coming over to the AJUG meeting this Tuesday, March 1 more»

  • Pete Behrens

    Organizational Agility Coach

    Marti nig & Associates Methods & Tools group recentl more»

  • Joseph Nusairat

    Author of Beginning JBoss Seam & Co-Author of Beginning Groovy & Grails

    Today is the first day of JBoss World, I survived the first three presentations and waiting for the keynote to be  complete to d more»

  • John Heintz

    Principal Consultant with New Aspects of Software

    This post is to mostly keep track of the numerous blog threads going on about IDLs and schemas for REST. I find myself with more to say that... more»

  • Brian Sam-Bodden

    Java author, Ruby geek and Open Source Advocate

    In this installment we are going to build the Dashboard page of the Tempo application. T more»

  • Mark Fisher

    Spring Integration Lead

    In my recent post, I had mentio more»

  • Ron Bodkin

    Chief Software Architect, Quantcast

    I'm looking forward to speaking at The Rich Web Experience conference in San Jose next month. The event runs from September 7th through 9th.... more»

  • Mark Goodwin

    Web Application Security Specialist

    We've already looked at one of the two big problems posed by anti DNS pinning on Java applets; because there's rebinding on the applet and... more»

  • Scott Davis

    Author of "Groovy Recipes" & TDD Expert

    Every time I see a live show at the Denver Botanic more»

  • Romain Guy

    Java User Interface expert.

    more»

  • Ramnivas Laddad

    Author of AspectJ in Action, Principal at SpringSource

    InfoQ.com has published my AOP myths and realities talk recorded at a No Fluff Just Stuff conference. InfoQ.com founded by Floyd Marine more»

  • David Geary

    Author of Graphic Java and co-author of Core JSF

    The 2006 NFJS tour kicked off t more»

  • Jason Hunter

    Author of Java Servlet Programming

    I just posted the JDOM 1.1 release for download. This release includes about 20 improvements and bug fixes. more»

  • Kito Mann

    Editor-in-chief of JSF Central and the author of JSF in Action

    Java™Server Faces (JSF) technology, a server-side framework that offers a component-based approach to Web user-interface development,... more»


Verify EasyMock Behavior When Expecting Exceptions

Posted by: Scott Leberknight on 05/13/2008

Often when writing unit tests I use EasyMock to mock dependencies of the class under test. And many times I need to test that a certain type of exception is thrown during a test. Sometimes I need both, for example I am using a mock to simulate a dependency that throws an exception and I want my test to verify the appropriate exception was indeed thrown and that the mock was called properly. In those cases, I use a simple little trick: use a try/finally block along with a JUnit "@Test(expected = FooException.class" annotation on my test method. Voila! Now you can verify mock behavior and verify the exception was thrown at the same time. This is cleaner than using a catch block and asserting the correct exception was thrown, since you rely on JUnit to verify the exception using the "expected" attribute of the @Test annotation. For example:

@Test(expected = ThrottleException.class)
public void testSomethingWithDependencies() {
    // Create mock
    Rocket mainBooster = createMock(Rocket.class);
	
    // Record behavior
    mainBooster.ignite();
    
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class);
    
    // Replay mock
    replay(rocket);
    
    // Create object with dependency on mainBooster
    SpaceShuttle shuttle = new SpaceShuttle(rocket);    
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    try {
        shuttle.blastOff();
    }
    finally {
        verify(rocket);
    }
}

If instead of writing tests in Java you write them in Groovy, the above code could be a little bit Groovier, though not much. (In an earlier post I showed how you can write unit tests in Groovy and still use JUnit instead of GroovyTestCase if you like.)

@Test(expected = ThrottleException)
void testSomethingWithDependencies() {
    // Create mock
    def mainBooster = createMock(Rocket)
    
    // Record behavior
    mainBooster.ignite()
    
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class)
    
    // Replay mock
    replay rocket
    
    // Create object with dependency on mainBooster
    def shuttle = new SpaceShuttle(rocket)
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    try {
        shuttle.blastOff()
    }
    finally {
        verify rocket
    }
}

Even more Groovy in this case would be to extend GroovyTestCase and use its shouldFail method, like so:

void testSomethingWithDependencies() {
    // Create mock
    def mainBooster = createMock(Rocket)
	
    // Record behavior
    mainBooster.ignite()
	
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class)
    
    // Replay mock
    replay rocket
    
    // Create object with dependency on mainBooster
    def shuttle = new SpaceShuttle(rocket)
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    shouldFail(ThrottleException) {
        shuttle.blastOff()
    }
    verify rocket
}

The GroovyTestCase version is probably the cleanest of the above three options. If you're not into Groovy, you can still use the JUnit "@Test(expected = BarException.class)" together with a try/finally/verify in plain Java unit tests for a cleaner test experience.


be the first to rate this blog

About Scott Leberknight

Scott is Chief Architect at Near Infinity Corporation, an enterprise software development, training, and consulting services company based in Reston, Virginia. He has been developing enterprise and web applications for 13 years professionally, and has developed web applications using Java, Ruby/Rails, Groovy/Grails and a smidgeon of Python. His main areas of interest include object-oriented design, system architecture, testing, and frameworks of all types including Spring, Hibernate, Ruby on Rails, Grails, and Django. In addition, Scott enjoys learning new languages to make himself a better and more well-rounded developer a la The Pragmatic Programmers' advice to "learn one language per year."

Scott holds a B.S. in Engineering Science and Mechanics from Virginia Tech, and an M. Eng. in Systems Engineering from the University of Maryland. Scott speaks at the No Fluff Just Stuff Symposiums and various other conferences. In his (sparse) spare time, Scott enjoys spending time with his wife, two daughters, and two cats. He also tries to find time to play soccer, go snowboarding, and mountain bike whenever he can.

More About Scott »