This covers special considerations when writing unit tests for a cmd2 application.

Testing Commands

The External Test Plugin provides a mixin class with an :meth:`` function that allows external calls to application commands. The app_cmd() function captures and returns stdout, stderr, and the command-specific result data.


If you need to mock anything in your cmd2 application, and most specifically in sub-classes of Cmd or CommandSet, you must use Autospeccing, spec=True, or whatever equivalant is provided in the mocking library you’re using.

In order to automatically load functions as commands cmd2 performs a number of reflection calls to look up attributes of classes defined in your cmd2 application. Many mocking libraries will automatically create mock objects to match any attribute being requested, regardless of whether they’re present in the object being mocked. This behavior can incorrectly instruct cmd2 to treat a function or attribute as something it needs to recognize and process. To prevent this, you should always mock with Autospeccing or spec=True enabled.

Example of spec=True

def test_mocked_methods():
    with mock.patch.object(MockMethodApp, 'foo', spec=True):
        cli = MockMethodApp()