1

I have this code in a method I´m unittesting

public void SomeMethod()
{
  IMyLogger log = new Logger();
  log.ConfigLogger(); // Trying to not call this method

  //...some other code...
}

Where this is the Logger class

public class Logger : IMyLogger
{
    public void ConfigLogger()
    {
        //Serilog logging code I´m trying to not call in my unittests.
        Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .CreateLogger();
    }
}

And this is the my unittest where I´m trying to mock away (not call the code inside of the ConfigLogger() method without luck.

public void Test()
{
    var logger = A.Fake<IMyLogger>();
    A.CallTo(() => logger.ConfigLogger()).DoesNothing(); //Not working..
}

So what I´m I missing here? Why do I think this should be just like this? Even though Serilog specialist give me a better way to unittest Serilog I would also like to find out how to "FakeItEasy a void method".

Sturla
  • 3,446
  • 3
  • 39
  • 56

2 Answers2

1

Your production code is still using a concrete instance of Logger. FakeItEasy cannot influence the behaviour of anything but FakeItEasy-created Fakes.

The pattern for use is:

  1. create a Fake that your production code will use as a collaborator
  2. configure the Fake
  3. provide the Fake to an instance of the production class under test
  4. execute the production code
  5. optionally interrogate the Fake

As your production code is written now, there is no opportunity to inject a collaborator - it makes its own collaborator (log). In order to avoid calling Logger methods, you'll need to provide a way to inject an alternative IMyLogger.

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
0

You should avoid having to instantiate and configure your logger within the method.

Something like

public class SomeClass()
{
    IMyLogger log;

    public SomeClass(IMyLogger logger)
    {
        this.log = logger;
    }

    public void SomeMethod()
    {
        // code you want to test
    }
}

Then just pass it into your class under test:

public void Test()
{
    var logger = A.Fake<IMyLogger>();
    var someClass = new SomeClass(logger);

    // test someClass.SomeMethod()
}
tom redfern
  • 30,562
  • 14
  • 91
  • 126