【发布时间】: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<T> : IVehicle<T> { string Fly(); }。然后应该可以模拟这个接口var m = new Mock<IAeroplane<Aeroplane>>()。然后像这样class AeroplaneActions : IAeroplane<Aeroplane>. -
我已添加此代码及其工作,感谢您的回复。
标签: c# unit-testing moq mstest