Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

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 assembly '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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...