What is mocking?

  •                          What is mocking?

    Mocking is a process used in unit testing when the unit being tested has external dependencies. The purpose of mocking is to focus on the code being tested and not on the behavior or state of external dependencies. In mocking, the dependencies are replaced by closely controlled replacements objects that simulate the behavior of the real ones. There are three main types of replacement objects - stubs, fakes and mocks.

    Fakes: Fakes replace the actual code by implementing the same interface but without interacting with other objects. The problem Fakes introduce is they are hard coded to return fixed results and in order to test for different use cases a lot of Fakes must be introduced. Tests become hard to understand and maintain since the tests require a lot of Fakes as well as “else” statements to cover all possible statements.

    Stubs: Stubs are similar to Fakes because they return prerecorded answers to calls. However, the difference is that by using a mocking framework you can create the Stub in the test with a minimal amount of code. Thus, it becomes clear how the dependency will respond and how the tested system should behave.

    Mocks: Mocks have all the advantages of Stubs but also provide the option to specify behavior by setting an expectation on how many times a method must be executed. While Stubs are simple substitutes, Mocks are substitutes that can verify usage.

    For more information on the differences between stubs, fakes and mocks read the Fakes, Stubs and Mocks blog post.

    More practical examples on how to get started mocking can be found in the Doing Your First Mock blog post

  • What is a mocking framework?

    Mocking frameworks are used to generate replacement objects like Stubs and Mocks. Mocking frameworks complement unit testing frameworks by isolating dependencies but are not substitutes for unit testing frameworks. By isolating the dependencies, they help the unit testing process and aid developers in writing more focused and concise unit tests. The tests also perform faster by truly isolating the system under test.

  • What is a test runner?

    Where the unit testing framework adds facilities to create unit tests, the tests still need to be executed to verify the behavior of the system under test. Test Runners execute unit tests. Most of the unit testing frameworks include test runners and they vary from simple command line runners to graphical interfaces.

    Some tools, such as JustCode, a Visual Studio developer productivity tool are able to run many types of unit tests.

    Additional information on the difference between testing frameworks, mocking tools and test runners can be found in the Why Mocking Matters blog post.

原文地址:https://www.cnblogs.com/chucklu/p/9118453.html