locked
A test for a method with an abstract class in parameter list RRS feed

  • Question

  • I have the methods like this one:

    void MyMethod (MyAbstractClass myAbstractClass)

    this abstract class is a huge third-party class with many members. Most of those members I don't need to use.

    Now I want to create a Test method for the MyMethod. All I can do now is to create a class which is derived from MyAbstractClass and use this class for the Test. And this is a tedious work to create this derived class.

    Is there a way to avoid creating this derived class?


    Leonid Ganeline [BizTalk MVP] BizTalk: Internals: Namespaces

    Wednesday, January 30, 2013 6:58 PM

Answers

  • If the members you're interested in are abstract/virtual then you could use a framework like Moq or NSubstitute to generate instances on the fly. E.g. assuming MyAbstractClass has an abstract method called GetTheAnswer() that returns an Int32, which needs to return an expected value for your test, then you could setup an instance using NSubstitute as follows:

    var myClass = Substitute.For<MyAbstractClass>();
    myClass.GetTheAnswer().Returns(42);
    HTH
    Thursday, January 31, 2013 12:24 AM

All replies

  • In order to test this, you'll need some class that inherits the abstract class.  This means you'll likely need to ipmlement the class fully.

    The only other option would be to (potentially) subclass some other implementation of MyAbstractClass, and override the members you care about.  This may or may not be possible, depending on how the existing implementations are defined.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Mr. Javaman II Wednesday, January 30, 2013 7:49 PM
    Wednesday, January 30, 2013 7:01 PM
  • If the members you're interested in are abstract/virtual then you could use a framework like Moq or NSubstitute to generate instances on the fly. E.g. assuming MyAbstractClass has an abstract method called GetTheAnswer() that returns an Int32, which needs to return an expected value for your test, then you could setup an instance using NSubstitute as follows:

    var myClass = Substitute.For<MyAbstractClass>();
    myClass.GetTheAnswer().Returns(42);
    HTH
    Thursday, January 31, 2013 12:24 AM