How to mock An Abstract Base Class

帅比萌擦擦* 提交于 2019-12-10 17:26:31

问题


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.

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.

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.

Many thanks.


回答1:


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());
}



回答2:


I was trying to mock an abstract class and this way didn't worked for me. what did work was to create a new class that extended the abstract class

class newclass : abstractClass
{
}

like this I could set the property and test the main method



来源:https://stackoverflow.com/questions/20591155/how-to-mock-an-abstract-base-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!