13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

308Chapter 13JUnit: Automating Unit TestingThe String message is very helpful when you get large numbers of comparis<strong>on</strong>sand asserti<strong>on</strong>s inside your test cases. It can help you identify whichassert in which test failed.TIPWhen writing your asserti<strong>on</strong>s, keep in mind the difference betweenassertEquals() and assertSame(). The latter will test if the two argumentsrefer to the very same instance of an object, whereas the former <strong>on</strong>lychecks to see that their values are equal. So any two references to objects thatare the same will also be equal, but not vice versa. For example:String sample = "value";String others = "more value".substring(5);assertEquals(sample, others); // will passassertSame(sample, others); // will failDigging a little deeper into how all this works, it might be worth pointingout that the JUnit TestCase class, while an abstract class itself, is also an extensi<strong>on</strong>of another class, the Assert class. The Assert class is the class that definesall these public static methods for asserting the various c<strong>on</strong>diti<strong>on</strong>s (see the listabove). That is why you d<strong>on</strong>’t need any qualifiers <strong>on</strong> the various assert calls.They are all part of your test case by virtue of it extending TestCase. It alsomeans that you could override any of them to get special behavior. This mightbe useful for assertEquals(Object, Object), to allow you to compareobjects of your own kinds, but we d<strong>on</strong>’t recommend this. You are better offoverriding the equals() method of your own object than messing with theJUnit methods. And remember that if you override those behaviors, your testswill <strong>on</strong>ly be as good as your implementati<strong>on</strong> of the assert mechanisms.13.5.2 Running a Test CaseRecall how we ran the JUnit self-tests after installati<strong>on</strong>. We can now use asimilar command to execute our own test case. With the CLASSPATH still setas above, try compiling and running the test case:$ javac net/multitool/core/AccountTest.java$ java junit.textui.TestRunner net.multitool.core.AccountTest

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!