Catch up on stories from the past week (and beyond) at the Slashdot story archive


Forgot your password?
Programming Books Media Bug Java Book Reviews IT Technology

Pragmatic JUnit Testing 118

Will Gwaltney writes "The Pragmatic Programmers have done it again. This time it's with volume 2 of their Pragmatic Starter Kit series, Pragmatic Unit Testing in Java with JUnit. In the friendly, accessible style we've come to expect from Andy Hunt and Dave Thomas, the book provides a gentle introduction to unit testing in general and the JUnit testing package in particular. Of course, by the time you've read through the introduction you're hooked, at which point Andy and Dave give you enough information to make you not just a good unit tester, but a better developer to boot." Gwaltney offers this disclaimer: "I know both authors and was one of the proofreaders for this book. I have no financial stake in either the book or their company." With that grain of salt, read on for the rest.
Pragmatic Unit Testing in Java with JUnit
author Andrew Hunt and David Thomas
pages 159
publisher The Pragmatic Bookshelf
rating 10
reviewer Will Gwaltney
ISBN 0974514012
summary Unit Testing introduction, tutorial, and developer's guide

What's the Approach?

You can go a long way in the unit testing world with this book. It's a great starter guide for learning about unit testing; the first chapter has several small sections which answer many of the questions a novice might have about the subject, including some of the most common objections to unit testing. Then the book launches into a detailed user guide to the JUnit package, including some useful but lesser-known topics like writing your own custom asserts.

After you've got the basics down, the book spends several chapters drilling into the concepts, considerations, and best practices for writing good tests. This section of the book is quite practical, and is where the true worth of the book comes out. Any developer who reads this section will come away better for it even if they never consistently write unit tests. It's amazing how many testing issues turn out to be development issues at their core; this section of the book points some of them out. Simply being aware of these issues can help you to avoid a number of common pitfalls.

Finally, the book discusses common unit testing problems and their solutions. This section is a lot of fun because of the anecdotes that Andy and Dave include; unfortunately some of them I recognized from my own experiences as a developer. (What, me do that? No, uh, of course not!)

Who's it For?

This book is primarily for developers (and testers who are intimately involved in the development process), since unit testing per se is primarily a developer task. Depending on the organization of the software shop, by the time code gets to a formal testing or QA group it's probably too late to apply unit testing methods effectively. (Note I said unit testing methods here.) The book is ideal for the unit testing novice, and there's a lot of good information here for more advanced developers to ponder.

The book is targeted at those who want to learn "how to think about tests, how testing affects design, and how to handle certain team-wide issues you may be having" (from the Preface). In particular the book is an excellent source of information for those developers who have recently moved into the Java area and are looking for a good testing framework.

No matter what your role in the development process, this book can help give you a fresh perspective into unit testing and related issues. It prods you to think about issues that perhaps you hadn't considered before.


As you can probably tell, I like the Pragmatic Programmer writing style. It's informal and friendly without being chatty or wordy, and the main text moves along well. More technical discussions are reserved for sidebars, and there are "Joe Asks..." sections throughout the book that anticipate questions that Joe Programmer might ask about the current topic.

The examples in the book are excellent. Many books err on the side of code snippets that don't have enough context to be understandable, or multi-page code extravaganzas that bury the details of the topic at hand under mountains of cruft. I found the examples here to give just the right amount of detail to understand what's going on. And the source for all the examples is available from the author's web site.


What this book is not is a reference manual for JUnit. The book doesn't include a javadoc listing for the JUnit package, nor does it have a section that digs into JUnit's internals. This is not necessarily a Bad Thing because that information is available from the JUnit web site, but it does bear mentioning.

If there was anything I found to complain about it was the use of acronyms in the concepts section of the book. I'll admit right here that I'm no lover of acronyms, so I felt that using things like Right-BICEP, CONNECT, and A-TRIP as mnemonics for the concepts was a bit over the top. (Read the book to see what I mean.) However, I have to admit that they help me remember the concepts discussed, so I guess they do their job (grumble).

Why Should I Read this Book?

If you hate testing, this book will very probably change your mind, and you'll have fun in the process (the stories are great!). And even if you still hate testing after you've finished the book, you will have enhanced your development skills enough to be able to delude yourself that testing isn't necessary for you (well, maybe not that much). At the very least, this book will make you aware of the various issues that proper testing can expose and maybe help you try to avoid them. By shining a light into these areas, it can still make you a more effective developer... maybe effective enough to realize how much more solid your work could be with this type of testing coverage.

If you love testing, this book will remind you why you began the love affair. Your love will be strengthened and deepened, and the tests you write will undoubtedly get better, too.

For Java developers specifically, this book will get you started writing JUnit tests painlessly and effectively and will take you a long way down the road to unit test proficiency. It will give developers in any language quite a bit to take "back to the terminal" regarding design and process as well as testing. An excellent and much needed book.

Like volume 1 of the Pragmatic Starter Kit series ( Slashdot Review), this book is available from the Pragmatic Programmer website. The printed version is $29.95 and there's a PDF version available for $20.00. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

This discussion has been archived. No new comments can be posted.

Pragmatic JUnit Testing

Comments Filter:
  • by tomblackwell ( 6196 ) on Monday March 01, 2004 @04:02PM (#8432864) Homepage
    It might be wiser to trust someone slightly more removed from the creators and creation of this book with respect to its utility.
  • by happyfrogcow ( 708359 ) on Monday March 01, 2004 @04:09PM (#8432948)
    i think you're blowing it a bit out of proportion. the review clearly stated pros/cons/intended audience and more.

    would you take a beta-testers review of an online game different? I bet you would be glad to have the behind the scenes insight as to whether or not the game sucks. If you were smart you would do just as was said and "take it with a grain of salt". continue to look for other reviews and file this one away in your head for later.
  • by HarpMan ( 53271 ) on Monday March 01, 2004 @04:38PM (#8433239)
    Um, this is a joke, right? You teach at Harvard!!??? Now I know why we're losing all our jobs to offshoring. If this the best 'teaching' our educational system produce, we're really in trouble.

    Seriously, it sound like your objections are just based on laziness - you don't want to look at extra code, documentation, etc. Too much work for you. Oh, that's another reason we're losing to offshore folks - laziness.

    I guess we're illogical too. What does documentation have to do with unit testing? Can't you do one without the other???

    Sorry, I'm just flabbergasted.

  • by Anonymous Coward on Monday March 01, 2004 @04:41PM (#8433274)

    I've tried my hardest to get the profs to teach i386 assembly and then C so that students understand how a computer works, but to no avail.

    Teaching i386 then assembly would be a sure-fire way to mentally scar and/or fail 99% of your students. You simply can't presume that all students have the level of competency in computing that learning i386 requires when they first start a computing degree.

    This competency can be picked up, and I'm not arguing that both assembly (to a certain degree) and a lower-level language like C are necessities for any good computing graduate, however a nicer ride at the beginning of the road is also a necessity. Giving someone an i386 reference manual and telling them to code won't produce more professional coders, it will instead drive away bright students who perhaps just don't have the necessary computing skills yet.

  • by outcast36 ( 696132 ) on Monday March 01, 2004 @04:42PM (#8433289) Homepage
    Your arguments are pretty valid for a TA who is trying to grade Java II homework assignemnts. But for people writing business systems there are some benefits.

    1. Extra code == extra bloat- In the business world we call this CYA. You write the tests, they run green. If something breaks, you didn't write crappy code.
    2. Too much documentation- Does anybody have this problem? I wish every system I touched had too much documentation
    3. Unit tests are written with no extra skill than the code they test- You bring up an intersting point here, and you are correct. For systems doing something novel or complicated, having the dev write the test makes no sense. However, most of the apps out here connect back to a CRM db, or fire off an email when something is done.... super boring stuff. A competent developer already has an understanding of these things and is more than capable of writing a test.

    anywho, your students are going to end up as PHBs & the rest of us would appreciate it if you didn't turn them off to testing before unleashing them onto the working world. Thanks.
  • by TeaEarlGreyHot ( 756865 ) on Monday March 01, 2004 @04:42PM (#8433290) Journal
    Every day I am reminded why the universities consistently fail to produce programmers who can work in the real world (assuming this wasn't just a troll).

    In the real world, code isn't handed in, marked, and that's that. Code is checked in, becomes part of a large, complicated system, and sometimes goes unvisited until years later, when entirely different personel have to take a gander at it and figure out what the heck it does, and why it was designed the way it was.

    The more comments and documentation, the better.

    In my current job, I'm in the middle of trying to untangle a badly-designed subsystem so it can be redesigned for new applications. There's no documentation, no unit tests. Only very high level descriptions of the I/O. The business logic is buried deep in the code, costing the company weeks of my time sifting through code. Some documentation on the outside would have cost a little bit more then, but saved a whole lot now.

    Furthermore, if your interfaces between subsystems are well-designed, JUnit should be all you need to warrant that YOUR code will interact with the rest of the project according to the specification. And if there's a problem, it's the specification's fault, not yours. Granted, JUnit isn't really used class-by-class, but it is very useful a step above that, when it comes to integrating your code into a large project.

    The problem in the academic world is there is no concept for how hugely huge projects get in the real world. No one is taught proper methodologies and good software engineering. Every assignment is a microcosm, and the short, quick, bang-out-the-code-and-ask-questions-later technique is what gets promoted in the process.

    I'm sure there are schools that aren't like this, and I'm making sweeping generalizations, but this is what I have seen.
  • by Anonymous Coward on Monday March 01, 2004 @04:44PM (#8433300)
    You know that instead of having to read all of this code you could just write a unit test yourself and determine pass/fail according to that. Then you wouldn't have to actually read (poor thing) the stuff that is given to him to read...

    Of course that would require the thought process of a real programmer. Seems the Ivy Leagues aren't all they were cracked up to be. I won't be hiring any Harvard graduates for quite some time...
  • by RedMage ( 136286 ) on Monday March 01, 2004 @04:48PM (#8433353) Homepage
    Well, I teach at Harvard also... And I'm glad I haven't run into you! Seriously, such arrogance has no place in a teaching situation.

    1. Extra bloat my eye! What you're saying here is that you're a lazy bum and can't read through extra class files. If you want to do something constructive then how about instructing on how to lay out a project intelligantly?

    2. Too much documentation? Again you're just a lazy TA and have no place grading. Regardless of the merits of HTML as a documentation medium, documentation is usually much more useful in grading than the actual code: it shows the thought process behind the code. Sure, I'm interested in that the code works as advertised, but I'm also interested in how you got there. It makes my job much easier to keep my students from falling into common pitfalls.

    3. I do agree here, but not as far as the basic premise that unit testing is bad. Bad tests are useless, while a good test can be rather helpful, especially in a regression situation. Teach your students how to write good test and their code will be better. Punish them for writing bad tests and they'll never test.

    Obviously you're not too proud of your convictions, or you wouldn't be an AC. I feel sorry for any professors you work with. I know mine are happy to work with me...

  • Re:Java (Score:5, Insightful)

    by Tumbarumba ( 74816 ) on Monday March 01, 2004 @04:51PM (#8433383) Homepage
    So what does a JUnit call look like

    JUnit unit = new JUnit.TestFramework.SimpleTest()
    unit.setPassMessage('Okay, exponention works...')
    unit.setFailMessage('Uh oh...')
    NumberFormatter format = new NumberFormatter()
    Nah, more like this:

    public void testPow() {
    assertEquals( "Unexpected Math.Pow result", Math.pow(2), 4 );

    Seriously, kids, java is bad for you...
    Yeah, I can create a verbose, unreadable and unrealistic example in Perl, too. It doesn't make the language bad, rather it reflects badly on the programmer.
  • by Anonymous Coward on Monday March 01, 2004 @04:52PM (#8433396)
    I'm posting anonymously for obvious reasons.

    You're totally clueless, and don't want anyone to know? ;-)

    I'm a teaching assistant (TA) at Harvard University, and I mark a lot of Java code as part of a job that supports my PhD studies. Code submitted to me with unit tests face an automatic 5 mark penalty, before i even begin marking. There are several reasons for this.

    You are a total moron...of course not many go to Hahvahd for CS studies. I wonder what your counterparts at real engineering schools like MIT or CalTech have to say about your viewpoint... Actually my best guess (and hope) is that you're a troll trying to land fish such as myself... ;-)

    Extra code == extra bloat. The unit test code is submitted as an extra class file, which means there is one more thing that I have to read over before I can judge their code on its merits.

    Oh, so the good programming practices of your students make your life more difficult - so you penalize them? You should be fired.

    I find that unit tests are a pain to compile, normally found deep in a directory structure where they make little sense.

    Of course the unit tests must be at the proper place in the directory heirarchy, or they wouldn't compile (Java namespace implementation). So, I doubt you know what you're talking about.

    Too much documentation. People who submit unit tests generally document the interfaces using javadoc, which just increases the amount of reading I have to do before I can assign a mark. HTML as a documentation format is stupid. There is nothing wrong with submitting code with comments at the start of a function or method and leaving it with that. If the code needs documentation because it is doing something non-obvious, it is time to rethink the code.

    Er, Javadocs aren't written in HTML...HTML is generated from Javadocs. As to your other remarks regarding code documentation, obviously you've never done any real-world programming. That is often a problem with PhD. candidates.

    Unit tests are written with no extra skill than the code they test. Unit tests induce a level of confidence in the programmer that their code works as a black box. This is a bad idea. Programmers should understand why each and everyone of their modules works the way it does, not assume that everything is well because it passes some rudimentary test that was created with the same skill level as the rest of their code.

    Code should work like a black box. That is the exact idea of encapsulation, a primary tenet of OO programming. You are quite obviously a troll with nothing to contribute to this discussion.

    As you can see, I'm against unit testing. I've tried my hardest to get the profs to teach i386 assembly and then C so that students understand how a computer works, but to no avail. If we are to regain our jobs from the Indians, we must be more professional coders.

    Ah yes, the final prong on the hook. How many of those Indian coders do you think do "i386 assembly" and "C"? Just around 0%...and don't fool yourself into thinking that either of those disciplines will do much to make entry-level coders better programmers. The important concepts are algorithmic, numeric and complexity oriented. Programming language isn't so important...and the more expressive and less bug-prone the better. Java is a pretty good choice, and has the added benefit of being widely used in the "real world" - a place you're obviously not too familiar with yourself.

  • by Delirium Tremens ( 214596 ) on Monday March 01, 2004 @05:03PM (#8433521) Journal
    Come on, people, relax. The above comment (#8433108 []) is obviously a Troll.
    It is very well crafted, but it does show all the characteritics of a Troll. Honest tone, but inflamatory arguments. Personal testimony (supposedly), but anonymous post. 'Insightful' opinions, but lack of touch with the actual matter etc ...
  • by Anonymous Coward on Monday March 01, 2004 @06:41PM (#8434435)
    Responding to the post above, there are a number of 'hidden benifits' to writing Unit tests for Real Programmers (and not Teacher's Assistants).

    1) It's fun (sad but true). I write my test cases first, and that gives me a chance to challenge myself. I'll try and write tests that are very comprehensive or hard to pass (but only if they adhere to the specification). I then hide the tests while I implement the code to see how much I remembered.

    2) It helps me seperate the notion of System code from Client code. This is pretty important because I'm often both the system architect and the client coder, and it's often hard to keep the two distinct when you're doing both.

    By writing the tests first, you are forced to think of the (unwritten) code as a client of the system. You ask yourself, 'How should this module work? What are the most simple and logical interfaces?' You then write code to those interfaces, and end up with clean architecture. You then implement the code to pass the tests.

    While that doesn't sound revolutionary, I find that without tests I have a tendency to let the logic dictate the interface. For example, I find myself thinking, 'this method would be really efficient if rather than receiving an abstract widget, it took 4 int args' (or something like that).

    There are some other benefits to Unit testing (code stability, confidence, etc), but those two were surprising 'discoveries' when I started unit testing.

Would you people stop playing these stupid games?!?!?!!!!