Unit Testing in Java: How Tests Drive the Code

Part III: Appendices

Appendix List

Appendix A: Notes to JUnit
Appendix B: Unit Tests with Other Programming Languages
Bibliography and List of References

A.1 Frequently Asked Questions (FAQs)

This short list of frequently asked questions was originally based on the FAQs contained in the JUnit documentation. The official JUnit FAQ list [URL:JUnitFAQ] has completely changed meanwhile. The following questions will be answered:

  • How do I implement a test case for a thrown exception?

  • How do I organize my test case classes?

  • How do I run setup code once for all my test cases?

  • I get a ClassNotFoundException when I use LoadingTestRunner. What can I do?

  • Why do I get exception XYZ when using a graphical test runner, but not in the textual test runner?

  • " assert" has been a keyword since JDK 1.4. Isn't there a conflict with JUnit's assert method?

  • How do I best integrate JUnit with my favorite development environment?

How Do I Implement a Test Case for a Thrown Exception?

Catch the exception and if it isn't thrown, call the fail method. Fail signals the failure of a test case. Here is an example:

public void testIndexOutOfBoundsException() {   Vector v= new Vector(10)   try {      Object o= v.elementAt(v.size());      fail("ArrayIndexOutOfBoundsException expected");   catch (ArrayIndexOutOfBoundsException expected) {   }}

Alternatively, you can use the ExceptionTestCase class:

  1. Make your test case class a subclass of junit.extensions.ExceptionTestCase.

  2. Write the test ignoring exceptions:

UNLIMITED FREE
ACCESS
TO THE WORLD'S BEST IDEAS

SUBMIT
Already a GlobalSpec user? Log in.

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.

Customize Your GlobalSpec Experience

Category: Knowledge Management Software
Finish!
Privacy Policy

This is embarrasing...

An error occurred while processing the form. Please try again in a few minutes.