【问题标题】:Trying to moq a class but am unable to access non interfaced methods尝试起订量一个类,但无法访问非接口方法
【发布时间】:2019-02-08 17:04:43
【问题描述】:

告诉我是否有接口

public interface IVehicle<T>
{
    string Drive();
    string Stop();
}

还有两个类 Car() 和 Aeroplane()

每个都有一个使用接口执行操作的类

public class CarActions : IVehicle<Car>
{
    public string Drive()
    {
        return "Go";
    }

    public string Stop()
    {
        return "Stop";
    }
}

public class AeroplaneActions : IVehicle<Aeroplane>
{
    public string Drive()
    {
        return "Go";
    }

    public string Stop()
    {
        return "Stop";
    }

    public virtual string Fly()
    {
        return "Fly";
    }     
}

当我模拟 Airplane 类时,它不会找到 fly() 方法,因为它不是接口的一部分

  Mock<AeroplaneActions> mockedDirectly = new Mock<AeroplaneActions>();

        mockedDirectly.Setup(method => method.Drive()).Returns("Drive");
        mockedDirectly.Setup(method => method.Stop()).Returns("Stop");
        mockedDirectly.Setup(method => method.Fly()).Returns("Fly");

我已经尝试直接模拟 Actions 类,它确实有效,但是在这种情况下我需要将我的方法更改为 virtual,我想避免这种情况。

        Mock<AeroplaneActions> mockedDirectly = new Mock<AeroplaneActions>();

        mockedDirectly.Setup(method => method.Drive()).Returns("Drive");
        mockedDirectly.Setup(method => method.Stop()).Returns("Stop");
        mockedDirectly.Setup(method => method.Fly()).Returns("Fly");

我想知道除了使用虚拟方法之外是否还有其他替代方法?

【问题讨论】:

  • 你为什么要嘲笑AeroplaneActions - 那是你的实现。您应该模拟依赖项(或接口) - 您要测试的究竟是什么?
  • 我之所以尝试直接mock AeroplaneActions是因为方法'fly()'只存在于实现中。如果我尝试只mock接口,我将无法访问这个作为IVehicle 的方法只有drive()stop()。我应该为fly() 等任何独特的方法创建更多接口并分别测试它们吗?
  • 请显示您要测试的代码。也许您可以为AeroplaneActions 使用另一个接口,例如public interface IAeroplane&lt;T&gt; : IVehicle&lt;T&gt; { string Fly(); }。然后应该可以模拟这个接口var m = new Mock&lt;IAeroplane&lt;Aeroplane&gt;&gt;()。然后像这样class AeroplaneActions : IAeroplane&lt;Aeroplane&gt;.
  • 我已添加此代码及其工作,感谢您的回复。

标签: c# unit-testing moq mstest


【解决方案1】:

也许您可以为AeroplaneActions 创建另一个接口,它将继承自IVehicle&lt;T&gt; 并具有Fly 方法,例如像这样:

public interface IAeroplane<T> : IVehicle<T> 
{ 
    string Fly(); 
}. 

那么AeroplaneActions类就会实现这个接口:

AeroplaneActions : IAeroplane<Aeroplane>

然后应该可以模拟这个接口:

var mock = new Mock<IAeroplane<Aeroplane>>(). 

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2014-08-27
    • 2016-08-25
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多