Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test private method

In typescript, what is the best way to test a private method. While testing a controller in Angularjs, sometimes controller add a property (function) to $scope, and if I do not make the property public, then assign to the $scope, I may to be able to test it. Is there a recommended way.

export class MyCtrl{
    constructor($scope){
        $scope.addProp = (d:string) => {
            this.addProp();
        }
    }

    private addProp(){
        //...
    }
}
like image 703
bsr Avatar asked May 02 '14 19:05

bsr


People also ask

Can i unit test private methods?

Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

Can we test private methods in unit testing JUnit?

So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.

How do you cover a private method in a test class?

Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.


1 Answers

One solution is to rearchitect your code so that it is more testable. You could create an AddPropProvider that does the actual work (with implementation details more exposed for testing) and pass it in to the constructor for MyCtrl. That's the classic inversion of control strategy.

Another solution is maybe just make that function public after all? Private is ideal for hiding implementation details that could change, but maybe you know that function is always going to be there anyways.

Finally there's the hack. That function really exists on the instances of MyCtrl and the compiler only doesn't want you calling it because you said so.

var m = new MyCtrl();
(<any>m).addProp();

Now if you remove or modify the signature for addProp that code will still compile so you've lost type safety. In most code that would be bad. But this is unit test code so we're going to learn about the break early and easily so it's not horrible.

like image 126
Jeffery Grajkowski Avatar answered Oct 01 '22 16:10

Jeffery Grajkowski