How do Java mocking frameworks work?

前端 未结 5 460
攒了一身酷
攒了一身酷 2021-02-03 23:10

This is NOT a question about which is the best framework, etc.

I have never used a mocking framework and I\'m a bit puzzled by the idea. How does it know how to create t

5条回答
  •  一整个雨季
    2021-02-03 23:50

    I will speak of the framework that I use ( jmock ), but others do something very similar.

    How does it know how to create the mock object?

    It does not, you tell the framework that you require a mock object and you give it a type ( ideally an interface ) of the object that you would like to mock. Behind the scenes the mock framework uses a combination of reflection and, sometimes, byte-code rewrites to create a mock object.

    Is it done in runtime or generates a file?

    jMock creates it at runtime.

    How do you know its behavior?

    Mock objects are pretty dumb. You specify the behavior that you expect of them.

    And most importantly - what is the work flow of using such a framework (what is the step-by-step for creating a test).

    One very important thing that framework must provide is an ability to check that expected behavior has been observed during the test execution.

    jmock does it by introducing specific test runner that checks that all expectations on all declared mock objects after the test has finished. If something does not match, the exception is thrown.

    Usually the pattern is:

    1. Acquire mock factory ( called Mockery in jmock )out of thin air ( with specific no-args constructor ).
    2. Create required mock objects.
    3. Setup expectation on mock objects
    4. Call the method you are testing, passing mocks instead of real objects
    5. If your method returns some values, check expected value with regular assertXXX methods.

提交回复
热议问题