开发者

How to test a method in an abstract class with abstract methods?

开发者 https://www.devze.com 2023-01-14 08:22 出处:网络
It is necessary to check implementation of \'MyMethod\' virtual method in the abstract \'MyAbstractClass\':

It is necessary to check implementation of 'MyMethod' virtual method in the abstract 'MyAbstractClass':

public abstract MyAbstractClass
{
    public void MyMethod()
    {
        Testpassed = true;
    }

    public abstract int StatusCode{get;internal set;} // **EDIT**: internal setter was added

    public bool TestPassed{get;private set;}
}

I've tried to do the following:

[TestMethod()]
{
    Mock<MyAbstractClass> mockClass = new Mock<MyAbstractClass>();
    mockClass.Object.MyMethod();
    Assert.IsTrue(mockClass.Object.TestPassed);
}

on attempt to execute 'MyMethod' the following error is generated:

Method 'set_StatusCode' in type 'MyAbstractClass`2Proxy0434d60c0f4542fb9b4667ead4ca3a18' from a开发者_C百科ssembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation..

Please advise, how could I get the problem resolved?

Thanks a lot!

P.S. Actually, I could inherit from MyAbstractClass and provide implementation for 'StatusCode' property, but I have a bunch of properties to be implemented...


The code that you posted runs fine (except for minor misspellings). I simply could not get it to fail with the same error. Moq implements the abstract property at runtime and makes it return the default value(0 in this case). Try a more recent version of Moq.

I would also caution against putting test logic into the class. If the only purpose of TestPassed is for testing than it definitely doesn't belong there. We could help a great deal more if you post real code.


See this answer about partial mocking and I think you'll have to provide a concrete implementation.


I understand that it's not an answer to your moq question, but anyway. Even if you have a lot of abstract properties, VS makes it extremely easy to add empty (actually, throwing) implementations. So, if MyMethod does not depend on these properties by design, I'd add an empty derived class and test it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号