[Moq] Mocking generic methods

1,721 views
Skip to first unread message

pipoca

unread,
Apr 30, 2010, 5:21:01 PM4/30/10
to Moq Discussions
Is it possible to write a mock for a generic method that wouldn't make
the mocked call lose any of the genericity?

Say I have a method Foo<T>(Bar bar, Baz baz, T quux), in my Quuux
object (note that T is specific to the Foo method, not the Quuux
class). Can I mock a call to Foo that will fire for any value of
quux, for any concrete type of quux?

In particular, I've got a generic call that will be of the type of
several subclasses to an abstract type. The mocking logic is the same
for all of those objects. Can I write a single mock for that, or do I
need to write n mocks, for n = the number of subclasses that I have?

--
Post: moq...@googlegroups.com
Unsubscribe: moqdisc-u...@googlegroups.com

pipoca

unread,
Jun 10, 2010, 9:54:00 AM6/10/10
to Moq Discussions
Bump.

Suppose I've got 3 classes, B, C, and D, all of which inherit from the
abstract class A, and I'm writing a web service. When I deserialize
JSON, I need to deserialize it as the child class, otherwise it will
lose all of the child's information. In my mocks, is there any way to
replace three mocks with just one? Something like replacing :

_serviceHelpers.Setup(sh =>
sh.DeserializeRepresentation<B>(It.IsAny<string>(),
It.IsAny<string>())).Returns((() => _testA as B)).Verifiable(); //
cast as B so the types agree
_serviceHelpers.Setup(sh =>
sh.DeserializeRepresentation<C>(It.IsAny<string>(),
It.IsAny<string>())).Returns((() => _testA as C)).Verifiable();
_serviceHelpers.Setup(sh =>
sh.DeserializeRepresentation<D>(It.IsAny<string>(),
It.IsAny<string>())).Returns((() => _testA as D)).Verifiable();

with:

_serviceHelpers.Setup(sh =>
sh.DeserializeRepresentation<A>(It.IsAny<string>(),
It.IsAny<string>())).Returns((() => _testA).Verifiable();

And have it fire for any subclass of A?

Nick Bronson

unread,
Jun 10, 2010, 10:37:13 PM6/10/10
to moq...@googlegroups.com
Not sure how you'd go about doing this one in moq, might be worth considering a custom mock object for this situation?
Reply all
Reply to author
Forward
0 new messages