• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to handle NullPointerException in your tests...

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I pass null as a paremeter to one of my under the test methods. Now I want to know is there any better way than putting this method call in a try/catch block and check to see myException.getClass().getName() == java.lang.NullPointerException" or myException instanceof NullPointerException or this is the best way in your opinion.
Of course I could use a mock object (e.g. using easyMock) and expect my desirable Exception but I prefer using a real one instead of playing with mocks in this case.
Your ideas are appreciated
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When using JUnit 4, you can use

@Test(expected=NullPointerException.class)

With JUnit 3, using the try-catch approach actually is the most common way. You don't need to explicitly check for the exception type if you only catch NullPointerExceptions, though.
 
author
Posts: 11962
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ashkan Roshanayi:
...putting this method call in a try/catch block and check to see myException.getClass().getName() == java.lang.NullPointerException" or...


I realize that you wrote that off-the-cuff but I'll still point out that it's much better to compare the Class objects than the Class objects' names:

[ January 31, 2007: Message edited by: Lasse Koskela ]
 
Ashkan Roshanayi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot for your kind replies.
-Best wishes
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic