'Getting System.Reflection.TargetInvocationException for a call to Mock.Object

I'm not sure as to why this is happening but when I am trying to call userIdProvider.GetUserId(_mockHubConnectionContext.Object) it throws System.Reflection.TargetInvocationException at _mockHubConnectionContext.Object. My constructor for the test class includes:

_mockConnectionContext = new Mock<ConnectionContext>();
_mockLoggerFactory = new Mock<ILoggerFactory>();
_mockHubConnectionContext = new Mock<HubConnectionContext>(_mockConnectionContext.Object, new HubConnectionContextOptions(), _mockLoggerFactory.Object);

The method signature for UserIdProvider.GetUserId() is:

public string GetUserId(HubConnectionContext hubConnectionContext)

To give you some more context, this started happening when we tried to move from .NET Core 3.1 to .NET 6.0.



Solution 1:[1]

I solved this issue quite a while back. Seeing no concrete answer to the question I decided to post the answer myself.

Changing the connection context passed to Mock<HubConnectionContext> from a mock to some concrete implementation like DefaultConnectionContext solved the issue. More details as to why this was causing an error can be found here.

Solution 2:[2]

TargetInvocationException is a wrapper around an exception thrown by something else, so the first thing you'll want to do is look at InnerException to check the message \ stack trace.

That will hopefully point you in the right direction for where the problem is.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aritra Sur Roy
Solution 2 lee-m