在Moq中模拟测试对象的方法?

编程入门 行业动态 更新时间:2024-10-26 00:22:20
本文介绍了在Moq中模拟测试对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想测试我类的方法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中模拟测试对象的方法?

本文发布于:2023-10-31 04:01:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   测试   方法   Moq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!