简体   繁体   English

使用Moq测试抽象类,而无需定义伪造的实现类

[英]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. 我想确保在调用SomeMethod调用ValidateStronglyTypedData

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.' System.ArgumentException:'使用ItExpr.IsNull而不是null参数值,因为它会阻止正确的方法查找。

I have tried ItExpr and still doesn't work. 我已经尝试过ItExpr ,但仍然无法正常工作。 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);    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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