简体   繁体   English

单元测试类规范

[英]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. 我想以这样的方式测试类的规范:当从getter方法中删除注释时,测试应该失败并警告类的规范已经改变。

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. 因为这会使测试更加脆弱,但它会提供正确的反馈,以便从getter方法中删除注释。 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. 集成测试甚至涵盖了这种情况,但Integration提供的反馈不会指出问题。

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. 我将从我自己的后院给你举例 - 我们使用注释测试来验证实现某个接口的类的方法是否标有[Transaction]属性。 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. 更糟糕的是,当方法没有[Transaction]标记时,乍一看没有什么不好的事情发生。 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. 现在,@ @XMLElement对您的应用程序的正常运行有多重要以及它可能导致的严重错误是否缺失是您要判断的。 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. 至于我,如果我可以用自动化测试(甚至是昂贵且脆弱的)来替换任何非确定性的,难以跟踪/调试的错误 ,那么我任何时候都会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM