简体   繁体   中英

Testing abstract class with Moq, without the need of defining fake implementation classes

I have this abstract class, that I want to test. I want to ensure that when SomeMethod is invoked, ValidateStronglyTypedData is called.

public abstract class SomeAbstractClass<TDataType> where TDataType : class
{
    public ResultType SomeMethod(string someParam)
    {
        TDataType tDataType = convert(someParam);
        this.ValidateStronglyTypedData(tDataType);
    }

    protected abstract ResultType ValidateStronglyTypedData(TDataType stronglyTypedData);
}

I've got this:

// Arrange
var mockSomeAbstractClass = new Mock<SomeAbstractClass<TestJsonDataType>>();
var testData = "{ 'testProperty': 'test value' }";
mockSomeAbstractClass.Protected().Setup<ValidationResult>("ValidateStronglyTypedData", It.IsAny<TestJsonDataType>());

// Act
mockSomeAbstractClass.Object.ValidateData(testData);

// Assert
mockSomeAbstractClass.Protected().Verify("ValidateStronglyTypedData", Times.Once(), It.IsAny<TestJsonDataType>());

but at runtime it complains that it cannot find the method. Is it because the protected method is abstract? It fails on the setup with:

System.ArgumentException: 'Use ItExpr.IsNull rather than a null argument value, as it prevents proper method lookup.'

I have tried ItExpr and still doesn't work. I am guessing it has to do with the class being generic.

I'd say why bother with all that mocking when you can just do the real thing?

public class TestClass
{
    private class DerivedTest : SomeAbstractClass<string>
    {
        public bool WasCalled { get; private set; }

        protected override ResultType ValidateStronglyTypedData(string stronglyTypedData)
        {
            this.WasCalled = true;
        }
    }

    [YourFavoriteFrameWorkAttributeForTestMethod]
    public void TestMethod()
    {
         // arrange
         var instance = new DerivedTest();

         // act
         var result = instance.SomeMethod("test");

         // assert
         Assert.IsTrue(instance.WasCalled);    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM