Narendra Pathai
Narendra Pathai

Reputation: 41975

Unit testing class specification

I wanted to test the specification of the class in a way that when an annotation is removed from the getter method the tests should fail and warn that specification of class has changed.

class SomeBean{

   @XMLElement(name = "name")
   public String getName(){
     return name;
   }
}

class SomeBeanUnitTest{
   @Test
   public void test_getNameMustHaveAnnotation(){
      Method getNameMethod = SomeBean.class.getDeclaredMethod("getName", new Class<?>[]{});
      assertNotNull(getNameMethod.getAnnotation(XmlElement.class));
   }
}

Do testing methods for declared annotations is a proper way to check the specification of class? As this will make the tests more brittle, but it will provide proper feedback that the annotation was removed from the getter method. Is it advisable to write such tests?

This condition is even covered in Integration test, but the feedback provided by Integration will not point out the problem.

Upvotes: 4

Views: 621

Answers (1)

k.m
k.m

Reputation: 31464

It depends.

It depends on how important/crucial to your application working that annotation is. This of course may sound very general as one might assume that every piece of code is important for application to function properly.

I'll give you example from my own backyard - we use annotation testing to verify whether methods of classes implementing certain interface are marked with [Transaction] attribute. Why is this important? Beacuse it's very easy to:

  • forget to mark method
  • remove attribute accidentally
  • become a victim of unfortunate merging accident

What is worse, when the method isn't marked with [Transaction], at first glance nothing bad happens. Application runs and functions properly. But as you might have probably guessed, such method doesn't run in transaction - which once in a while might cause critical error which is extremly hard to track. Cost of writing such test / benefit is very low.

Now, how important is @XMLElement for proper workings of your application and how critical errors it may cause was it missing is for you to judge. When in doubt, weight the cost vs benefit. As for me, if I could replace any non deterministic, hard to track/debug error with automated test (even costly and brittle one), I'd do that anyday.

Upvotes: 3

Related Questions