JUnit 注解@Category的工作原理

Suppose you have a large number of unit test cases and you don’t want them to be executed all at the same time during Maven build. You can simply achieve it via annotation @Category.

(1) Create empty class FastTests and SlowTests. (2) In your test case class, categorize your test method using @Category annotation:



(3) Append the following code to your pom.xml:


        
            SlowTests
            
                com.sap.SlowTests
            
        
        
            FastTests
            
                com.sap.FastTests
            
        
    
    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.1
                
                    1.8
                    1.8
                
            
            
                org.apache.maven.plugins
                maven-surefire-plugin
                2.13
                
                    
                        org.apache.maven.surefire
                        surefire-junit47
                        2.13
                    
                
                
                    ${testcase.groups}
                
            
        
    

(4)In my project, by default all 7 test methods will be executed during Maven build:



Suppose you only want to execute unit test belonging to category “SlowTests”, use the following command line:



Since now I only marked one method with annotation SlowTests, only one test method is executed:



If you would like to execute all unit tests EXCEPT @SlowTests, simply add another profile in pom.xml:


            NonSlowTests
            
                
                    
                        org.apache.maven.plugins
                        maven-surefire-plugin
                        
                            com.sap.SlowTests
                        
                    
                
            
        

Before test, in order to prove that Slow method is NOT really executed, I add a system.out.println in each method:



Use command line: mvn test -P NonSlowTests From console output, I can ensure that the method with @Category(SlowTests.class) is NOT executed at all.



要获取更多Jerry的原创文章,请关注公众号"汪子熙":


请使用浏览器的分享功能分享到微信等