Search code examples
.netasp.net-coremoqxunitasp.net-core-signalr

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

  • 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.