StezPet
StezPet

Reputation: 2450

NUnit unit Testing with Moq in Xamarin

I am using two interfaces for logging(NLog) in my Xamarin App

ILoggingService

public interface ILoggingService
{
    void Info(string message);
    void Info(string format, params object[] args);

    void Error(string message);
    void Error(string format, params object[] args);
    void Error(Exception e, string message);
    void Error(Exception e, string format, params object[] args);

    void Fatal(string message);
    void Fatal(string format, params object[] args);
    void Fatal(Exception e, string message);
    void Fatal(Exception e, string format, params object[] args);

    void Debug(string message);
    void Debug(string format, params object[] args);

    void Trace(string message);
    void Trace(string format, params object[] args);

    void Warn(string message);
    void Warn(string format, params object[] args);
}

And Another interface

ILogManager

public interface ILogManager
{
      ILoggingService GetLog([System.Runtime.CompilerServices.CallerFilePath]string callerFilePath = "");
}

In my test project I have created the Setup file like this.

[SetUpFixture]
public class Setup
{
    public static readonly Mock<IDependencyService> MockedService = new Mock<IDependencyService>(MockBehavior.Strict);
    readonly Mock<ILogManager> _logManager = new Mock<ILogManager>(MockBehavior.Strict);
    readonly Mock<ILoggingService> _loggingService = new Mock<ILoggingService>(MockBehavior.Strict);

    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        MockedService.Setup(p => p.Get<ILogManager>()).Returns(_logManager.Object);
        MockedService.Setup(p => p.Get<ILoggingService>()).Returns(_logManager.Object.GetLog());
    }

    [OneTimeTearDown]
    public void OneTimeTearDown()
    {

    }
}

I think I made some mistake during mocking the interface. Because of this, I am getting the GetLog() always null.

logger = _serviceLocator.Get<ILogManager>().GetLog(); // Always return null

Can anyone guide me to resolve my issue.? Seems like some issue in creating the stub for the mentioned interface.

Please help

Upvotes: 1

Views: 153

Answers (1)

Nkosi
Nkosi

Reputation: 247163

The log manager mock was never configured to return anything for its GetLog member. Therefore it will return null when invoked.

[OneTimeSetUp]
public void OneTimeSetUp() {

    _logManager.Setup(_ => _.GetLog(It.IsAny<string>())).Returns(_loggingService.Object);

    MockedService.Setup(p => p.Get<ILogManager>()).Returns(_logManager.Object);
    MockedService.Setup(p => p.Get<ILoggingService>()).Returns(_loggingService.Object);
}

You have to setup the behavior of the members that are expected to be invoked when testing otherwise they will default to their default return type, which in this case would be null.

Upvotes: 3

Related Questions