I wonder if there is anyway one can fake up a generic method call, for all possible types (or specified sub-types)?
For example, suppose we have this wonderful IBar interface.
public interface IBar
{
int Foo<T>();
}
Can I fake a dependency to this IBar's Foo call, without having to specify T being any specific type?
[TestFixture]
public class BarTests
{
[Test]
public void BarFooDoesStuff()
{
var expected = 9999999;
var fakeBar = A.Fake<IBar>();
A.CallTo(() => fakeBar.Foo<T>()).Returns(expected);
var response = fakeBar.Foo<bool>();
Assert.AreEqual(expected, response);
}
}
Thanks!
Yes, you can define a generic method in a non-generic class in Java.
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
I'm not aware of any way to do this directly. I don't think DynamicProxy (which FakeItEasy uses) supports open generic types. However, there's a workaround, if you're interested.
There's a way to specify a call to any method or property on a fake. Check out the Where
and WithReturnType
bits in this passing test:
[TestFixture]
public class BarTests
{
[Test]
public void BarFooDoesStuff()
{
var expected = 9999999;
var fakeBar = A.Fake<IBar>();
A.CallTo(fakeBar)
.Where(call => call.Method.Name == "Foo")
.WithReturnType<int>()
.Returns(expected);
var response = fakeBar.Foo<bool>();
Assert.AreEqual(expected, response);
}
}
Still, though, I'm curious about the use for this. Do you have an example test that actually uses the faked interface as a dependency?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With