简体   繁体   中英

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.

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.

如果您想在这样的抽象类上模拟方法,那么您需要使其成为虚拟的或抽象的。

My answer for the similar question :

As a workaround you can use not the method itself but create virtual wrapper method instead

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

    public void Print()
    {
        PrintReal();
    }
}

And then override it in the test class:

abstract class TestAbDelegate: TestAb{

     public abstract override  bool PrintReal();
}

Test:

[Test]
void Test()
{
    var mock = new Mock<TestAbDelegate>();
    mock.CallBase = true;

   mock.Setup(db => db.PrintReal());

    var ta = mock.Object;
    ta.Print();

    mock.Verify(m => m.PrintReal());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM