【问题标题】:moq a class that IS derived from the same interface as the one being moq'd起订量是从与起订量相同的接口派生的类
【发布时间】:2014-05-22 18:32:31
【问题描述】:

我是整个 MOQ 运动的新手......顺便说一句,这很酷......我现在正在嘲笑各种东西......

无论如何,我遇到了这种情况,想知道如何模拟它。

我有一个类实现了我想模拟的接口:

public interface ImyInterface
{
    void doit();
}

public abstract class myBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class
{
    protected TChannel Channel { get; private set; }

    // ICommunicationObject implementation not shown
}

public class myIIntClass : myBase<ImyInterface>, ImyInterface
{
    public myIIntClass()
    {
    }

    public void doit()
    {
         Channel.doit();
    }
}

我认为我的最小起订量测试并没有模拟任何东西......但我不确定并希望对如何正确编写它或重构我的课程有所了解:

这是我目前的最小起订量测试:

MyClass myClass = null;

Mock<ImyInterface> moq = new Mock<ImyInterface>();
moq.Setup(x => x.doit());

myClass = (MyClass)moq.Object;

myClass.doit();

moq.VerifyAll();

感谢一位 moqer 到另一位... :-)

【问题讨论】:

    标签: c# class interface moq


    【解决方案1】:

    我觉得你可能错过了在这里嘲笑的意义。您模拟存在于您正在测试的工作单元中的依赖项。所以,假设我在MyClass的具体实现中测试doit;我想确保它正常工作。现在,假设该方法依赖于另一个类;它调用一个返回布尔值的方法。我想做的是模拟那个类,因为我想确保MyClass.doit在返回true时表现正确在返回false时表现正确。

    看,在上面的例子中,我所做的是确保没有其他依赖项影响MyClass.doit的代码流;我强迫 MyClass.doit 沿着非常具体的 路径前进;我想测试那条路径。

    您创建的代码实际上没有执行任何操作,因为它只是执行模拟的方法。

    【讨论】:

      【解决方案2】:

      您不会模拟/存根被测单元。如果你在测试doIt(),你不要模拟它,你模拟它的(或类)依赖。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-07
        • 1970-01-01
        • 2016-08-25
        • 2020-12-06
        • 2017-03-21
        相关资源
        最近更新 更多