chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Hello all,

I want make a test case for "GetInfo" method, in which calling generic method (CreateObject<T>) more than once. Which returns result set based on T passed. But I am able to understand, how to mock CreateObject<T> so that I can return different-different result sets. Kindly let me know.

Thanks
asked by sony (7.2k points)

4 Answers

0 votes
Hi Sony,

Just use WhenCalled on CreateObject method few times and each time specify what to return based on the bounded generic argument.
Isolator will know what to return based on the generic argument type bounded type at runtime.

Example.
var fake = Isolate.Fake.Instance<Foo>();
Isolate.WhenCalled(() => fake.CreateObject<A>()).WillReturn(new A());
Isolate.WhenCalled(() => fake.CreateObject<B>()).WillReturn(new B());

var b = fake.CreateObject<B>();
var a = fake.CreateObject<A>();

Assert.AreEqual(typeof(A), a.GetType());
Assert.AreEqual(typeof(B), b.GetType());
answered by ohad (35.4k points)
0 votes
Hi Ohad,

Thanks for your reply, this is pretty helpful. But I am stuck on how to mock private/protected generic method which I can't directly access with fake object. Kindly let me know.

Thanks
answered by sony (7.2k points)
0 votes
Hi Sony,
You should Isolate.NonPublic.WhenCalled together with WithGenericArguments completing statement.

Example:
var fake = Isolate.Fake.Instance<Foo>();
Isolate.NonPublic.WhenCalled(fake, "CreateObject").WithGenericArguments(typeof (A)).WillReturn(new A());
Isolate.NonPublic.WhenCalled(fake, "CreateObject").WithGenericArguments(typeof (B)).WillReturn(new B());
answered by ohad (35.4k points)
0 votes
Thanks Ohad.
answered by sony (7.2k points)
...