Java Reference
In-Depth Information
As a bonus, RhinoUnit includes JSL int, 11 which allows you to check from Ant that your
JavaScript code follows best practices. Download and unzip RhinoUnit. 12 If you're on
Java 6, you've finished; if not, some additional steps are documented in appendix E.
Let's create a simple function to test; the following code defines a factorial func-
tion (factorial.js.)
function factorial(n) {
if ((n === 0) || (n === 1)) {
return 1;
}
return n * factorial(n - 1);
}
The following JavaScript unit tests the factorial function (test-example.js.)
B
eval(loadFile("src/main/webapp/factorial.js"));
testCases(test,
function test15() {
assert.that(factorial(15), eq(1307674368000));
},
C
D
function test16() {
assert.that(factorial(16), eq(20922789888000));
}
);
We start the test by including the library of functions we want to test b with a call to
eval . Note that the path to the file is relative to where we're running the test from; in
this case, it's the project's root directory. Next, we must call testCases , passing in test
as the first variable C , followed by our test functions. You can pass in any number of
functions; note the comma separating the test functions. For this simple test, we call
our factorial function from two different tests and make sure that the computation
results in the expected value D E , for example, checking that calling factorial(15)
yields 1307674368000 D . The assert.that call is how to make an assertion in Rhi-
noUnit. The first value is the value we're testing, the actual value ; the second value, the
predicate, defines the actual test. Here we use eq to test for equality to its argument,
1307674368000 . The general format is
E
assert.that(actual, predicate)
The RhinoUnit site lists 13 the functions you can use in addition to eq ; these are the
most widely used:
The function eq(expected) uses === to compare actual and expected values.
The function matches(regExp) tests the actual value against the given regu-
lar expression.
11
http://www.JSLint.com/
12
http://code.google.com/p/rhinounit/
13
http://code.google.com/p/rhinounit/wiki/APIDescription
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search