My Testing Experience

Before my days of automated testing…

I wrote only solid code!

Untested code? Git push production master

There’s no time for tests!

Unit test? Get out of my way

So what brought me to automated testing?

My code isn’t solid!

Server Down Impossible

Everyday, I’m struggling!

The working dead

Automated Testing Benefits

If you like it, why you no unit test?

One does not simply write unit tests

Writing Proper Tests

Make Them With Simple Goals

Maze

Why?


Problem?

Make Them Deterministic

You no fail locally but fail on build server?

Why?


Problem?

Make Them Test The Right Thing

Do the right thing

What not to do


What to do

Unit test all the code!

How to Start?

Simple Example: Fibonacci in C++


Code:

int fib(int n) {
  if (n <= 0) { return 0; }
  else if (n == 1) { return 1; }
  else { return fib(n-2) + fib(n-1); }
}
void main() {
  cout << fib(5) << endl;
}

Test:

void testFib() {
  // given
  int n = 6;
  // when
  int x = fib(n);
  // then
  assert(x, 8);
}

Hard to Test Example


public class EntityController {

  IRepo repo = new EntityRepo(...);

  public Entity find(int id) {
    Date d = Date.now();
    if (d.getTime() % 60000 >= 30000) {
      return repo.getEntity(id, d);
    } else {
      return null;
    }
  }

}

Less Hard to Test Example


public class EntityController {

  private IRepo repo;

  // we can perform dependency injection
  public IRepo setRepo(IRepo r) {
    repo = r;
  }

  // we can maintain backwards compatibility
  public Entity find(int id) {
    return find(id, Date.now());
  }

  // ... and still test deterministically
  public Entity find(int id, Date d) {
    if (d.getTime() % 60000 >= 30000) {
      return repo.getEntity(id, d);
    } else {
      return null;
    }
  }
}

How I Feel About Tests Now

Conclusion?

Im not saying you have to test, but you have to test

Questions?

(Ask now)






These slides have been open-sourced and are available @ https://github.com/pcting/slides_testxp