I have been taught to follow the Red->Greeen->Refactor pattern when doing TDD. There have been situations where this pattern have not been applicable though.
For instance, a test to make sure that a controller action method (ASP.NET MVC) does not have an Authorize attribute. Since the test is testing the absense of an attribute it will pass on the first go, unless an Authorize attribute is added only to have the test fail.
What I have done so far when testing for absense of said Authorize attribute is to write a test for it, then add the Authorize attribute just to make sure that the test actually works, then immediately remove the Authorize attribute.
Am I doing something wrong, or is this just the way it is; some tests will pass unless we intentionally add code to make the fail and then remove that particular code?
1
So the situation is this: your method does not have an Authorize attribute. Why do you need to test this? There are an infinite number of negative assertions like this which could be made about any given entity, all of which are initially true. If you have a genuine need to test this, it’s because it’s a genuine problem somewhere – somewhere something is getting objects with a method with an Authorize attribute, and it shouldn’t. That’s the point at which to introduce the test. Not out of the blue. And that’s the point – where you say, “this thing can’t work if it’s handed an object with a method with an Authorize attribute.” where you figure out what should happen if it is handed such an object. Write that test. Don’t write a test about your controller, which itself is really neutral about the presence or absence of the attribute. Write the test around the entity which genuinely cares about the attribute. Then make it pass.
4