Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq To Test An Abstract Class

I am trying to run a unit test on a method in an abstract class. I have condensed the code below:

Abstract Class:

public abstract class TestAb
{
    public void Print()
    {
        Console.WriteLine("method has been called");
    }
}

Test:

[Test]
void Test()
{
    var mock = new Mock<TestAb>();
    mock.CallBase = true;
    var ta = mock.Object;
    ta.Print();
    mock.Verify(m => m.Print());
}

Message:

Method is not public

What am I doing wrong here? My goal is to test the methods inside the abstract class using he Moq framework.

like image 474
Guerrilla Avatar asked Dec 15 '13 06:12

Guerrilla


People also ask

Can we mock abstract class using Moq?

Getting started with MoqMoq can be used to mock both classes and interfaces.

Can you test an abstract class?

The answer is: always test only concrete classes; don't test abstract classes directly . The reason is that abstract classes are implementation details. From the client perspective, it doesn't matter how Student or Professor implement their GetSignature() methods.

How do you spy an abstract class?

The Mockito. spy() method is used to create a spy instance of the abstract class. Step 1: Create an abstract class named Abstract1_class that contains both abstract and non-abstract methods. Step 2: Create a JUnit test case named Abstract1Test.

Can you JUnit test an abstract class?

With JUnit, you can write a test class for any source class in your Java project. Even abstract classes, which, as you know, can't be instantiated, but may have constructors for the benefit of “concrete” subclasses.


1 Answers

The message is because your Test() method is not public. Test methods need to be public. Even after making the test method public it will fail as you can only verify abstract/virtual methods. So in your case you will have to make the method virtual since you have implementation.

like image 154
Adarsh Shah Avatar answered Sep 18 '22 18:09

Adarsh Shah