Mock Objects vs Test Database

后端 未结 6 1909
庸人自扰
庸人自扰 2021-02-19 20:42

What\'s the advantage of using mock objects in comparison to a static test database that has known data and using transactions to make sure nothing changes when testing against

6条回答
  •  你的背包
    2021-02-19 21:08

    Imagine you're about to write a class which doesn't exist. Maybe it's a controller. It's not something which talks straight to the database.

    You have a good idea of how it ought to behave, and you know what it should be responsible for, and what it should delegate to some other service (using Single Responsibility Principle). So you write interfaces to represent the roles of the helper classes it's going to use.

    Then you write an example of how you might use your class that you're about to create. If you like, you can call the example a unit test. You mock out the interactions with the helper classes. When you run the example, it fails, because you haven't written the code yet. You can now write the code to make it pass, using the interfaces of the helper classes - which you also haven't written yet.

    Then you do the same with the helper classes, mocking out their helpers.

    Eventually you'll reach a class which talks to the database. Or maybe it talks to a web service. Or perhaps the data is static, or in memory. (It doesn't matter to the original class, because your class is decoupled from this).

    At this point you'll want an example to describe the behaviour of this class, too, and if it's a database connector, you'll need a database for the example.

    Writing code this way produces code that's easy to use and understand, with nothing extra that isn't needed by something further up the stack. This is usually more robust than code that's easier to write. That's why we sometimes use mocks - because writing tests first using mocks helps produce good, maintainable, decoupled design.

提交回复
热议问题