使用最小起订量仅模拟某些方法 [英] Using moq to mock only some methods

查看:52
本文介绍了使用最小起订量仅模拟某些方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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();

这篇关于使用最小起订量仅模拟某些方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆