mardi 30 juin 2015

Test if method in ClassA has been called from another method in ClassA

It is possible to test if a method has been called using Moq and dependency injection. However, is it possible to test if one method in a class calls another within the same class?

In example, I want to test that if I log a certain exception, that an information message is logged as well.

The method is:

public void Error(string message, Exception exception, long logId = 0)
{
    var int32 = (int)logId;
    Info("Id was converted to an int so that it would fit in the log: " + logId, int32);
    Error(message, exception, int32);
}

This was my attempt at unit testing it. It fails... can it be done?

void logging_an_error_with_a_long_id_also_logs_info()
{
    var mock = new Mock<ILogger>();
    var testedClass = new Logger();
    var counter = 0;

    testedClass.Error("test" + counter++, new Exception("test" + counter), Int64.MaxValue);

    mock.Verify(m => m.Info(It.IsAny<string>(), It.IsAny<int>()));
}

Since the info and error methods are in the same class (ClassA), I don't believe I can pass ClassA as a dependency into ClassA. So don't test it?

Aucun commentaire:

Enregistrer un commentaire