does AutoMoqCustomization work for abstract classes?
Asked Answered
R

1

6

Please note, I'm somewhat new to TDD, so I will take general advice as well as specific answer.

Neither abstract classes nor interfaces can be instantiated. Clearly Moq can give me a mocked up instance of the ADataFeed in the second test. Why does AutoMoqCustomization work for interfaces IDataFeed but not for abstract classes ADataFeed, instead throwing an InvalidOperationException?

Secondarily, what would be the AutoFixture approach (or TDD generally) be to drive a design that might call for an abstract class with a constructor to require and guarantee certain values, such as a connection string in this case?

[Theory, AutoMoqData]
public void AllDataFeedsHaveAConectionString(
    IDataFeed sut)
{
    var result = sut.GetConnectionString();
    Assert.Null(result);
}

[Fact]
public void AllDataFeedsRequireAConnectionString()
{
    var expected = Guid.NewGuid().ToString();
    var sut = new Mock<ADataFeed>(expected);
    var result = sut.Object.GetConnectionString();
    Assert.Equal(expected, result);
}

[Theory, AutoMoqData]
public void AllDataFeedsRequireAConnectionString2(
    [Frozen] string expected, 
    ADataFeed sut)
{
    var result = sut.GetConnectionString();
    Assert.Equal(expected, result);
}
Raspy answered 14/12, 2012 at 20:43 Comment(6)
AutoMoqCustomization can provide abstract base classes as well as interfaces. Is the constructor of ADataFeed public? If so, make it protected. It's a design error with a public constructor on an abstract classJez
VERY interesting. Ok, moq handles a public constructor on abstract class... autofixture doesn't. Neither work with a private constructor and both work when it is protected. I'll take your word for it that it is a design error... another question for another day. In the interim I'll use protected.Raspy
FTR: msdn.microsoft.com/en-us/library/vstudio/…Jez
Did that resolve your issue?Jez
yes, I think my question is resolved... the second half is probably too expansive and subjective... I just have to get better at TDD. Right now, my testing isn't helping me from getting bogged down in implementation. -- I don't know how to mark your comments as an answer tho.Raspy
The important thing is that you get answers to your questions :) Regarding the second part of the question, do yourself the favor of not creating abstract classes, and everyting will be much simpler :) "Favor object composition over class inheritance."Jez
R
1

Abstract classes with constructors must be marked protected. AutoFixture will not program against abstract classes when the constructor is marked public, as this is a design error.

Raspy answered 19/8, 2013 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.