I’m using NUnit and Moq to test a class which uses a generic WCF service client wrapper I wrote, and I’ve run into an error I can’t figure out. I have the following interface:
public interface IService
{
void Call();
}
…implemented by the following service client:
public class ServiceClient : ClientBase<IService>, IService
{
public void Call()
{
}
}
…and wrapped by this class with the following generic constraints:
public class ServiceClientWrapper<TClient, TService>
where TClient : ClientBase<TService>, TService
where TService : class
{
public virtual TService CreateServiceClient()
{
return (TService)Activator.CreateInstance<TClient>();
}
}
To make it testable I have a wrapper factory which I can mock. The wrapper factory interface is this:
public interface IServiceClientWrapperFactory
{
ServiceClientWrapper<TClient, TService>
CreateServiceClientWrapper<TClient, TService>()
where TClient : ClientBase<TService>, TService
where TService : class;
}
I test this set up using this code:
// A mock IService to return from my mock service wrapper:
var mockService = new Mock<IService>();
// A mock client wrapper to return from my mock wrapper factory:
var mockClientWrapper =
new Mock<ServiceClientWrapper<ServiceClient, IService>>();
mockClientWrapper
.Setup(mcw => mcw.CreateServiceClient())
.Returns(mockService.Object);
// A mock wrapper factory to inject into a client object:
var mockClientWrapperFactory = new Mock<IServiceClientWrapperFactory>();
mockClientWrapperFactory
.Setup(mcwf => mcwf.CreateServiceClientWrapper<ServiceClient, IService>())
.Returns(mockClientWrapper.Object);
// Get the mock client wrapper from the mock wrapper factory - boom!
mockClientWrapperFactory.Object
.CreateServiceClientWrapper<ServiceClient, IService>();
The error is:
GenericArguments[0], ‘TService’, on
‘ServiceClientWrapper`2[TClient,TService]’
violates the constraint of type
parameter ‘TClient’.
The constraints are the same wherever I’ve stated them, it compiles and runs just fine, the error isn’t thrown if I implement IServiceClientWrapperFactory and run it without Moq… any ideas?
I played with the code a bit, and I get the same result. As far as I can tell, there isn’t anything wrong with your definitions.
It seems that it might be a bug in Moq, when implementing mocks that have various combinations of generic constraints on them.
I tried removing various constraints (and commenting out or modifying code, as required). It seems if I remove
TServicefromwhere TClient : ... , TService, then I don’t get this error.This seems further corroborated by the fact that there have been multiple similar bugs in the past:
FYI, the version I used to repro your problem was: Moq.4.0.10827, NET40 (not NET40-RequiresCastle)