Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test private classes

Let's say I made use of the following module-kind pattern in JavaScript:

var myModule = (function () {
    var Foo = function () { /* ... */ };
    var Bar = function () {
        this.foo = new Foo();
    };
    Bar.prototype.someMethod = function () {
        this.foo.someMethod();
    };
    return {
        'Bar': Bar
    };
})();

Is it advisable and if yes - how can I expose Foo for unit testing? Is there some common technique or pattern for doing this?

like image 519
tyrondis Avatar asked Mar 05 '11 11:03

tyrondis


1 Answers

I don't think you should really need to unit test the private members. As long as you have comprehensive tests on the public members, any errors within the private members will manifest themselves as errors on the public members. You can then use good ol' debugging to find out what the exact problem was.

Alternatively, if you have your tests run on a separate build to production, you could expose the enclosing object, and test against that. You'd need to remember to remove the reference to the enclosing object before deployment - or you could automate it somehow. Honestly though, I generally wouldn't bother removing it, unless you're packaging a library for public consumption.

var myModule = (function () {
    var _this = this;
    var Foo = function () { /* ... */ };
    var Bar = function () {
        this.foo = new Foo();
    };
    Bar.prototype.someMethod = function () {
        this.foo.someMethod();
    };
    return {
        'Bar': Bar,
        '__private__': _this
    };
})();

function test_foo(obj) {
    var foo = obj.__private__.Foo;
    assert(foo.prop, 10)
}

For an inhouse system, being able to access the private data/functions is usually a non-issue, if it is clearly understood that accessing private members should not be done. This is highlighted by providing a reference to the enclosing object with a name like __private__. (Can you tell I'm kinda into Python? ;) )

like image 76
Josh Smeaton Avatar answered Oct 23 '22 03:10

Josh Smeaton