我有以下方法:
public CustomObect MyMethod()
{
var lUser = GetCurrentUser();
if (lUser.HaveAccess)
{
//One behavior
}
else
{
//Other behavior
}
//return CustomObject
}
Run Code Online (Sandbox Code Playgroud)
我想要模拟IMyInterface.GetCurrentUser,以便在调用时MyMethod我可以访问其中一个代码路径来检查它.如何用Moq做到这一点?
我正在做以下事情:
var moq = new Mock<IMyInterface>();
moq.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);
//act
var lResult = moq.Object.MyMethod();
Run Code Online (Sandbox Code Playgroud)
但由于某些原因lResult总是null,当我试图进入MyMethod调试时,我总是跳到下一个声明.
给定一个对象,我想创建一个实现对象接口并模拟一个方法的模拟,但将其余方法转发给真实对象,而不是基类。
例如:
ISqlUtil sqlUtil = GetTheRealSqlUtilObjectSomehow(...);
var mock = new Mock<ISqlUtil>();
mock.Setup(o => o.SpecialMethodToBeMocked(...)).Returns<...>(...)
// Here I would like to delegate the rest of the methods to the real sqlUtil object. How ?
Run Code Online (Sandbox Code Playgroud)
因此,在示例中,我只想模拟ISqlUtil.SpecialMethodToBeMocked并将其余方法/属性转发到现有实例sqlUtil。
在 Moq.NET 中可能吗?
编辑 1
它也应该适用于泛型方法。