What should a “unit” be when unit testing?

前端 未结 10 1025
梦毁少年i
梦毁少年i 2020-12-28 15:16

On Proggit today I was reading the comment thread on a submission entitled, \"Why Unit Testing Is A Waste of Time\".

I\'m not really concerned with premise of the ar

10条回答
  •  清酒与你
    2020-12-28 15:59

    A "unit" should be a single atomic unit for your definition. That is, precisely what defines a "unit" for unit testing is rather subjective; it can depend rather strongly on precisely what your architecture is, and how your application chooses to break down functional units. What I'm saying is that there is no clearly defined "unit", except for what you define. A "unit" can be a single method which has a single side effect, or it can be a related set of methods which together define a single, coherent set of functionality.

    Rationality is rather important here; it's entirely possible to write unit tests for each accessor of each class that you have; however, that's clearly overkill. Similarly, it's possible but silly to define your entire application as a unit, and expect to have a single test to test it.

    Generally, you want a "unit" for testing to describe one clearly defined, clearly distinct chunk of functionality. At each level of viewing your application, you should be able to see clear "atoms" of functionality (if your design is good); these can be as simple as "retrieve a record from the database" for a low-level view, and as complicated as "create, edit, and delete a user" at a high-level view. They're not mutually exclusive, either; you can easily have both as unit tests.

    The point to be taken here is that the unit you want to test is the unit that makes sense. You want unit testing to validate and verify functionality; so what a unit test tests is what you define as functionality. What is a unit of functionality? That's up to your individual situation to define.

提交回复
热议问题