2

Eclipse Juno Service Release 1

Example of a working Unit Test ...

InRangeTest = TestCase("InRangeTest");

InRangeTest.prototype.test01 = function()
{
    var ir = new InRange(0.0, "<", Number.MAX_VALUE, "≤");
    assertTrue(ir.isInRange(0.3));
};

But, to do more than one test I believe I should be using setUp. Unless I am mistaken, the advantage of setUp is that I would not have to instantiate var ir in every unit test. So, I tried the following ...

InRangeTest = TestCase("InRangeTest");

InRangeTest.prototype.setUp = function()
{
    var ir = new InRange(0.0, "<", Number.MAX_VALUE, "≤");
};

InRangeTest.prototype.test01 = function()
{
    assertTrue(ir.isInRange(0.3));
};

Only, I get the error message

ReferenceError: ir is not defined

Replacing var ir with this.ir did not get it working.

What's wrong?

Thanks for any help in advance.

Extermiknit
  • 153
  • 1
  • 2
  • 12

1 Answers1

0

If you use this.ir in both functions it should work:

InRangeTest = TestCase("InRangeTest");

InRangeTest.prototype.setUp = function()
{
    this.ir = new InRange(0.0, "<", Number.MAX_VALUE, "≤");
};

InRangeTest.prototype.test01 = function()
{
    assertTrue(this.ir.isInRange(0.3));
};
meyertee
  • 2,211
  • 17
  • 16
  • Sorted. Thanks. The sub-text to the question is me trying to get to grips with scope and visibility in Javascript. If I understand it correctly, The "this" keyword binds the "ir" object to the "InRangeTest" object constructor, which is why it was needed for the unit tests to see the "ir" object. Otherwise, the "ir" object would only be visible within its parent object, which, in this case, is the unit test and not the parent of all the unit tests in InRangeTest. (Sorry if I got my terminology mixed up). – Extermiknit Jan 03 '13 at 04:59
  • It can be confusing, especially coming from other languages. In JS there's only function scope. So if you define `var x;` it'll only be visible within that function. If you access a variable, JS will go up all the function scopes until it reaches the global scope (window), looking for that variable. In your initial example it'll look for `ir` defined on window and won't find it. `setUp` and `test01` will be called as methods on the TestCase object, and therefore have `this` bound to that object. So that's how you can share the values. See also http://stackoverflow.com/questions/500431 – meyertee Jan 03 '13 at 22:07