那么BDD就够了吗?
答案当然是NO。BDD是很强大,你可以试一下,但是如果你真正的用于实践,你就会发现这些测试类和被测试类很快就会失去其联系。在BDD中,不仅仅测试方法不再是testXXX,那些测试类也可能不再是按约定取的名称。或者,你可能针对同一个被测试类/方法,会拥有多个测试的方法。例如之前的那个例子,当然不是很贴切,可能一个具体的测试类,比如来测试getHolder方法的行为的测试类更好一点。
你需要帮助吗?这是我的新的项目TestedBy
通过注释来标注被测试类和方法,来使其与测试类和方法联系在一起,怎么样?不是太坏,你说呢?
我的想法或多或少从这里开始,但是不仅限于一个注释。我很高兴这个主意,因此我决定开始一个新的开源项目来提供测试工具,用来把被测试类放到中心的位置。
继续看,我将展示给你如何通过注释和相关工具来改变你测试的方法。
TestedBy目标在于改变观察测试类和被测试类的角度。我们可以把被测试的类(项目中最重要的类)放在中心位置,并可从这些类连接到他们的测试类和方法。一个代码快照可能抵得上更多的解释:
Java代码
1. public class TestedBySample {
2.
3. /**
4. * @param args
5. */
6. public static void main( String[] args ) {
7. TestedBySample sample = new TestedBySample();
8. System.out.print(sample.add(1, 2));
9.
10. }
11.
12. @TestedBy( testClass = "it.javalinux.testedby.TestedBySampleTest", testMethod = "addShouldWork" )
13. public int add( int i,
14. int j ) {
15. return i + j;
16. }
17. @TestedByList( {@TestedBy( testClass = "it.javalinux.testedby.TestedBySampleTest", testMethod = "addShouldWork" ),
18. @TestedBy( testClass = "it.javalinux.testedby.TestedBySampleTest", testMethod = "addShouldWork2" )} )
19. public int add2( int i,
20. int j ) {
21. return i + j;
22. }
23.
24. }
2.
3. /**
4. * @param args
5. */
6. public static void main( String[] args ) {
7. TestedBySample sample = new TestedBySample();
8. System.out.print(sample.add(1, 2));
9.
10. }
11.
12. @TestedBy( testClass = "it.javalinux.testedby.TestedBySampleTest", testMethod = "addShouldWork" )
13. public int add( int i,
14. int j ) {
15. return i + j;
16. }
17. @TestedByList( {@TestedBy( testClass = "it.javalinux.testedby.TestedBySampleTest", testMethod = "addShouldWork" ),
18. @TestedBy( testClass = "it.javalinux.testedby.TestedBySampleTest", testMethod = "addShouldWork2" )} )
19. public int add2( int i,
20. int j ) {
21. return i + j;
22. }
23.
24. }
很好吧,但是它确实改变了你单元测试的方法?我觉得是,怎么样,至少在两个方面。