Is it OK to copy & paste unit-tests when the logic is basically the same?

前端 未结 9 2047
悲&欢浪女
悲&欢浪女 2021-02-02 12:09

I currently have like 10 tests that test whenever my Tetris piece doesn\'t move left if there is a piece in the path, or a wall. Now, I will have to test the same behaviour for

相关标签:
9条回答
  • 2021-02-02 12:34

    I agreed @Rob. The code needs refactoring. But if you don't want to do refactor the code at this point of time then you can go and have parametrized tests. The same test run for different parameters. See TestCase and TestCaseSource attributes in nunit.

    Refer http://nunit.org/index.php?p=parameterizedTests&r=2.5

    0 讨论(0)
  • 2021-02-02 12:35

    The xunitpatterns.org web site says "no" (copy / paste is not ok) because it can increase costs when tests need to be updated:

    • Test Code Duplication

    "Cut and Paste" is a powerful tool for writing code fast but it results in many copies of the same code each of which must be maintained in parallel.

    and for further reading it also links to the article

    • Refactoring Test Code

    By: Arie van Deursen, Leon Moonen, Alex van den Bergh, Gerard Kok

    0 讨论(0)
  • 2021-02-02 12:38

    Try taking the 3rd approach that you haven't mentioned, that of refactoring your code so that you can share one implementation of the test between all 10 tests.

    The jist is, duplicating code is almost always the wrong thing to do. In this example you could refactor the checking code into a method called, for example IsTetrisPieceUnableToMoveLeftBecauseOfAPieceOrAWall. I always go for very descriptive method names like that when writing a bit of "shared" functionality for a unit test as it makes it extraordinarily clear just what's being done / tested.

    0 讨论(0)
提交回复
热议问题