C
C#2y ago
shivam51

❔ Not able to mock a daprclient function in dotnet

I am unit testing a function where I use the InvokeMethodAsync method of DaprClient but I constantly get the error:
error NS1000: Member InvokeMethodAsync can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted.
error NS1000: Member InvokeMethodAsync can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted.
. for the code
_daprClient
.InvokeMethodAsync<TransactionResponse>(HttpMethod.Get, "svc-transactions", "123")
.Returns(transactionResponse);
_daprClient
.InvokeMethodAsync<TransactionResponse>(HttpMethod.Get, "svc-transactions", "123")
.Returns(transactionResponse);
How to fix this? I am using xUnit along with nSubstitute for mocking.
4 Replies
Denis
Denis2y ago
The error tells you exactly what needs to be done - use an abstract class or interface. Using the dapper class directly is not possible with mocking, but it is possible with stubbing and shimming - that is the old way of decoupling monolithic code for testing purposes So, you could abstract your dapper class by wrapping it into a new class And that class would inherit an interface With that, you can now mock the interface however you want
shivam51
shivam51OP2y ago
Can you share some examples in this direction? DaprClient doesn't have any interface defined for it.
Denis
Denis2y ago
Create an interface that has the same methods as the daprclient (methods that use need and use, not necessary to create every method) E.g., call the interface IDaprClientWrapper Create a class that inherits the IDaprClientWrapper interface. The class will also have a private field of the DaprClient Map the daprclient to the inherited methods in the class Thought your code, replace the Daprclient with the interface
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server