How to test private methods in C #?

7

How to test private methods using Microsoft.VisualStudio.TestTools.UnitTesting and Moq

My test class looks like this:

[TestClass]
public class ClasseDeTeste
{

    private  MinhaClasseComMetodosPrivados _minhaClasseComMetodosPrivados;

    [TestInitialize]
    public void Initialize()
    {
        ...inicialização de diversos repositórios 

        _minhaClasseComMetodosPrivados = new MinhaClasseComMetodosPrivados(parametros, ...);
    }

    [TestMethod]
    public void TestarFuncaoPrivadaXXX()
    {

       var result = _minhaClasseComMetodosPrivados.metodoPrivado(param1, param2, param3);

       Assert.AreEqual("retorno esperado ",result);
    }

}
    
asked by anonymous 05.06.2017 / 22:47

2 answers

8

At first, you should not test. The idea of unit testing is to test whether the public API is working as expected.

In any case, you can use the class PrivateObject of the Microsoft.VisualStudio.TestTools.UnitTesting namespace. It was created just for this purpose.

An example of how to use it:

[TestMethod]
public void TestarFuncaoPrivadaXXX()
{       
    var target = new MinhaClasseComMetodosPrivados();       
    var obj = new PrivateObject(target);

    var result = obj.Invoke("MetodoPrivado");

    Assert.AreEqual("retorno esperado ",result);
}

You can also do with reflection "on hand". Something like:

var target = new MinhaClasseComMetodosPrivados();
var methodInfo = typeof(MinhaClasseComMetodosPrivados).GetMethod("MetodoPrivado", 
                                           BindingFlags.NonPublic | BindingFlags.Instance);

object[] parametros = new [] { 1, "alguma string" }; // Só pra ilustrar
methodInfo.Invoke(target, parametros);

Also, of course, you can create a wrapper class and call private methods by public methods, but this is a shameless approach.

    
05.06.2017 / 22:50
8

The answer you really want is jbueno's. But doing unit testing on private methods is a conceptual mistake.

Unit tests should verify that the public API is always responding as expected. Private methods are implementation details and not part of the public API. Testing them does not make sense because they need the freedom to be able to work differently.

The most interesting thing to do is to have an object state invariance check between private method execution. Even this is controversial because there are cases that no matter the invariance in the middle of private processing.

    
05.06.2017 / 23:16