Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any tips on writing testing-friendly code?

Are there any guidelines for writing test-friendly Python code?

What I believe:

  • One method does one thing.
  • Don't use side-effects.

Any other suggestions?

like image 817
xiaowl Avatar asked Jan 17 '11 06:01

xiaowl


People also ask

Should you write tests before code?

It often makes sense to write the test first and then write as much code as needed to allow the test to pass. Doing this moves towards a practice known as Test-Driven Development (TDD). Bluefruit uses a lot of TDD because it helps us to build the right product without waste and redundancies.

How can I be good at unit testing?

Good unit tests are well structured Arrange: Setup the prerequisites for your test. Create objects, prepare inputs and configure mocked interfaces. Act: Perform the actual work of the test, typically by calling a function. Assert: Verify that the unit under test did what you expected.


2 Answers

TDD

The best tip I can give you to write test friendly code is to write the tests first. Then write the production code (TDD). Uncle Bob devised three simple rules to write TDD:

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

Especially this quote should sink in:

If you think about this you will realize that you simply cannot write very much code at all without compiling and executing something. Indeed, this is really the point.

Writing Testable Code

Also read "Writing Testable Code" from google's testing expert(are for java, but also apply to python for large parts). You should also download/read the complete PDF on that page. But a quick recap:

  1. Constructor does Real Work
  2. Digging into Collaborators
  3. Brittle Global State & Singletons
  4. Class Does Too Much
like image 139
Alfred Avatar answered Oct 13 '22 21:10

Alfred


Write methods that don't rely on other models or resources - if they need to access them, they should be passed in to the method.

like image 26
sevenseacat Avatar answered Oct 13 '22 20:10

sevenseacat