Mocking?

Test2 Mocking Libraries

Mocking is when you set up a 'pretend' instance of an object, class, method, or function. This 'pretend' version emulates the original weel enough to be used in tests, but removes any messy bits that are hard to provide in the test environment.

There is no shortage of mocking tools on cpan. Most make you want to claw your eyes out.

A while back Mock::Quick came in, and provided a much cleaner API for mocking, but it too had limitations.

The mocking components provided by Test2 (Specifically Test2::Mock) build off the design of Mock::Quick, but fix several shortcomings.

Control
What?

What is a control object?


It is an object that gives you meta-control over a package.


  • A control object is a handle on a mocked package.
  • Always an instance of Test2::Mock.
  • Allows you to add, override, restore, and reset methods.
  • Clears all mocking when destroyed.
  • Nestable.

You can use a control object to manage and 'control' a perl package. Unlike a lot of mocking out there, it respects scope, and cleans up after itself.
Usage

How do I use it?

  • add() will fail if a method is already defined
  • override() will fail if a method is not already defined
  • restore() is like a 'pop' for mocks
  • reset() removes mocking for a method
  • Any method can be used in the constructor
Tools

Test2::Tools::Mock

This package provides sugar for Test2::Mock
mock()    Universal mocking interface
mocked() Check if something is mocked
mock_class()Explicit class mocking
mock_obj() Explicit object mocking
Classes

Class Mocking

The mock() function can usually tell if you are mocking a class If you prefer you can use the explicit form, or the explicit function:
Objects

Object Mocking

Sometimes you do not want to mock out a whole class. Sometimes you just want an object that 'fits' nearly anywhere.