c#Moq一种带有可选参数的方法
我无法为具有可选参数的方法设置模拟。假设我有一个类和接口,如:c#Moq一种带有可选参数的方法,c#,unit-testing,moq,C#,Unit Testing,Moq,我无法为具有可选参数的方法设置模拟。假设我有一个类和接口,如: public class Bird : iBird { public void Chirp(string name = "BigBird") { System.Diagnostics.Debug.WriteLine(name); } } public interface iBird { void Chirp(string name = "Tweetie"); } 如果我使用参数设置
public class Bird : iBird
{
public void Chirp(string name = "BigBird")
{
System.Diagnostics.Debug.WriteLine(name);
}
}
public interface iBird
{
void Chirp(string name = "Tweetie");
}
如果我使用参数设置Chirp method mock:
[TestClass]
public class BirdTests
{
[TestMethod]
public void chirpTest()
{
var c = new Mock<Bird>();
c.Setup(x => x.Chirp(It.IsAny<string>()));
c.Object.Chirp("Woody");
}
}
[TestClass]
公营雀鸟测试
{
[测试方法]
公开测试()
{
var c=新的Mock();
c、 设置(x=>x.Chirp(It.IsAny());
c、 对象。啁啾(“伍迪”);
}
}
当我运行测试时,我得到:
测试方法BirdTests.chirpTest引发异常:
System.NotSupportedException:非虚拟服务器上的设置无效
(在VB中可重写)成员:x=>x.Chirp(It.IsAny())
如果我取出It.IsAny()函数,它将无法编译
如何模拟此方法?问题实际上是该方法未标记为
虚拟
,而不是该方法具有可选参数:
测试方法BirdTests.chirpTest引发异常:System.NotSupportedException:非虚拟(在VB中可重写)成员上的设置无效:x=>x.Chirp(It.IsAny())
为了用Moq模拟一个方法,必须将该方法标记为
virtual
,以便Moq生成的代理类可以提供它自己的模拟方法的实现。从错误消息判断,问题似乎在于该方法不是virtual
,而不是可选参数,我是瞎子。那么,如果你不添加答案,我该如何给你打分呢?如果你模拟iBird
,我可以添加更详细的答案,它应该可以正常工作。请注意,当嘲笑具体对象时,你也应该考虑是否应该调用基类方法。卡莱布,你说得对。工作得很有魅力。