Search code examples
asp.netunit-testingtestingxunitnsubstitute

error NS1000: Member InvokeMethodAsync can not be intercepted


I am trying to unit test my dotnet function that uses dapr client for service-to-service calls. I mocked the dapr Client but am not able to use the InvokeMethodAsync for the test. I get the error

error NS1000: Member InvokeMethodAsync can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted.

My service function:

public async Task<TransactionResponse> GetTransactionDetails(Transaction transaction){
    // Fetch transaction details from another service
    var response = await _daprClient.InvokeMethodAsync<TransactionResponse>(HttpMethod.Get, "svc-transactions", transaction.id);

    return response;
}

The way I try to mock this in unit test:

// Set up the Dapr client to return the expected response
_daprClient
    .InvokeMethodAsync<TransactionResponse>(HttpMethod.Get, "svc-transactions", "123")
    .Returns(transactionResponse);

I am using xUnit for unit testing along with NSubstitute for mocking in .net 7.0


Solution

  • It seems like DaprClient does not have an interface or an abstract class that can be mocked by NSubstitute and as the documentation of NSubstitute rightly says "If you can’t override a member by manually writing a sub-class, then NSubstitute won’t be able to either!". The way to fix this issue is by creating an interface(IDaprAccessor) around DaprClient and creating a class(DaprAccessor) that implements this interface.

    Then use DaprAccessor everywhere in the code without having to touch DaprClient at all.