Moq & C #: invalid callback. Setting a method with parameters cannot invoke a callback with parameters
The actual interface signature looks like this
Task<GeneralResponseType> UpdateAsync(ICustomerRequest<IEnumerable<CustomerPreference>> request, CancellationToken cancellationToken, ILoggingContext loggingContext = null);
TestCase:
ICustomerRequest<IEnumerable<CustomerPreference>> t = null;
CancellationToken t1 = new CancellationToken();
LoggingContext t2 = null;
this.customerPreferenceRepositoryMock.Setup(x => x.UpdateAsync(
It.IsAny<ICustomerRequest<IEnumerable<CustomerPreference>>>(),
It.IsAny<CancellationToken>(),
It.IsAny<LoggingContext>()))
.Callback<ICustomerRequest<IEnumerable<CustomerPreference>>,CancellationToken, LoggingContext>((a, b, c) => { t = a ; t1 =b;t2= c; });
The setup throws an exception in the test file as shown below
Invalid callback. Setting up a method with parameters (ICustomerRequest
1,CancellationToken,ILoggingContext) cannot invoke callback with parameters (ICustomerRequest
1, CancellationToken, LoggingContext).
What is wrong, what am I doing?
I checked Moq: Invalid Callback. Setting a method with parameters cannot invoke a callback with parameters
But I didn't see any help.
source to share
As mentioned in the comments, the parameters used Callback
do not match the definition of the method. Although it Setup
uses It.IsAny<LoggingContext>
, the method definition uses the parameterILoggingContext
Change t2
to
ILoggingContext t2 = null;
And upgrade Callback
to
.Callback<ICustomerRequest<IEnumerable<CustomerPreference>>,CancellationToken, ILoggingContext>((a, b, c) => {
t = a;
t1 = b;
t2 = c;
});
or
.Callback((ICustomerRequest<IEnumerable<CustomerPreference>> a,
CancellationToken b,
ILoggingContext c) => {
t = a;
t1 = b;
t2 = c;
});
It will work anyway.
I would also like to report that it Setup
returns completed Task
to allow the test to flow asynchronously as expected.
this.customerPreferenceRepositoryMock
.Setup(x => x.UpdateAsync(
It.IsAny<ICustomerRequest<IEnumerable<CustomerPreference>>>(),
It.IsAny<CancellationToken>(),
It.IsAny<LoggingContext>()))
.Callback((ICustomerRequest<IEnumerable<CustomerPreference>> a,
CancellationToken b,
ILoggingContext c) => {
t = a;
t1 = b;
t2 = c;
//Use the input to create a response
//and pass it to the `ReturnsAsync` method
})
.ReturnsAsync(new GeneralResponseType()); //Or some pre initialized derivative.
Review Moq QuickStart for a better understanding of how to use the framework.
source to share