IntelliJ Java IDE
The moose likes Testing and the fly likes How to write test unit for Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Engineering » Testing
Reply Bookmark "How to write test unit for Constructor" Watch "How to write test unit for Constructor" New topic
Author

How to write test unit for Constructor

Matthew Vahedi
Greenhorn

Joined: Jan 05, 2012
Posts: 6
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.
Brian Burress
Ranch Hand

Joined: Jun 30, 2003
Posts: 118
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.
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 23645

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta
 
 
subject: How to write test unit for Constructor
 
Threads others viewed
regular expression problems
Pattern Problems
JS on the html page
Generate a random value from a regex
Replace text by HTML links
IntelliJ Java IDE

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture