I am new to TDD and DDD and I have one simple question regarding static methods in general. Most of the gurus of TDD says in one word that static methods are bad (and that we should forget about creating tons of static utilities that we (um or I) used to make before as they are not testable. I can see why they are not testable ( a great clarification article can be found here for those who are interested but I guess I am the only noob here 🙁 ) but I was wondering is there a nice and clean guideline for using statics from TDD point of view?
This may be really silly question for most of you but some tips would be great and I just want to know how experts here think of static stuff. Thanks in advance.
Edit: While looking for answer I found 2 other nice threads regarding usage of static ( not TDD concern though) which I guess are good reads for those who are interested(myself inclusive).
I think you may have slightly misunderstood.
Static methods are testable. Take this method as an example:
You can test this by testing that the return value is what you expect based on the arguments passed in.
Where static methods become troublesome when testing is when you need to introduce a mock.
Let’s say I have some code that calls the
File.Delete()static method. To test my code without relying on the file system, I would want to replace/mock this call with a test version that just verifies that it has been called from the code being tested. This is easy to do if I had an instance of an object on whichDelete()was being called. Most (all?) mocking frameworks can not mock static methods, so using a static method in my code forces me to test it differently (usually by calling the real static method).To test something like this, I would introduce an interface:
My code would then take an instance of an object that implements this interface (either in the method call or as a parameter in the constructor), and then call its
Delete()method to do the delete:To test this, I can make a mock of the
IFileDeleterinterface and simply verify that itsDelete()method had been called. This removes the need to have a real file system as part of the test.This may look like the code is more complex (which it is), but it pays for itself in making it far easier to test.