Dependency Injection With Test Driven Development


With unit tests you can check that your code behaviours just as you expect it to. When writing your unit tests you shouldn't need to worry about if any other area of the application is working correctly.

The benefits of unit testing are:

  • Decouples your code
  • Write more modular classes
  • Functions are smaller and more focused
  • Your functions are more defensive
  • Quality of code becomes higher
  • You will find it easier to reuse code.

When writing unit tests you just need to test this one method of your application, if your method relies on another class/variable there should be a way you can inject this into the method. This is where dependency injection in your code comes in handy, it will allow you to inject objects into your classes to change the output of the class.

There are a few things you need to do to make a method unit testable, methods will need an input from a parameter or a class variable and it will need a return or set a class variable in the method. If the method hasn't got these things then the method can not be unit testable. If there isn't a return of the method then there is no way in knowing how the method performs.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email