简体   繁体   中英

Moq: Moq is setup but doesn't think it is called

I have the following class with a Log function that for the testing purpose just returns true.

public SomeClass : ILogger
{
    // Other functions

    public bool Log()
    {
        return true;
    }

}

How ever in my unit test I have the following:

 Mock<ILogger> logger = new Mock<ILogger>();
 logger.Setup(func => func.Log()).Returns(() => false).Verifiable();

 SomeClass testMe = new SomeClass(logger.Object);
 bool result = testMe.Log();

 logger.Verify(); //This fails saying that the Log function was never called

The bool result is not set to false, but to true. Which leads me to believe my setup is incorrect. Is this the case?

That is because you haven't called Log() method of injected logger instance. Call logger.Log() inside your SomeClass Log method

public SomeClass : ILogger
{
    private ILogger logger;
    // Other functions

    public SomeClass(ILogger logger)
    {
     this.logger = logger;
    }    

    public bool Log()
    {
        return logger.Log();
        //return true;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM