我很难解决这个问题。任何帮助是极大的赞赏。我的restClient.Object获取一个null异常。当我检查restClient的.Object时,我得到了
消息:调用目标已抛出异常。
内部异常:值不能为null。参数名称:source
堆栈跟踪:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
at Moq.Mock`1.<InitializeInstance>b__2()
at Moq.PexProtector.Invoke(Action action)
at Moq.Mock`1.InitializeInstance()
at Moq.Mock`1.OnGetObject()
at Moq.Mock.GetObject()
at Moq.Mock.get_Object()
at Moq.Mock`1.get_Object()
是的,我指的是这行代码:
var client = new IncidentRestClient(**restClient.Object**);
我是否错误地嘲笑对象?
[Test]
public void Insert_Method_Throws_exception_if_response_StatusCode_is_not_Created()
{
//Arrange
var restClient = new Mock<RestClient>();
restClient.Setup(x => x.Execute<RootObject>(It.IsAny<IRestRequest>()))
.Returns(new RestResponse<RootObject>
{
StatusCode = HttpStatusCode.BadRequest
});
var client = new IncidentRestClient(restClient.Object);
Assert.Throws<Exception>(() => client.CreateNewIncident(insertIncidentRequest));
}
答案 0 :(得分:2)
卸载并重新安装Moq对我不起作用。相反,将Mock对象上的CallBase
属性设置为true可以解决问题:
var restClientMock = new Mock<RestClient> { CallBase = true };
答案 1 :(得分:0)
问题已经解决。我不得不卸载并重新安装Moq与nuget。