SlideShare a Scribd company logo
1 of 4
Download to read offline
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 (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

Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnitShouvik Chatterjee
 
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 SupportSam Brannen
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, PloneQuintagroup
 
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 PowerMockYing Zhang
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
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 TestsTomek Kaczanowski
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best PracticesJitendra 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.4jeresig
 

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

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

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