jaypman
jaypman

Reputation: 167

RestSharp Moq Object Null Exception C# REST Unit Test

I'm having difficulties trying to figure this out. Any help is greatly appreciated. My restClient.Object gets a null exception. When I inspect the .Object of the restClient I get

Message: Exception has been thrown by the target of an invocation.

Inner Exception: Value cannot be null.Parameter name: source

Stack Trace:

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()

Btw, I'm referring to this line of code:

var client = new IncidentRestClient(**restClient.Object**);

Am I mocking the object incorrectly?

[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));
}

Upvotes: 1

Views: 2088

Answers (2)

nwayve
nwayve

Reputation: 2331

Uninstalling and reinstalling Moq did not work for me. Instead, setting the CallBase property on the Mock object to true did the trick:

var restClientMock = new Mock<RestClient> { CallBase = true };

Upvotes: 2

jaypman
jaypman

Reputation: 167

Issue has been resolved. I had to uninstall and reinstall Moq with nuget.

Upvotes: 0

Related Questions