How to start unit testing or TDD?

后端 未结 14 1837
离开以前
离开以前 2020-12-04 07:18

I read a lot of posts that convinced me I should start writing unit test, I also started to use dependency injection (Unity) for the sake of easier mocking, but I\'m still n

14条回答
  •  温柔的废话
    2020-12-04 07:23

    In C# and with visual studio I find following procedure very helpful:

    1. Think! Make a small upfront design. You need to have a clear picture what classes you need and how objects should relate with each other. Concentrate only on one class/object (the class/object you want to implement) and one relationship. Otherwise you end up with a too heavyweight design. I often end up with multiple sketches (only a few boxes and arrows) on a spare sheet of paper.

    2. Create the class in the production code and name it appropriately.

    3. Pick one behaviour of the class you want to implement and create a method stub for it. With visual studio creating empty method stubs is a piece of cake.

    4. Write a test for it. Therefor you will need to initialize that object, call the method and make an assert to verify the result. In the easiest case the assertion requires another method stub or a property in the production code.

    5. Compile and let the test runner show you the red bar!

    6. Code the required behavior in the production code to see the green bar appear.

    7. Move to the next behaviour.

    For this procedure two things are very important:

    • You need a clear picture what you want and how the class/object should look like. At least spend some time one it.
    • Think about behaviours of the class/object. This will make the tests and the production code behaviour-centric, which is a very natural approach to think about classes/objects.

    Test first or not test first?

    I find it usually harder to retrofitting tests to existing production code. In most cases this is due to tangled dependencies to other objects, when the object which is under test needs to be initialized. TDD usually avoids this, because you want to initialize the object in the test cases with less effort as possible. This will result to a very loose coupling.

    When I retrofit tests, the must cumbersome job is the task of initializing the object under test. Also the assertions may be a lot of work because of tangled dependencies. For this you will need to change the production code and break dependencies. By using dependency injection properly this should not be an issue.

提交回复
热议问题