Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fake generic method with FakeItEasy without specifying type

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!

like image 462
Rokey Ge Avatar asked Apr 04 '14 14:04

Rokey Ge


People also ask

Can a non generic class have a generic method?

Yes, you can define a generic method in a non-generic class in Java.

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

How do you find the type of generic type?

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.

How does a generic method differ from a generic type?

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.


1 Answers

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?

like image 82
Blair Conrad Avatar answered Sep 29 '22 01:09

Blair Conrad