chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
I want to test an abstract class where the constructor calls an abstract method.

public abstract MyClass
{
    public MyClass()
    {
        MyMethod();
    }

    protected abstract MyMethod();
}


How can I test this?
asked by paulo.morgado (11k points)

5 Answers

0 votes
Hi Paulo.

Nice one.
the easiest way I see to test this is:

public class Class1 : MyClass
{
  protected override void MyMethod()
  { }
}

[Test]
[VerifyMocks]
public void test()
{
  Mock mock = MockManager.Mock<Class1>(Constructor.NotMocked);
  mock.ExpectCall("MyMethod");

  Class1 target = new Class1();
}
answered by lior (13.2k points)
0 votes
That's how I did it. But I was hoping for something more "Natural"
answered by paulo.morgado (11k points)
0 votes
Its an egg and chicken problem.
In order to set expectations you need to create the MockObject.
When you create the MockObject the constructor is invoked/mocked.

Anyway Ill add this to our future list and see if we can give a good solution for this.
answered by lior (13.2k points)
0 votes
We might get into a little of a purist argument on this one, but I might actually just stub out a derived class and skip mocking altogether. Yeah, a little longer and a little messier, but it doesn't require any special understanding of what's going on for later test maintainers.

public abstract MyClass 
{ 
  public MyClass() 
  { 
    MyMethod(); 
  } 

  protected abstract MyMethod(); 
}

[TestFixture]
publc UnitTests
{
  [Test]
  public void MyMethodGetsCalled()
  {
    DerivedClass testObject = new DerivedClass();
    Assert.IsTrue(testObject.MyMethodWasCalled);
  }
  
  public DerivedClass : MyClass
  {
    public bool MyMethodWasCalled = false;
    
    protected override MyMethod()
    {
      this.MyMethodWasCalled = true;
    }
  }
}
answered by tillig (6.7k points)
0 votes
It works, but it's not fun. :)

Let's get purist here. Isn't that a mock. You can check your expectations in the end.
answered by paulo.morgado (11k points)
...