Using Moq to determine if a method is called(使用 Moq 确定是否调用了方法)
问题描述
据我了解,如果我调用更高级别的方法,我可以测试是否会发生方法调用,即:
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:
public abstract class SomeClass()
{
public void SomeMehod()
{
SomeOtherMethod();
}
internal abstract void SomeOtherMethod();
}
我想测试一下,如果我调用 SomeMethod()
那么我希望 SomeOtherMethod()
会被调用.
I want to test that if I call SomeMethod()
then I expect that SomeOtherMethod()
will be called.
我认为这种测试可以在模拟框架中使用是否正确?
Am I right in thinking this sort of test is available in a mocking framework?
推荐答案
你可以通过Verify来查看你已经mock过的东西中的某个方法是否被调用了,例如:
You can see if a method in something you have mocked has been called by using Verify, e.g.:
static void Main(string[] args)
{
Mock<ITest> mock = new Mock<ITest>();
ClassBeingTested testedClass = new ClassBeingTested();
testedClass.WorkMethod(mock.Object);
mock.Verify(m => m.MethodToCheckIfCalled());
}
class ClassBeingTested
{
public void WorkMethod(ITest test)
{
//test.MethodToCheckIfCalled();
}
}
public interface ITest
{
void MethodToCheckIfCalled();
}
如果该行被留下注释,它会在您调用验证时抛出 MockException.如果未注释,它将通过.
If the line is left commented it will throw a MockException when you call Verify. If it is uncommented it will pass.
这篇关于使用 Moq 确定是否调用了方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Moq 确定是否调用了方法


- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01