【发布时间】:2018-06-29 07:08:22
【问题描述】:
我正在尝试通过使用 Linq Expression methods Api 来使用 Moq 的 Verify 方法(以验证是否调用了方法)。
以下是两个单元测试。 TestMethod1 正在使用一个简单的 lambda 表达式,它工作正常。
我想在TestMethod2中实现和TestMethod1一模一样;但是通过使用 Linq 表达式方法 Api。但是当我运行 TestMethod2 时,它给出了异常:
Castle.Proxies.ISomeInterfaceProxy 和 Moq.Mock 类型之间没有定义强制表达式。
谁能告诉我我做错了什么?
using System;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest2
{
public interface ISomeInterface
{
void DoSomething(string param1, string param2);
}
public class ImplementationClass
{
private ISomeInterface _someInterface;
public ImplementationClass(ISomeInterface someInterface)
{
_someInterface = someInterface;
}
public void Investigate(string param1, string param2)
{
_someInterface.DoSomething(param1, param2);
}
}
[TestMethod]
public void TestMethod1()
{
Mock<ISomeInterface> myMock = new Mock<ISomeInterface>();
ImplementationClass myImplementationClass = new ImplementationClass(myMock.Object);
string Arg1 = "Arg1";
string Arg2 = "Arg2";
myImplementationClass.Investigate(Arg1, Arg2);
Expression<Action<ISomeInterface>> lambdaExpression = m => m.DoSomething(Arg1, Arg2);
myMock.Verify(lambdaExpression);
}
[TestMethod]
public void TestMethod2()
{
Mock<ISomeInterface> myMock = new Mock<ISomeInterface>();
ImplementationClass myImplementationClass = new ImplementationClass(myMock.Object);
string Arg1 = "Arg1";
string Arg2 = "Arg2";
myImplementationClass.Investigate(Arg1, Arg2);
var methodInfo = myMock.Object.GetType().GetMethod("DoSomething");
var call = Expression.Call(Expression.Constant(myMock.Object), methodInfo, Expression.Constant(Arg1), Expression.Constant(Arg2));
Expression<Action<ISomeInterface>> expression = Expression.Lambda<Action<ISomeInterface>>(call, Expression.Parameter(typeof(ISomeInterface)));
myMock.Verify(expression); // Exception comes from here.
}
}
}
【问题讨论】:
-
哪一行代码抛出异常?
-
在TestMethod2中,myMock.Verify(expression) 抛出异常
标签: c# lambda expression moq verify