Click below for Step by Step and Interview Q & A (dotnetinter) wrote,
Click below for Step by Step and Interview Q & A
dotnetinter

C# Unit Testing interview questions with answers: - How can we UNIT test private methods using VSTS?

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.

Tags: charp interview questions, information technology questions, programming interview questions, unit testing private methods, unit testing using privateobject class
Subscribe

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments