您能否使接口的 Moq 模拟通过实现该接口的类型的强制转换和空检查?

特别是在我的情况下,如果 Foo 是一个属性 IBar,并且我已经嘲笑了 Foo。


if (!(Foo is Bar bar))

{

    Logger.Error("ERROR, NOT CORRECT TYPE");

    return false;

}

如果可能的话,我想让我的Mock<IBar>不Mock<Bar>。


完整的未片段示例:


Bar 类,什么 Foo 属性被“强制转换”为:


public class Bar : IBar

{

    // Stuff I don' care about because I am using a mock

}

测试类:


[TestClass]

public class InuEmulatorCustomBehaviourBaseTests

{

    Mock<IBar> _IBarMock;


    [TestInitialize]

    public void TestInitialise()

    {

        _IBarMock= new Mock<IBar>();


        // Code used to set up a spy to check log messages produced during each test

    }


    [TestMethod]

    public void UnitUnderTest_Initialise_LogsNoErrors_when_Foo_is_of_type_Bar_Test()

    {

         //Arrange

         var unitUnderTest = new UnitUnderTest { Foo = _IBarMock.Object };


         //Act

         unitUnderTest.Initialise();


         //Assert

         Assert.AreEqual(0, _spiedLogMessage.Count, "An error was logged when none should have been.");

    }


    [TestCleanup]

    public void TestCleanup()

    {

        // Code used to reset the spy to check log messages produced during each test

    }

}

和 UnitUnderTestClass:


public class UnitUnderTest

{

    IBar _foo;

    public IBar Foo

    {

        private get

        {

            return _foo ?? _foo = new Bar(); 

        }

        set { _foo = value; } //set as new Mock<IBar> during unit test

    }


    public bool Initialise()

    {

        if (!(Foo is Bar bar))

        {

            Logger.Error("ERROR, NOT CORRECT TYPE");

            return false; //don't want my test to follow this path

        }

        return true; //want my test to follow this path

    }

}

我明白为什么上述测试失败,我想知道我是否可以以及如何在不使用Mock<Bar>.


慕田峪7331174
浏览 174回答 1
1回答

呼啦一阵风

恕我直言,这是不可能的。根本原因是你的被测单元声称它可以与实现接口的东西一起工作(通过属性类型),但在它的实现中它测试特定的实现。对我来说,这是一个很大的代码味道,因为如果被测单元告诉外部世界它只需要一个特定的接口,它就不应该依赖于特定的实现。也许该方法不应该测试特定类型,而是如果将某些属性Foo设置为特定值,则很容易模拟。
打开App,查看更多内容
随时随地看视频慕课网APP