?

Log in

No account? Create an account

Previous Entry | Next Entry

In order to invoke private methods in VSTS unit test we have a class called as “privateobject”. Create the object of “PrivateObject” class and pass the class whose private method needs to be invoked. In our case “IsNegative” is the private method which has a integer input parameter.You can then use the “PrivateObject” object to invoke the private methods / functions as shown in the below code.

code3

Is it good to practice to UNIT test Private methods?

No. When we say UNIT it’s a class. So if we test the public methods the private methods get tested internally as well. If you are testing private methods of a class that means there is something seriously wrong with the class design.

public class Maths
{
public int Add(int num1, int num2)
{
    if (IsNegative(num1) && IsNegative(num2))
    {
        throw new Exception("Number should not be negative");
    }
    return num1 + num2;
}

private bool IsNegative(int num)
{
    if (num > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
}

For instance in the above “maths” class there is a private function “isNegative” , if you are testing this method that means “Maths” class is overloaded with responsibility. “Maths” class should only be doing arithmetic operations (Add, Subtract etc), but it is also loaded with responsibility of doing validation.

So probably it’s a good idea to move the validation to a separate class called as “Validator” who will do the numeric checks and then use this class inside the “Maths” class.

You can then write test cases on the “Validator” class separately which is a cleaner approach than the previous approach of using “PrivateObject” and invoking them via reflection.

public class Validator
{
private private bool IsNegative(int num)
{
    if (num > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
}

Below is a nice video on Unit testing private methods using VSTS test.

Copy right www.questpond.com

Tags

Latest Month

September 2017
S M T W T F S
     12
3456789
10111213141516
17181920212223
24252627282930
Powered by LiveJournal.com