如何模拟抽象基类 [英] How to mock An Abstract Base Class

查看:66
本文介绍了如何模拟抽象基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为问题"的基类,还有几个子类,例如"TrueFalse","MultipleChoice","MatchPairs"等.

I have a base class called "Question" and several child classes such as "TrueFalse", "MultipleChoice", "MatchPairs" etc...

基类具有所有子类都使用的逻辑方法,例如发送分数和引发事件.

The base class has methods with logic that all of the child classes use, such as sending off scores and raising events.

我已经为子类设置了单元测试,但是我不确定如何为基类中的方法设置单元测试.

I have set my unit tests up for the child classes but I am not sure how I can setup unit tests for the methods in the base class.

我做了一些搜索,我知道我需要创建一个类的Mock,但是我不确定如何执行此操作,因为我只看到了如何在可实例化对象上执行此操作.

I did some searching and I understand I need to create a Mock of the class but I am not sure how to do this as I have only seen how to do this on an instantiable object.

我有起订量& NUnit安装在项目中,因此理想情况下喜欢使用它.我还是编程的新手,这是我第一次添加单元测试,因此,我感谢您可以给我的任何建议.

I have Moq & NUnit installed in project so ideally id like to use this. I am still new to programming and this is my first time adding unit tests so I appreciate any advice you can give me.

我首先在网站上进行了搜索,发现了两个类似的问题,但是他们没有给出任何有关如何执行此操作的示例,只是需要嘲笑它.

I did a search on site first and found a couple of similar questions but they did not give any example on how to do it, just that it needed to be mocked.

非常感谢.

推荐答案

来自此答案,看起来像您需要的遵循以下原则:

From this answer it looks like what you need is something along these lines:

[Test]
public void MoqTest()
{
    var mock = new Moq.Mock<AbstractBaseClass>();            
    // set the behavior of mocked methods
    mock.Setup(abs => abs.Foo()).Returns(5);

    // getting an instance of the class
    var abstractBaseClass = mock.Object;
    // Asseting it actually works :)
    Assert.AreEqual(5, abstractBaseClass.Foo());
}

这篇关于如何模拟抽象基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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