How do I mock a class without an interface using StructureMap's AutoMocker?

466 Views Asked by At

I am huge proponent of testing and I think having to create extra interface to be able to write unit tests is small price to pay. I have added structure map automocker to test suite and it seems to be absolutely not able to mock class. Rhino mock has ability to mock public classes as long as public methods are marked virtual.

I would like to get rid of interfaces if possible. Any and all help appreciated.

1

There are 1 best solutions below

0
On

Before I answer this, I would just like to point out that it completely defeats the purpose of using StructureMap when you don't use interfaces. (Well, not completely, but defeats enough of the purpose of using it for me to question why you've decided to go with StructureMap in the first place...) You won't get very far in your tests without interfaces or if you do, you're going to have all of your logic sitting in one class or 20-30 classes all tightly coupled, which again is missing the point of using StructureMap. Having said that I think this should work in situations where you need to mock out a concrete class

[Test]
public void TestMethod()
{
    // Arrange
    var service = new RhinoAutoMocker<BusinessRuleService>();
    service.PartialMockTheClassUnderTest();
    service.ClassUnderTest.Expect(x => x.VirtualMethodImTesting());

    // Act
    service.ClassUnderTest.CallableMethod();

    // Assert
    service.ClassUnderTest.VerifyAllExpectations();
    // ... or other stuff ...
}