Writing code hard to test

How to write code that is hard to test?
– most people say: making things private, using private keyword, long methods (monolythic code)

Real issues

  1. mixing “new” operator with business logic prevents you from testing things in isolation (wrong: creating new objects directly in the business logic instead of using them)
  2. looking for things
  3. business logic in the constructor (in constructor you should ask for dependencies by constructor arguments and assign them to instance fields. Business logic should be in methods that use these dependecies but not construct them)
  4. having global state
  5. using static methods (which is essentialy procedural programming), it is easy to test leaf methods that do not call anybody else (Math.absolute(value)), but if a this static method has a bunch of collaborators then you cannot test this method in isolation, you cannot mock the db (cannot override static method). The worst thing is trying to test your application from the main method.
  6. deep inheritance hierarchy (if your class under test extends A, B, C classes you are also testing those classes if you want or not)
  7. too many conditionals (if statements – you need to prepare lots of test data to get throught the path you want)

Scope of tests

  1. Large number of unit tests – class level tested in insolation – very fast tests
  2. Many functional tests – collection of classess as subsystem – medium tests
  3. Some scenario tests – for the whole system – slow tests

The end to end tests are important but they take a lot of time and there are so many things that can go wrong so making sure every is set up correctly is hard and time consuming. It is hard to reproduce failures. Better test smaller portions of program and some happy path (all the things are wired up together correctly). Break the applicaion into subsystem and even invidual components and test the invidually.

For bad code it is hard to write good test.

In order to test classes with dependencies you should be able to have a choice to:

  1. mock dependencies or
  2. stub dependencies or
  3. instantiate a real class that has been alread well tested.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s