有没有办法使用字符串参数而不是表达式来设置Moq Mock?您可以使用受保护功能的受保护扩展来执行此操作,但如果公开,则会引发异常。例如,以下是使用Moq设置受保护的void函数的方法:
myMock.Protected().Setup("MyProtectedFunction");
我希望能够使用公共功能做同样的事情。如果我能做到这一点,我已经有一些反射代码可以返回我需要模拟的所有函数的名称,我希望可以在此基础上构建,以避免在一个巨大的工厂类上设置许多函数。
答案 0 :(得分:3)
有趣的问题,这几乎可以使用表达式。由于setup方法采用表达式,因此可以在运行时构建它。
在编译时需要发生的唯一一点是根据模拟方法的返回类型将表达式转换为适当的lambda类型。不幸的是,Moq没有提供Setup
过载的裸Expression
,否则可能会在运行时100%做你想做的事。
public abstract class Fruit
{
}
public class Apple :Fruit
{
}
public interface IFactory {
Fruit CreateFruit(string type);
void VoidMethod(int intParameter);
}
[TestClass]
public class UnitTest1 {
[TestMethod]
public void TestMethod1() {
var factoryMock = new Mock<IFactory>();
Expression factoryCall = Expression.Lambda(
Expression.Call(Expression.Variable(typeof(IFactory), "f"), "CreateFruit", new Type[]{}, Expression.Constant("Apple")),
Expression.Parameter(typeof(IFactory), "f"));
//factoryMock.Setup(f=>f.CreateFruit("Apple")).Returns(new Apple());
factoryMock.Setup((Expression<Func<IFactory, Fruit>>)factoryCall).Returns(new Apple());
var ret = factoryMock.Object.CreateFruit("Apple");
Assert.IsInstanceOfType(ret, typeof(Apple));
}
}