Reflection


You've seen how the use of the Object method getClass allows you to determine the type of an object at runtime. This is known as reflective capabilitythe ability of code to examine information about the code itself; that is, to reflect on itself. Another term used for reflection capabilities is metadata.

JUnit uses reflection heavily to gather the information it needs to be able to run your tests. You supply a test class file to JUnit to be tested. JUnit uses reflection to determine whether or not your class file inherits from junit.framework.TestCase, rejecting it if it does not. JUnit also uses reflection to obtain a list of methods in a test class. It then iterates these methods, executing only those that pass its criteria for being a test method:

  • The method name must start with the word "test," in lowercase letters.

  • The return type of the method must be void.

  • The method must not take any parameters.

So far, you have been telling JUnit which classes you want tested. This allows you to run only the tests that you specify. A problem with this approach is that it is easy to forget to add your test class to a suite. You might end up skipping critical tests!

Another approach is to have Java scan through all the classes in your classpath, gather the classes that are legitimate test classes, and execute only those. The benefit is that you don't have to maintain the suites in code. No tests will be left behind. The only downside is that there may be tests, such as performance tests, that you don't want run all the time. However, you can write additional code to bypass such tests if necessary.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net