Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that a call to any overload must have happened with FakeItEasy?

I have a method which I am testing. Given certain inputs, it should write a failure method to the logger (an ILogger). The interface has several overloads for Log(), as well as some properties (ex. a logging level). I am mocking the logger using FakeItEasy.

What I want to assert is that a call to Log() has happened. However, I don't care about which specific overload got used. How can I do this?

My ideas:

// Doesn't work, since a different overload (with more parameters) is used.
A.CallTo(() => mockLogger.Log(null)).WithAnyArguments().MustHaveHappened();

// "Works", but if the code were to call something else on the logger
// (ex. change the logging level), this would also pass!
Any.CallTo(mockLogger).MustHaveHappened();
like image 514
Daniel Rose Avatar asked Mar 09 '11 15:03

Daniel Rose


1 Answers

Edit

This can be done using the following syntax:

A.CallTo(logger).Where(x => x.Method.Name == "Log").MustHaveHappened()

Original answer

There's no easy way of doing that, and - correct me if I'm wrong - I don't think there is in any mocking framework.

That being said there is a - not so easy - way to do it provided in the example below.

public interface ILogger
{
    void Log(string value);
    void Log(object value);
}

public class LoggerTests
{
    public void FakeGetCallsExample()
    {
        var logger = A.Fake<ILogger>();

        logger.Log("whatever");

        var callsToLog = Fake.GetCalls(logger).Where(x => x.Method.Name.Equals("Log"));

        // Asserting with NUnit.
        Assert.That(callsToLog(), Is.Not.Empty);
    }

    // The following does not work as of now but I'll seriously consider
    // implementing it:
    public void AnyCallToWithCallSpecificationExample()
    {
        var logger = A.Fake<ILogger>();

        logger.Log("whatever");

        // I would add a "filtering" method to the Any.CallTo-syntax:
        Any.CallTo(logger).WhereCallMatches(x => x.Method.Name.Equals("Log")).MustHaveHappened();

        // It would also enable an extension method:
        Any.CallTo(logger).ToMethodNamed("Log").MustHaveHappened();
    }
}
like image 153
Patrik Hägne Avatar answered Oct 23 '22 17:10

Patrik Hägne