SlideShare a Scribd company logo
In this tutorial, we will show you how to create two custom annotations – @Test and @TestInfo , to simulate a simple
unit test framework.
P.S This unit test example is inspired by this official Java annotation article.
1. @Test Annotation
This @interface tells Java this is a custom annotation. Later, you can annotate it on method level like
this @Test(enable=false) .
Test.java
packagepackage comcom..mkyongmkyong..testtest..corecore;;
importimport javajava..langlang..annotationannotation..ElementTypeElementType;;
importimport javajava..langlang..annotationannotation..RetentionRetention;;
importimport javajava..langlang..annotationannotation..RetentionPolicyRetentionPolicy;;
importimport javajava..langlang..annotationannotation..TargetTarget;;
@Retention@Retention((RetentionPolicyRetentionPolicy..RUNTIMERUNTIME))
@Target@Target((ElementTypeElementType..METHODMETHOD)) //can use in method only.//can use in method only.
publicpublic @@interfaceinterface TestTest {{
//should ignore this test?//should ignore this test?
publicpublic booleanboolean enabledenabled(()) defaultdefault truetrue;;
}}
Note
Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives,
String, Class, enums, annotations, and arrays of the preceding types.
2. @TesterInfo Annotation
This @TesterInfo is applied on class level, store the tester details. This shows the different use of return types – enum,
array and string.
TesterInfo.java
packagepackage comcom..mkyongmkyong..testtest..corecore;;
importimport javajava..langlang..annotationannotation..ElementTypeElementType;;
importimport javajava..langlang..annotationannotation..RetentionRetention;;
importimport javajava..langlang..annotationannotation..RetentionPolicyRetentionPolicy;;
importimport javajava..langlang..annotationannotation..TargetTarget;;
@Retention@Retention((RetentionPolicyRetentionPolicy..RUNTIMERUNTIME))
@Target@Target((ElementTypeElementType..TYPETYPE)) //on class level//on class level
publicpublic @@interfaceinterface TesterInfoTesterInfo {{
publicpublic enumenum PriorityPriority {{
LOWLOW,, MEDIUMMEDIUM,, HIGHHIGH
}}
PriorityPriority prioritypriority(()) defaultdefault PriorityPriority..MEDIUMMEDIUM;;
StringString[[]] tagstags(()) defaultdefault """";;
StringString createdBycreatedBy(()) defaultdefault "Mkyong""Mkyong";;
StringString lastModifiedlastModified(()) defaultdefault "03/01/2014""03/01/2014";;
}}
3. Unit Test Example
Create a simple unit test example, and annotated with the new custom annotations – @Test and @TesterInfo .
TestExample.java
packagepackage comcom..mkyongmkyong..testtest;;
importimport comcom..mkyongmkyong..testtest..corecore..TestTest;;
importimport comcom..mkyongmkyong..testtest..corecore..TesterInfoTesterInfo;;
importimport comcom..mkyongmkyong..testtest..corecore..TesterInfoTesterInfo..PriorityPriority;;
@TesterInfo@TesterInfo((
prioritypriority == PriorityPriority..HIGHHIGH,,
createdBycreatedBy == "mkyong.com""mkyong.com",,
tagstags == {{"sales""sales",,"test""test" }}
))
publicpublic classclass TestExampleTestExample {{
@Test@Test
voidvoid testAtestA(()) {{
ifif ((truetrue))
throwthrow newnew RuntimeExceptionRuntimeException(("This test always failed""This test always failed"));;
}}
@Test@Test((enabledenabled == falsefalse))
voidvoid testBtestB(()) {{
ifif ((falsefalse))
throwthrow newnew RuntimeExceptionRuntimeException(("This test always passed""This test always passed"));;
}}
@Test@Test((enabledenabled == truetrue))
voidvoid testCtestC(()) {{
ifif ((1010 >> 11)) {{
// do nothing, this test always passed.// do nothing, this test always passed.
}}
}}
}}
4. Java reflection – Read the Annotation
Below example show you how to use Java reflection APIs to read and process the custom annotations.
RunTest.java
packagepackage comcom..mkyongmkyong..testtest;;
p g y g ;
importimport javajava..langlang..annotationannotation..AnnotationAnnotation;;
importimport javajava..langlang..reflectreflect..MethodMethod;;
importimport comcom..mkyongmkyong..testtest..corecore..TestTest;;
importimport comcom..mkyongmkyong..testtest..corecore..TesterInfoTesterInfo;;
publicpublic classclass RunTestRunTest {{
publicpublic staticstatic voidvoid mainmain((StringString[[]] argsargs)) throwsthrows ExceptionException {{
SystemSystem..outout..printlnprintln(("Testing...""Testing..."));;
intint passedpassed == 00,, failedfailed == 00,, countcount == 00,, ignoreignore == 00;;
ClassClass<<TestExampleTestExample>> objobj == TestExampleTestExample..classclass;;
// Process @TesterInfo// Process @TesterInfo
ifif ((objobj..isAnnotationPresentisAnnotationPresent((TesterInfoTesterInfo..classclass)))) {{
Annotation annotationAnnotation annotation == objobj..getAnnotationgetAnnotation((TesterInfoTesterInfo..classclass));;
TesterInfo testerInfoTesterInfo testerInfo == ((TesterInfoTesterInfo)) annotationannotation;;
SystemSystem..outout..printfprintf(("%nPriority :%s""%nPriority :%s",, testerInfotesterInfo..prioritypriority(())));;
SystemSystem..outout..printfprintf(("%nCreatedBy :%s""%nCreatedBy :%s",, testerInfotesterInfo..createdBycreatedBy(())));;
SystemSystem..outout..printfprintf(("%nTags :""%nTags :"));;
intint tagLengthtagLength == testerInfotesterInfo..tagstags(())..lengthlength;;
forfor ((String tagString tag :: testerInfotesterInfo..tagstags(()))) {{
ifif ((tagLengthtagLength >> 11)) {{
SystemSystem..outout..printprint((tagtag ++ ", "", "));;
}} elseelse {{
SystemSystem..outout..printprint((tagtag));;
}}
tagLengthtagLength----;;
}}
SystemSystem..outout..printfprintf(("%nLastModified :%s%n%n""%nLastModified :%s%n%n",, testerInfotesterInfo..lastModifiedlastModified(())));;
}}
// Process @Test// Process @Test
forfor ((Method methodMethod method :: objobj..getDeclaredMethodsgetDeclaredMethods(()))) {{
// if method is annotated with @Test// if method is annotated with @Test
ifif ((methodmethod..isAnnotationPresentisAnnotationPresent((TestTest..classclass)))) {{
Annotation annotationAnnotation annotation == methodmethod..getAnnotationgetAnnotation((TestTest..classclass));;
Test testTest test == ((TestTest)) annotationannotation;;
// if enabled = true (default)// if enabled = true (default)
ifif ((testtest..enabledenabled(()))) {{
trytry {{
methodmethod..invokeinvoke((objobj..newInstancenewInstance(())));;
SystemSystem..outout..printfprintf(("%s - Test '%s' - passed %n""%s - Test '%s' - passed %n",, ++++countcount,, methodmethod..getNamegetName(())));;
passedpassed++++;;
}} catchcatch ((ThrowableThrowable exex)) {{
SystemSystem..outout..printfprintf(("%s - Test '%s' - failed: %s %n""%s - Test '%s' - failed: %s %n",, ++++countcount,, methodmethod..getNamegetName(()),, exex..getCausegetCause(())));;
failedfailed++++;;
}}
}} elseelse {{
SystemSystem..outout..printfprintf(("%s - Test '%s' - ignored%n""%s - Test '%s' - ignored%n",, ++++countcount,, methodmethod..getNamegetName(())));;
ignoreignore++++;;
}}
}}
}}
}}
SystemSystem..outout..printfprintf(("%nResult : Total : %d, Passed: %d, Failed %d, Ignore %d%n""%nResult : Total : %d, Passed: %d, Failed %d, Ignore %d%n",, countcount,, passedpassed,, failedfailed,, ignoreignore));;
}}
}}
Output
TestingTesting......
Priority :HIGHPriority :HIGH
CreatedBy :mkyong.comCreatedBy :mkyong.com
Tags :sales,Tags :sales, testtest
LastModified :03/01/2014LastModified :03/01/2014
1 - Test1 - Test 'testA''testA' - failed: java.lang.RuntimeException: This- failed: java.lang.RuntimeException: This testtest always failedalways failed
2 - Test2 - Test 'testC''testC' - passed- passed
3 - Test3 - Test 'testB''testB' - ignored- ignored
ResultResult :: TotalTotal :: 3, Passed: 1, Failed 1, Ignore 13, Passed: 1, Failed 1, Ignore 1

More Related Content

What's hot

3 j unit
3 j unit3 j unit
3 j unit
kishoregali
 
Test ng
Test ngTest ng
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
Büşra İçöz
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
Levon Apreyan
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
Andrey Oleynik
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
Srikrishna k
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
Ravikiran J
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
Abhishek Yadav
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
Denis Bazhin
 
xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
Chris Oldwood
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
Onkar Deshpande
 
Junit 4.0
Junit 4.0Junit 4.0
Junit
JunitJunit
Unit testing
Unit testingUnit testing
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
Valerio Maggio
 
Junit
JunitJunit
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
Nayanda Haberty
 

What's hot (20)

3 j unit
3 j unit3 j unit
3 j unit
 
Test ng
Test ngTest ng
Test ng
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
xUnit Style Database Testing
xUnit Style Database TestingxUnit Style Database Testing
xUnit Style Database Testing
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Junit
JunitJunit
Junit
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Junit
JunitJunit
Junit
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 

Similar to Java custom annotations example

Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
liminescence
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnit
Shouvik Chatterjee
 
Unit testing
Unit testingUnit testing
Unit testing
Pooya Sagharchiha
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
Sam Brannen
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
Quintagroup
 
Power mock
Power mockPower mock
Power mock
Piyush Mittal
 
UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
Timo Stollenwerk
 
JUnit 5
JUnit 5JUnit 5
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
solit
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
JUnit
JUnitJUnit
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
Hans Jones
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
jeresig
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
Jitendra Zaa
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
jeresig
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
Sunil kumar Mohanty
 

Similar to Java custom annotations example (20)

Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnit
 
Unit testing
Unit testingUnit testing
Unit testing
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Power mock
Power mockPower mock
Power mock
 
UPC Testing talk 2
UPC Testing talk 2UPC Testing talk 2
UPC Testing talk 2
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
JUnit
JUnitJUnit
JUnit
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 

Recently uploaded

Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
Reetu63
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
sandeepmenon62
 

Recently uploaded (20)

Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
ppt on the brain chip neuralink.pptx
ppt  on   the brain  chip neuralink.pptxppt  on   the brain  chip neuralink.pptx
ppt on the brain chip neuralink.pptx
 
What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptxOperational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
Operational ease MuleSoft and Salesforce Service Cloud Solution v1.0.pptx
 

Java custom annotations example

  • 1. In this tutorial, we will show you how to create two custom annotations – @Test and @TestInfo , to simulate a simple unit test framework. P.S This unit test example is inspired by this official Java annotation article. 1. @Test Annotation This @interface tells Java this is a custom annotation. Later, you can annotate it on method level like this @Test(enable=false) . Test.java packagepackage comcom..mkyongmkyong..testtest..corecore;; importimport javajava..langlang..annotationannotation..ElementTypeElementType;; importimport javajava..langlang..annotationannotation..RetentionRetention;; importimport javajava..langlang..annotationannotation..RetentionPolicyRetentionPolicy;; importimport javajava..langlang..annotationannotation..TargetTarget;; @Retention@Retention((RetentionPolicyRetentionPolicy..RUNTIMERUNTIME)) @Target@Target((ElementTypeElementType..METHODMETHOD)) //can use in method only.//can use in method only. publicpublic @@interfaceinterface TestTest {{ //should ignore this test?//should ignore this test? publicpublic booleanboolean enabledenabled(()) defaultdefault truetrue;; }} Note Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. 2. @TesterInfo Annotation This @TesterInfo is applied on class level, store the tester details. This shows the different use of return types – enum, array and string. TesterInfo.java packagepackage comcom..mkyongmkyong..testtest..corecore;; importimport javajava..langlang..annotationannotation..ElementTypeElementType;; importimport javajava..langlang..annotationannotation..RetentionRetention;; importimport javajava..langlang..annotationannotation..RetentionPolicyRetentionPolicy;; importimport javajava..langlang..annotationannotation..TargetTarget;; @Retention@Retention((RetentionPolicyRetentionPolicy..RUNTIMERUNTIME)) @Target@Target((ElementTypeElementType..TYPETYPE)) //on class level//on class level publicpublic @@interfaceinterface TesterInfoTesterInfo {{
  • 2. publicpublic enumenum PriorityPriority {{ LOWLOW,, MEDIUMMEDIUM,, HIGHHIGH }} PriorityPriority prioritypriority(()) defaultdefault PriorityPriority..MEDIUMMEDIUM;; StringString[[]] tagstags(()) defaultdefault """";; StringString createdBycreatedBy(()) defaultdefault "Mkyong""Mkyong";; StringString lastModifiedlastModified(()) defaultdefault "03/01/2014""03/01/2014";; }} 3. Unit Test Example Create a simple unit test example, and annotated with the new custom annotations – @Test and @TesterInfo . TestExample.java packagepackage comcom..mkyongmkyong..testtest;; importimport comcom..mkyongmkyong..testtest..corecore..TestTest;; importimport comcom..mkyongmkyong..testtest..corecore..TesterInfoTesterInfo;; importimport comcom..mkyongmkyong..testtest..corecore..TesterInfoTesterInfo..PriorityPriority;; @TesterInfo@TesterInfo(( prioritypriority == PriorityPriority..HIGHHIGH,, createdBycreatedBy == "mkyong.com""mkyong.com",, tagstags == {{"sales""sales",,"test""test" }} )) publicpublic classclass TestExampleTestExample {{ @Test@Test voidvoid testAtestA(()) {{ ifif ((truetrue)) throwthrow newnew RuntimeExceptionRuntimeException(("This test always failed""This test always failed"));; }} @Test@Test((enabledenabled == falsefalse)) voidvoid testBtestB(()) {{ ifif ((falsefalse)) throwthrow newnew RuntimeExceptionRuntimeException(("This test always passed""This test always passed"));; }} @Test@Test((enabledenabled == truetrue)) voidvoid testCtestC(()) {{ ifif ((1010 >> 11)) {{ // do nothing, this test always passed.// do nothing, this test always passed. }} }} }} 4. Java reflection – Read the Annotation Below example show you how to use Java reflection APIs to read and process the custom annotations. RunTest.java packagepackage comcom..mkyongmkyong..testtest;;
  • 3. p g y g ; importimport javajava..langlang..annotationannotation..AnnotationAnnotation;; importimport javajava..langlang..reflectreflect..MethodMethod;; importimport comcom..mkyongmkyong..testtest..corecore..TestTest;; importimport comcom..mkyongmkyong..testtest..corecore..TesterInfoTesterInfo;; publicpublic classclass RunTestRunTest {{ publicpublic staticstatic voidvoid mainmain((StringString[[]] argsargs)) throwsthrows ExceptionException {{ SystemSystem..outout..printlnprintln(("Testing...""Testing..."));; intint passedpassed == 00,, failedfailed == 00,, countcount == 00,, ignoreignore == 00;; ClassClass<<TestExampleTestExample>> objobj == TestExampleTestExample..classclass;; // Process @TesterInfo// Process @TesterInfo ifif ((objobj..isAnnotationPresentisAnnotationPresent((TesterInfoTesterInfo..classclass)))) {{ Annotation annotationAnnotation annotation == objobj..getAnnotationgetAnnotation((TesterInfoTesterInfo..classclass));; TesterInfo testerInfoTesterInfo testerInfo == ((TesterInfoTesterInfo)) annotationannotation;; SystemSystem..outout..printfprintf(("%nPriority :%s""%nPriority :%s",, testerInfotesterInfo..prioritypriority(())));; SystemSystem..outout..printfprintf(("%nCreatedBy :%s""%nCreatedBy :%s",, testerInfotesterInfo..createdBycreatedBy(())));; SystemSystem..outout..printfprintf(("%nTags :""%nTags :"));; intint tagLengthtagLength == testerInfotesterInfo..tagstags(())..lengthlength;; forfor ((String tagString tag :: testerInfotesterInfo..tagstags(()))) {{ ifif ((tagLengthtagLength >> 11)) {{ SystemSystem..outout..printprint((tagtag ++ ", "", "));; }} elseelse {{ SystemSystem..outout..printprint((tagtag));; }} tagLengthtagLength----;; }} SystemSystem..outout..printfprintf(("%nLastModified :%s%n%n""%nLastModified :%s%n%n",, testerInfotesterInfo..lastModifiedlastModified(())));; }} // Process @Test// Process @Test forfor ((Method methodMethod method :: objobj..getDeclaredMethodsgetDeclaredMethods(()))) {{ // if method is annotated with @Test// if method is annotated with @Test ifif ((methodmethod..isAnnotationPresentisAnnotationPresent((TestTest..classclass)))) {{ Annotation annotationAnnotation annotation == methodmethod..getAnnotationgetAnnotation((TestTest..classclass));; Test testTest test == ((TestTest)) annotationannotation;; // if enabled = true (default)// if enabled = true (default) ifif ((testtest..enabledenabled(()))) {{ trytry {{ methodmethod..invokeinvoke((objobj..newInstancenewInstance(())));; SystemSystem..outout..printfprintf(("%s - Test '%s' - passed %n""%s - Test '%s' - passed %n",, ++++countcount,, methodmethod..getNamegetName(())));; passedpassed++++;; }} catchcatch ((ThrowableThrowable exex)) {{ SystemSystem..outout..printfprintf(("%s - Test '%s' - failed: %s %n""%s - Test '%s' - failed: %s %n",, ++++countcount,, methodmethod..getNamegetName(()),, exex..getCausegetCause(())));; failedfailed++++;; }} }} elseelse {{ SystemSystem..outout..printfprintf(("%s - Test '%s' - ignored%n""%s - Test '%s' - ignored%n",, ++++countcount,, methodmethod..getNamegetName(())));; ignoreignore++++;; }}
  • 4. }} }} }} SystemSystem..outout..printfprintf(("%nResult : Total : %d, Passed: %d, Failed %d, Ignore %d%n""%nResult : Total : %d, Passed: %d, Failed %d, Ignore %d%n",, countcount,, passedpassed,, failedfailed,, ignoreignore));; }} }} Output TestingTesting...... Priority :HIGHPriority :HIGH CreatedBy :mkyong.comCreatedBy :mkyong.com Tags :sales,Tags :sales, testtest LastModified :03/01/2014LastModified :03/01/2014 1 - Test1 - Test 'testA''testA' - failed: java.lang.RuntimeException: This- failed: java.lang.RuntimeException: This testtest always failedalways failed 2 - Test2 - Test 'testC''testC' - passed- passed 3 - Test3 - Test 'testB''testB' - ignored- ignored ResultResult :: TotalTotal :: 3, Passed: 1, Failed 1, Ignore 13, Passed: 1, Failed 1, Ignore 1