This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Journey To Enterprise Agility and have Daryl Kulak & Hong Li on-line!
See this thread for details.
Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

How to write test unit for Constructor  RSS feed

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody,

Please tell me how I can write down a UnitTest for the following code:
(I would like to make sure that this pattern matching fails/passes as desired) Please note that this is the constructor of a class.
 
Ranch Hand
Posts: 135
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest you refactor your code so that you are invoking a method call instead of a constructor (static method if you do not want to instantiate a class) and consider naming it something like isValid or isInputValid and return a boolean (true/false). Then write your tests to invoke this method and pass the various values you wish to test.
 
author & internet detective
Marshal
Posts: 38504
653
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew,
Welcome to CodeRanch!

Does your code really just output a value? If so, you have two choices:
1) Extract to a method that returns a boolean as suggest above. This is the best approach.
2) Mock out System.out (and whatever object print is) with a ByteArrayOutputStream. The System class lets you change where System.out points to so you can test the results. I recommend storing the original System.out reference so you can put it back in the @After/tearDown.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!