Search code examples
c#testingxunit

how to test private methods using xunit C#


I'm using xUnit for testing for the code in C#. I had a problem, when I test a private method, it isn't work because the method isn't public (the another classes cannot access this method).

I have a class where has a private method:

public class Calculator{
    //...
    private double DegreeToRadian(double angle)
    {
        return Math.PI * angle / 180.0;
    }
    //...
}

And in the test:

public class TestCalculator{

    [Fact]
    public void ConvertDegreeToRadian()
    {
        // Arrange
        Calculator _calculator = new Calculator();
    
        // Act
        double angle = 90;
        double expected = angle * Math.PI / 180;
        double result = _calculator.DegreeToRadian(angle);
    
        // Assert
        Assert.Equal(expected, result);

    }
}

Is there a way to test in a private method?


Solution

  • You should test all your code but private methods are tested implicitly.

    That is, your code somehow affects the output of some public method.

    If it doesn't, then it is never executed. If it does, then you test it by calling the public method and testing against the output that is affected by the private one.

    The only exception to that rule, is testing internal classes as it is an in between visibility option.