使用最小起订量仅模拟某些方法
我有以下方法:
public CustomObect MyMethod()
{
var lUser = GetCurrentUser();
if (lUser.HaveAccess)
{
//One behavior
}
else
{
//Other behavior
}
//return CustomObject
}
我想模拟IMyInterface.GetCurrentUser
,以便在调用MyMethod
时可以转到其中一个代码路径进行检查.如何用Moq做到这一点?
I want to mock IMyInterface.GetCurrentUser
, so that while calling MyMethod
I could get to one of the code paths to check it. How to do that with Moq?
我正在做以下事情:
var moq = new Mock<IMyInterface>();
moq.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);
//act
var lResult = moq.Object.MyMethod();
但是出于某些原因,lResult
始终是null
,当我尝试在调试中进入MyMethod
时,我总是跳到下一条语句.
But for some reason lResult
is always null
and when I'm trying to get into MyMethod
in debug I'm always skipping to the next statement.
这称为部分模拟,而我知道要在最小订量中做到这一点,需要模拟该类而不是接口,然后在其上设置"Callbase"属性您嘲笑的对象为"true".
This is called a partial mock and the way I know to do it in moq requires mocking the class rather than the interface and then setting the "Callbase" property on your mocked object to "true".
这需要将要测试的类的所有方法和属性设置为虚拟.假设这不是问题,那么您可以编写如下测试:
This will require making all the methods and properties of the class you are testing virtual. Assuming this isn't a problem, you can then write a test like this:
var mock = new Mock<YourTestClass>();
mock.CallBase = true;
mock.Setup(x => x.GetCurrentUser()).Returns(lUnauthorizedUser);
mockedTest.Object.MyMethod();