How to mock conditional parameters?

18 views
Skip to first unread message

subimage

unread,
Mar 12, 2010, 8:08:37 PM3/12/10
to mocha-developer
Here's another tricky testing situation I'm dealing with.

CIM has a "create_profile" method. It should return true if passed a
unique value. If it's passed the exact same value a second time it
should return false. The value is unknown and unpredictable.

How do I stub this?

James Mead

unread,
Mar 13, 2010, 10:10:25 AM3/13/10
to mocha-d...@googlegroups.com

If you introduce an adapter for the third party service as I described
in my previous message, you may be able to encapsulate the "unique
value" behaviour within the adapter so that you don't need to deal
with this problem when stubbing the adapter.

If I understand you correctly, it sounds as if the "unique value" is
generated by the app code and not by the third party service. This
means that by definition, the value is known and predictable. Even if
it's a random number, since you are in control of the app code, you
can change or stub the generation of the "unique value" for the
duration of a test.

Rather than talking in the abstract, it might be easier if you post
some example code.

Regards, James.

subimage

unread,
Mar 13, 2010, 1:57:23 PM3/13/10
to mocha-developer
Hey James, thanks for the quick response.

The adapter I'm testing is actually ActiveMerchant in this instance.

> If you introduce an adapter for the third party service as I described
> in my previous message, you may be able to encapsulate the "unique
> value" behaviour within the adapter so that you don't need to deal
> with this problem when stubbing the adapter.
>
> If I understand you correctly, it sounds as if the "unique value" is
> generated by the app code and not by the third party service. This
> means that by definition, the value is known and predictable. Even if
> it's a random number, since you are in control of the app code, you
> can change or stub the generation of the "unique value" for the
> duration of a test.

You're correct. The unique value is based on time - and could be
stubbed out. However, I wanted to test the behavior, not the
implementation in this instance. I thought that if I stubbed out the
expected values that I'm using for keys that it would make the tests
brittle. I was hoping that there was some way to match this with
Mocha's parameter matchers that I was missing.

I just ended up going with a mocked object in test/mocks that I'm
using at this point, which seems to work OK for my needs and is fairly
flexible while going forward.

- s

James Mead

unread,
Mar 14, 2010, 6:05:39 AM3/14/10
to mocha-d...@googlegroups.com

I'm glad you've found a solution that you're happy with.

There may be a way of doing what you want with a parameter matcher,
but it's difficult to help without seeing a concrete example of the
problem.

Cheers, James.

Reply all
Reply to author
Forward
0 new messages