I am using Nsubstitute for mocking. To reduce code I want to write a generic class that fakes a generic attribute:
public class Tester<TValue>
where TValue: IValue
{
// this is used inside the class in other methods
private TValue CreateValue()
{
return Substitute.For<TValue>(); // here the compiler has an error
}
}
This code gives a compile error at the marked place:
The type 'TValue' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Substitute.For(params object[])'
This seems obvious, because the implementation of the Substitute
class looks like this:
public static class Substitute
{
public static T For<T>(params object[] constructorArguments) where T : class;
}
What I am wondering about is, why then such a code is possible: Substitute.For<IValue>()
and does not raise an error. Can anybody explain how to do the generic class with the faking right?