Mock object creation by example?

Discussion in 'Python' started by John J. Lee, Jul 9, 2003.

  1. John J. Lee

    John J. Lee Guest

    I had the bright idea a week or two ago to construct mock objects (for
    unit testing) "by example" by calling methods on a generic mock
    object.

    Say we have a class Bar, and we want to check that, when we use
    BarUser in a particular way, BarUser first calls method Bar.xyzzy with
    args "foo" and bar=2, then method Bar.do_nothing.

    # first, construct a mock object by example:
    m = Mock()
    m.xyzzy("foo", bar=2)
    m.do_nothing()

    # then run the test
    m.start_test()
    bu = BarUser(m)
    bu.method_a("foo", 1, bar=2)
    bu.method_b()


    That's it, essentially.

    It does needs a bit more complication than that to be useful. For
    example, a way specifying return values and exceptions to be expected,
    a way of asking it to pretend to be a class object, ways of making
    slightly fuzzy the expected number and order of calls and their
    arguments, and the ability to easily inherit from Mock and override
    methods etc. For example, you might say:

    m.return_something().returns(1)
    m.raise_something().raises(Exception)


    Of course, it turns out somebody else thought of it first. For
    example, in Java:

    http://www.abstrakt.de/mockcreator.html


    Anybody know if something like this already exists in Python?

    Actually, looking at the examples on mockcreator's web page does lead
    give you the suspicion that they've had some contact with a certain
    language <wink>:

    // setup of MockObjects
    MockFoo mockFoo = new MockFoo();
    mockFoo.expectDoSomething( "nobody expects", "the spanish inquisition" );

    // Testcode
    assertEquals( "the spanish inquisition", mockFoo.doSomething( "nobodyExpects" ) );

    // Verify
    mockFoo.verify();


    John
     
    John J. Lee, Jul 9, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ken
    Replies:
    0
    Views:
    378
  2. John J. Lee
    Replies:
    4
    Views:
    376
    John J. Lee
    Nov 8, 2003
  3. Remy Blank
    Replies:
    3
    Views:
    918
    Lothar Scholz
    Mar 6, 2004
  4. jon wayne
    Replies:
    9
    Views:
    731
    Jim Langston
    Sep 22, 2005
  5. mfaine
    Replies:
    0
    Views:
    346
    mfaine
    Aug 23, 2007
Loading...

Share This Page