Pex - Automated Whitebox Testing for .NET : parameterized mocks

Parameterized Mocks


How to test a method which has a parameter of an interface type? Or of a non-sealed class? We don't know which implementations will later be used when this method is called! And maybe we don't even have any real implementation available at test time.

The conventional answer: mock objects with explicit behavior

A mock object implements an interface (or extends a non-sealed class). It does not represent a real implementation, but just a shortcut that allows the execution of tests using the mock object. It's behavior is manually written as part of the each test case where it is used. Many tools exist which make it easier to write such mock objects and their expected behavior. But it must still be written by hand.

Parameterized Mocks

Instead of hard-coded values in mock objects, Pex can generate the values.
Just as Pex enables Parameterized Unit Testing, Pex also enables Parameterized Mocks.

Parameterized mocks have two different execution modes:

  • choosing, when exploring code, Pex mocks are a source of additional test inputs, and Pex will try its best to choose interesting values,
  • replay, when executing a previously generated test, Pex mocks behave like stubs with behavior (i.e. predefined behavior).

Use PexChoose to obtain auxiliary values for parameterized mocks.

See also:
Martin Fowler's Mocks Aren't Stubs .

(c) Microsoft Corporation. All rights reserved. pex Wiki Documentation 0.93.50813.0