Lecture 'Test-Driven-Development and Dependency Injection' at HS-ZIGR

| tagged as

I had the chance to give a lecture for students of the masters degree for computer science at the University of Applied Sciences Zittau / Görlitz. The title of the course of lectures was "Webdevelopment in practice" and my part was a lecture on the topic "Test driven Development and Dependency Injection".

At first I talked about the advantages of automatic tests in professional software development. I described the different types of tests like unit tests and integration tests. One of the main points was that "real" unit tests only test the component itself and not the surrounding environment. To achive this you need to replace all dependencies of a class with mock objects to be able to simulate an environment for your tests.

Based on this insight I described the design pattern dependency injection as this pattern is the best way to be able to replace dependencies of a component. In the lecture I didn't use a framework for dependency injection but explained how you can implement dependency injection by hand. I showed the different styles of dependency injection like "constructor injection", "field injection" and "setter injection" and explained why in my opinion constructor injection is the most advantageous choice.

After the basics I showed the test driven way of developing software. Writing your test before the implementation is leading to better testable code and in most cases to lesser coupling between components. I personally think that one of the biggest points of doing TDD is that it helps me to focus on the requirements of the software and not the implementation. I think about how a class should be used by a developer. This leads to a better API for every class.

The last part of the lecture was a chapter about testing anti-patterns. I explained that using static methods in java is only aceptable when they are stateless and there are no side-effects. Otherwise you can't be sure about the state of your application when executing the test. The same is true for the Singleton design pattern.

Another testing anitpattern in my opinion is using final for classes or methods as in this cases it is harder to use mocking in the tests.


In addition to the lecture there was an computer exercise afterwards. The students had to try out TDD in practice. The exercise was taken from the german book "Das Java-Praktikum" (dpunkt.verlag, 2008, from Reinhard Schiedermeier and Klaus Köhler). This is a book with small exercises to learn and practise java programming. In the book it's not done with TDD but in my opinion the exercises are great for this purpose.

The task was to write a class that encapsulates a specific point in time and gives the user and easy way to handle and visualize this instance of time.

The code of the test and the implementation can be found on github: https://github.com/lestard/tdd-example-clocktime.