How to mock An Abstract Base Class
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());
}
Guerrilla
Updated on June 07, 2022Comments
-
Guerrilla almost 2 years
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.
-
Guerrilla over 10 yearsThank you Adam. This is what I needed, I dont know why I couldnt find this when I searched, thankyou.
-
Guerrilla over 10 yearsI cannot get this working. I get error "Method is not public". I used
var mock = new Mock<Question>(new object[]{"question text",true}); var Question = mock.Object; Question.Ask(); mock.Verify(m => m.Ask());
Method is public but I think issue is that class is abstract. -
Adam Rackis over 10 years@guerr - I don't think that's how you set up your mock. I would create it the same way the code does, and then set up your mocked values with Setup, or whatever other means moq gives you
-
Guerrilla over 10 yearsIf I use setup to define what the method returns then am I testing the logic inside the method? Isnt that for when im testing a class that uses another class and I want to fake the behaviour it returns? Sorry for the noob questions, I have done a lot of reading but this is my first time actually tackling this. I really appreciate the help
-
Guerrilla over 10 yearsI made a new question with the code i used and message I got so it is clearer - stackoverflow.com/questions/20591869/…
-
Adam Rackis over 10 yearsYour new question is worded well, I upvoted it. Hopefully you'll get a good answer.
-
devyJava about 2 yearsWhat is the purpose of overriding
CheckCorrect
in MultipleChoiceTest abstract class when it isn't being executed in your test. Am I missing something here? -
devyJava about 2 yearsHow can this work when the abstract class does not have a zero parameter argument constructor?