如何使用 moq 测试抽象类中的具体方法? [英] How to use moq to test a concrete method in an abstract class?

查看:27
本文介绍了如何使用 moq 测试抽象类中的具体方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,当我想模拟一个抽象类时,我只是在扩展抽象类的代码中创建一个模拟类,然后在我的单元测试中使用该类...

In the past when I wanted to mock an abstract class I'd simply create a mocked class in code that extended the abstract class, then used that class in my unit testing...

public abstract class MyConverter : IValueConverter
{
    public abstract Object Convert(...);

    public virtual Object ConvertBack(...) { ... }
}

private sealed class MockedConverter : MyConverter { ... }

[TestMethod]
public void TestMethod1()
{
    var mock = new MockedConverter();

    var expected = ...;
    var actual = mock.ConvertBack(...);

    Assert.AreEqual(expected, actual);
}

我想养成使用 Moq 的习惯.我不确定如何使用 Moq 来测试我的抽象类的默认返回值.这里有什么建议吗?

I want to get into the habit of using Moq instead. I'm not sure how I'd go about using Moq to test the default return value of my abstract class. Any advice here?

推荐答案

如果将 CallBase 设置为 true,它将调用基类实现.

If you set CallBase to true, it will invoke the base class implementation.

var mock = new Mock<MyConverter> { CallBase = true };

请参阅自定义模拟行为快速入门的自定义模拟行为部分.

如果没有期望覆盖成员,则调用基类实现(也称为 Rhino Mocks 中的部分 Mocks"):默认为 false.

Invoke base class implementation if no expectation overrides the member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false.

这篇关于如何使用 moq 测试抽象类中的具体方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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