我有一个接口,其上的方法定义如下:
IEnumerable<dynamic> ExecuteDynamic(string query, object param = null)
我正在尝试测试的代码调用这样的接口:
var result = _repository.ExecuteDynamic("cart_getNewXsession", new
{
HTTP_USER_AGENT = _context.Request.UserAgent,
RHID = _context.Request.UserHostAddress,
scid = GetSourceCode(),
wsid = _systemSettings.GetWSID(),
HTTP_REFERER = _context.Request.UrlReferrer == null ? "" : _context.Request.UrlReferrer.ToString(),
QUERY_STRING = _context.Request.Url.Query
});
我正试图模仿这个方法的调用:
var repository = new Mock<>();
var sprocReturnValue = (new[] { (dynamic)new { guid = "123456" } }).AsEnumerable();
repository.Setup(x => x.ExecuteDynamic("cart_getNewXsession", It.IsAny<object>()))
.Returns<IEnumerable<dynamic>>(x => sprocReturnValue);
但是,当我在测试中运行时,我收到错误:
System.Reflection.TargetParameterCountException : Parameter count mismatch.
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at Moq.Extensions.InvokePreserveStack(Delegate del, Object[] args)
at Moq.MethodCallReturn`2.Execute(ICallContext call)
at Moq.Interceptor.Intercept(ICallContext invocation)
at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IRepositoryProxy.ExecuteDynamic(String query, Object param)
Services\SessionService.cs(68,0): at Core.Services.SessionService.GetNewXS()
Services\SessionService.cs(49,0): at Core.Services.SessionService.BuildXS()
Services\Session\BuildXS.cs(78,0): at Core.Tests.Services.Session.BuildXS.When_XS_In_Cookie_Use_XS_From_Cookie()
在这种情况下,我该如何设置我的模拟对象?
答案 0 :(得分:1)
问题是Returns
方法。
以下内容将起作用(LINQPad中的示例):
void Main()
{
var repository = new Mock<IRepository>();
var sprocReturnValue = (new[] { (dynamic)new { guid = "123456" } }).AsEnumerable();
repository.Setup(x => x.ExecuteDynamic("cart_getNewXsession", It.IsAny<object>()))
.Returns(sprocReturnValue);
var _repository = repository.Object;
var result = _repository.ExecuteDynamic("cart_getNewXsession", new { Whatever = 0 });
Console.WriteLine(result.First().guid); // 123456
}
public interface IRepository
{
IEnumerable<dynamic> ExecuteDynamic(string query, object param = null);
}