我想测试我班级的方法 A,但不调用通常由 A 调用的实际方法 B.这是因为 B 有很多外部交互,我现在不想测试.
I want to test method A of my class, but without calling the actual method B which is normally called by A. That's because B has a lot of external interactions I don't want to test for now.
我可以为 B 调用的所有服务创建模拟,但这是相当多的工作.我宁愿只是模拟 B 并让它返回示例数据.
I could create mocks for all the services called by B, but that's quite some work. I'd rather just mock B and make it return sample data.
这可能与 Moq 框架有关吗?
Is that possible to do with Moq framework?
是的,有一个问题!您必须确保方法 B 是虚拟的并且可以被覆盖.
It is, with a catch!
You have to make sure method B is virtual and can be overriden.
然后,将模拟设置为在未提供设置时调用基本方法.然后你设置B,但不设置A.因为没有设置A,实际的实现会被调用.
Then, set the mock to call the base methods whenever a setup is not provided. Then you setup B, but don't setup A. Because A was not setup, the actual implementation will be called.
var myClassMock = new Mock<MyClass>();
myClassMock.Setup(x => x.B()); //mock B
myClassMock.CallBase = true;
MyClass obj = myClassMock.Object;
obj.A(); // will call the actual implementation
obj.B(); // will call the mock implementation
在幕后,Moq 将动态创建一个扩展 MyClass 并覆盖 B 的类.
Behinds the scenes, Moq will dynamically create a class that extends MyClass and overrides B.
这篇关于在 Moq 中模拟被测主题的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
ASP.NET Core 使用 Azure Active Directory 进行身份验证并ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 进行身
ASP.NET Core 2.0 Web API Azure Ad v2 令牌授权不起作用ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授权不起作用)
如何获取守护进程或服务器到 C# ASP.NET Web API 的How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何获取守护进程或服务器到 C# ASP.N
异步调用时 Azure KeyVault Active Directory AcquireTokenAAzure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(异步调用时 Azure KeyVault Active Directory AcquireTokenAsync 超
使用电子邮件地址和应用程序密码从 oauth2/tokenGetting access token using email address and app password from oauth2/token(使用电子邮件地址和应用程序密码从 oauth2/token 获取访问令
新的 Azure AD 应用程序在通过管理门户更新之前无New Azure AD application doesn#39;t work until updated through management portal(新的 Azure AD 应用程序在通过管理门户更新之前无法运行