TDD in Django, how to unit test my modelform?

前端 未结 1 1961
深忆病人
深忆病人 2021-01-06 18:45

I\'m new to TDD, and trying to apply TDD practice in a Django project.

Based on London school TDD workflow, I\'m working outside-in, view layer, form layer and model

相关标签:
1条回答
  • 2021-01-06 19:31

    When using frameworks like django it is tricky to write unit tests. The problem is that the model and the form are very tightly coupled by django design. By coupling here I mean for example that form expects specific fields to exist in model.

    Given that the model rarely has any logic itself and usually is just a definition of fields I would say that it is more practical to test the form together with the model and do not mock it. The tests for the logic you define in the form in most cases will depend only on the definition of the fields.

    But back to you your question.

    You can be a purist and mock the model. In order to test the form in isolation you would need to mock the model but a bit differently. Instead of using pure Mock you need to create another test model with a minimal definition of the model that this form can work with. This test model establishes kind of a contract between the form and the model. Namely what fields this form expects the model to have. And then in you test you should mock the model in the form with the test model.

    And you can do that using regular TDD practice of incremental steps. That is start from form with a test for one field and create (initially empty) test model and add fields one by one to it along creation tests for them in the form.

    Of cause you would still need an integration test (or tests) to check that your form works with the real model.

    And here's one important point. You are correct that you should not test the logic provided by django. But it does not mean that your test can't rely on it and use it.

    The same applies to your own code. The test for form should not test you model directly, but from practical perspective it can rely on the real model (given that model logic itself is tested as well in its own test). One would argue that this is not a pure unit test, but it is the price you pay for using the Web framework for perfectionists with deadlines.

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