2017-02-10 66 views
0

我有以下类与日志功能,为测试目的只是返回true。Moq:Moq被设置,但不认为它被称为

public SomeClass : ILogger 
{ 
    // Other functions 

    public bool Log() 
    { 
     return true; 
    } 

} 

在我的单元测试如何过我有以下几点:

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 

的布尔结果未设置为false,但为true。这导致我相信我的设置不正确。是这样吗?

+0

这是因为您没有调用注入记录器实例的Log()方法。在'SomeClass'' Log'方法内调用'logger.Log()' – Developer

+1

请提供'SomeClass'上声明的'Log'方法的实现。很可能你不会调用你的记录器的日志功能。 – Rafal

回答

1

这是因为您没有调用Log()注入记录器实例的方法。在SomeClass内部拨打logger.Log()对数方法

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

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

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