SlideShare a Scribd company logo
1 of 53
Download to read offline
A fresh look at Java Enterprise
Application testing with Arquillian
          Vineet Reynolds
             May 2012
How does this solve our problems?

WHY ARQUILLIAN?
Test Doubles
redux
How did we arrive at the current
testing landscape?
Let’s test a repository
@Stateless @Local(UserRepository.class)
public class UserJPARepository implements UserRepository {

    @PersistenceContext                                      Injected by the container.
    private EntityManager em;                                How do we get one in our
                                                                       tests?

    public User create(User user) {
          em.persist(user);
                                                               How do we test this?
          return user;
    }
      ...
}
Did you say Mocks?
public class MockUserRepositoryTests {
    …
    @Before public void injectDependencies() {
        // Mock
        em = mock(EntityManager.class);
        userRepository = new UserJPARepository(em);
    }

    @Test public void testCreateUser() throws Exception {
        // Setup
        User user = createTestUser();

        // Execute
        User createdUser = userRepository.create(user);

        // Verify
        verify(em, times(1)).persist(user);
        assertThat(createdUser, equalTo(user));
        …
Seems perfect, but…
verify(em, times(1)).persist(user);


• Is brittle
• Violates DRY
• Is not a good use of a Mock
Implementations matter

TESTING WITH REAL OBJECTS
Using a real EntityManager
public class RealUserRepositoryTests {

   static EntityManagerFactory emf;
   EntityManager em;
   UserRepository userRepository;

   @BeforeClass public static void beforeClass() {
       emf = Persistence.createEntityManagerFactory("jpa-examples");
   }

   @Before public void setup() throws Exception {
       // Initialize a real EntityManager
       em = emf.createEntityManager();
       userRepository = new UserJPARepository(em);
       em.getTransaction().begin();
   }
   …
Testing with a real EntityManager
@Test
public void testCreateUser() throws Exception {
    // Setup
    User user = createTestUser();

    // Execute
    User createdUser = userRepository.create(user);
    em.flush();
    em.clear();

    // Verify
    User foundUser = em.find(User.class, createdUser.getUserId());
    assertThat(foundUser, equalTo(createdUser));
}
Better, but …
• Requires a separate persistence.xml
• Manual transaction management
• Flushes and clears the persistence context
  manually
Bringing the test as close as possible to production

ARQUILLIAN ENTERS THE SCENE
We must walk before we run
@RunWith(Arquillian.class)           // #1                                Use the Arquillian test
public class GreeterTest {                                                       runner.
    @Deployment                       // #2
    public static JavaArchive createDeployment() {                          Assemble a micro-
        return ShrinkWrap.create(JavaArchive.class)                            deployment
            .addClass(Greeter.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    }
                                                                               A CDI Bean.
    @Inject                          // #3                              Managed by the container.
    Greeter greeter;
                                                                         Injected by Arquillian.
    @Test                             // #4
    public void should_create_greeting() {
        assertEquals("Hello, Earthling!",                               Test like you normally do.
            greeter.greet("Earthling"));                                         No mocks.
    }                                                                       Just the real thing.
}
@RunWith(Arquillian.class)


   JUnit           TestNG
   >= 4.8.1         > 5.12.1
@Deployment
• Assemble test archives with ShrinkWrap
• Bundles the -
  – Class/component to test
  – Supporting classes
  – Configuration and resource files
  – Dependent libraries
Revisiting the deployment
      @Deployment                                                   // #1
      public static JavaArchive createDeployment() {
          return ShrinkWrap.create(JavaArchive.class)               // #2
              .addClass(Greeter.class)                              // #3
              .addAsManifestResource(EmptyAsset.INSTANCE,
     "beans.xml");                                                  // #4
      }

1.   Annotate the method with @Deployment
2.   Create a new JavaArchive. This will eventually create a JAR.
3.   Add our Class-Under-Test to the archive.
4.   Add an empty file named beans.xml to enable CDI.
Test enrichment
• Arquillian can enrich test class instances with
  dependencies.
• Supports:
   –   @EJB
   –   @Inject
   –   @Resource
   –   @PersistenceContext
   –   @PersistenceUnit
   –   @ArquillianResource
   –   …
Revisiting dependency injection
@Inject
Greeter greeter;



• The CDI BeanManager is used to create a
  new bean instance.
• Arquillian injects the bean into the test
  class instance, before running any tests.
Writing your tests
• Write assertions as you normally would
  – No record-replay-verify model
  – Assert as you typically do
  – Use real objects in your assertions
Running your tests
• Run the tests from your IDE or from your
  CI server
  – Just like you would run unit tests
     • Run as JUnit test - Alt+Shift+X, T
     • Run as Maven goal - Alt+Shift+X, M
Using Arquillian to test the repository

TESTING THE REPOSITORY - DEMO
The stuff that Arquillian does under the hood

WHAT DID YOU JUST SEE?
Arquillian changes the way you see tests

WHY SHOULD YOU USE IT?
Refining the tests involving a database

THE PERSISTENCE EXTENSION
Source Code
https://github.com/VineetReynolds/Arquillian-JavaOne-India-2012
A fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with Arquillian

More Related Content

What's hot

iOS Behavior-Driven Development
iOS Behavior-Driven DevelopmentiOS Behavior-Driven Development
iOS Behavior-Driven DevelopmentBrian Gesiak
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
EclipseMAT
EclipseMATEclipseMAT
EclipseMATAli Bahu
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample applicationAntoine Rey
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest modulePyCon Italia
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Andres Almiray
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Andres Almiray
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using dockerPavel Rabetski
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification QuestionsSpringMockExams
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 

What's hot (20)

iOS Behavior-Driven Development
iOS Behavior-Driven DevelopmentiOS Behavior-Driven Development
iOS Behavior-Driven Development
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Spock
SpockSpock
Spock
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
EclipseMAT
EclipseMATEclipseMAT
EclipseMAT
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017Making the most of your gradle build - Gr8Conf 2017
Making the most of your gradle build - Gr8Conf 2017
 
Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017Making the most of your gradle build - Greach 2017
Making the most of your gradle build - Greach 2017
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 
Reproducible component tests using docker
Reproducible component tests using dockerReproducible component tests using docker
Reproducible component tests using docker
 
Unit testing
Unit testingUnit testing
Unit testing
 
Java Quiz - Meetup
Java Quiz - MeetupJava Quiz - Meetup
Java Quiz - Meetup
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 

Viewers also liked

Music magazine questionnaire
Music magazine questionnaireMusic magazine questionnaire
Music magazine questionnairecvfo7
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire resultscvfo7
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire resultscvfo7
 
Potential Cover Photos
Potential Cover PhotosPotential Cover Photos
Potential Cover Photoscvfo7
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire resultscvfo7
 
Magazine analysis 111
Magazine analysis 111Magazine analysis 111
Magazine analysis 111cvfo7
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire resultscvfo7
 
Potential cover photos
Potential cover photosPotential cover photos
Potential cover photoscvfo7
 
Magazine analysis
Magazine analysisMagazine analysis
Magazine analysiscvfo7
 
Photo analysis 2
Photo analysis 2Photo analysis 2
Photo analysis 2cvfo7
 
Photo analysis 2
Photo analysis 2Photo analysis 2
Photo analysis 2cvfo7
 
151115 県p研究大会発表up用
151115 県p研究大会発表up用151115 県p研究大会発表up用
151115 県p研究大会発表up用Shinichiro Kawakami
 

Viewers also liked (13)

Music magazine questionnaire
Music magazine questionnaireMusic magazine questionnaire
Music magazine questionnaire
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire results
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire results
 
Potential Cover Photos
Potential Cover PhotosPotential Cover Photos
Potential Cover Photos
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire results
 
Magazine analysis 111
Magazine analysis 111Magazine analysis 111
Magazine analysis 111
 
Questionnaire results
Questionnaire resultsQuestionnaire results
Questionnaire results
 
Potential cover photos
Potential cover photosPotential cover photos
Potential cover photos
 
Magazine analysis
Magazine analysisMagazine analysis
Magazine analysis
 
Photo analysis 2
Photo analysis 2Photo analysis 2
Photo analysis 2
 
Photo analysis 2
Photo analysis 2Photo analysis 2
Photo analysis 2
 
Intra axial posterior fossa tumor
Intra axial posterior fossa tumorIntra axial posterior fossa tumor
Intra axial posterior fossa tumor
 
151115 県p研究大会発表up用
151115 県p研究大会発表up用151115 県p研究大会発表up用
151115 県p研究大会発表up用
 

Similar to A fresh look at Java Enterprise Application testing with Arquillian

Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...JAXLondon2014
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianVirtual JBoss User Group
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshellBrockhaus Group
 
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...Peter Pilgrim
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesNarendra Pathai
 
MarsJUG - Une nouvelle vision des tests avec Arquillian
MarsJUG - Une nouvelle vision des tests avec ArquillianMarsJUG - Une nouvelle vision des tests avec Arquillian
MarsJUG - Une nouvelle vision des tests avec ArquillianAlexis Hassler
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
First adoption hackathon at BGJUG
First adoption hackathon at BGJUGFirst adoption hackathon at BGJUG
First adoption hackathon at BGJUGIvan Ivanov
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightOpenDaylight
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnitvaruntaliyan
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
JUG Summer Camp - Une nouvelle vision des tests avec Arquillian
JUG Summer Camp - Une nouvelle vision des tests avec ArquillianJUG Summer Camp - Une nouvelle vision des tests avec Arquillian
JUG Summer Camp - Une nouvelle vision des tests avec ArquillianAlexis Hassler
 

Similar to A fresh look at Java Enterprise Application testing with Arquillian (20)

Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with Arquillian
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
 
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
Devoxx UK 2013 Test-Driven Development with JavaEE 7, Arquillian and Embedded...
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
 
MarsJUG - Une nouvelle vision des tests avec Arquillian
MarsJUG - Une nouvelle vision des tests avec ArquillianMarsJUG - Une nouvelle vision des tests avec Arquillian
MarsJUG - Une nouvelle vision des tests avec Arquillian
 
Arquillian
ArquillianArquillian
Arquillian
 
3 j unit
3 j unit3 j unit
3 j unit
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
First adoption hackathon at BGJUG
First adoption hackathon at BGJUGFirst adoption hackathon at BGJUG
First adoption hackathon at BGJUG
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
JUG Summer Camp - Une nouvelle vision des tests avec Arquillian
JUG Summer Camp - Une nouvelle vision des tests avec ArquillianJUG Summer Camp - Une nouvelle vision des tests avec Arquillian
JUG Summer Camp - Une nouvelle vision des tests avec Arquillian
 

Recently uploaded

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

A fresh look at Java Enterprise Application testing with Arquillian

  • 1. A fresh look at Java Enterprise Application testing with Arquillian Vineet Reynolds May 2012
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. How does this solve our problems? WHY ARQUILLIAN?
  • 13. Test Doubles redux How did we arrive at the current testing landscape?
  • 14. Let’s test a repository @Stateless @Local(UserRepository.class) public class UserJPARepository implements UserRepository { @PersistenceContext Injected by the container. private EntityManager em; How do we get one in our tests? public User create(User user) { em.persist(user); How do we test this? return user; } ... }
  • 15. Did you say Mocks? public class MockUserRepositoryTests { … @Before public void injectDependencies() { // Mock em = mock(EntityManager.class); userRepository = new UserJPARepository(em); } @Test public void testCreateUser() throws Exception { // Setup User user = createTestUser(); // Execute User createdUser = userRepository.create(user); // Verify verify(em, times(1)).persist(user); assertThat(createdUser, equalTo(user)); …
  • 16. Seems perfect, but… verify(em, times(1)).persist(user); • Is brittle • Violates DRY • Is not a good use of a Mock
  • 18. Using a real EntityManager public class RealUserRepositoryTests { static EntityManagerFactory emf; EntityManager em; UserRepository userRepository; @BeforeClass public static void beforeClass() { emf = Persistence.createEntityManagerFactory("jpa-examples"); } @Before public void setup() throws Exception { // Initialize a real EntityManager em = emf.createEntityManager(); userRepository = new UserJPARepository(em); em.getTransaction().begin(); } …
  • 19. Testing with a real EntityManager @Test public void testCreateUser() throws Exception { // Setup User user = createTestUser(); // Execute User createdUser = userRepository.create(user); em.flush(); em.clear(); // Verify User foundUser = em.find(User.class, createdUser.getUserId()); assertThat(foundUser, equalTo(createdUser)); }
  • 20. Better, but … • Requires a separate persistence.xml • Manual transaction management • Flushes and clears the persistence context manually
  • 21. Bringing the test as close as possible to production ARQUILLIAN ENTERS THE SCENE
  • 22. We must walk before we run @RunWith(Arquillian.class) // #1 Use the Arquillian test public class GreeterTest { runner. @Deployment // #2 public static JavaArchive createDeployment() { Assemble a micro- return ShrinkWrap.create(JavaArchive.class) deployment .addClass(Greeter.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); } A CDI Bean. @Inject // #3 Managed by the container. Greeter greeter; Injected by Arquillian. @Test // #4 public void should_create_greeting() { assertEquals("Hello, Earthling!", Test like you normally do. greeter.greet("Earthling")); No mocks. } Just the real thing. }
  • 23. @RunWith(Arquillian.class) JUnit TestNG >= 4.8.1 > 5.12.1
  • 24. @Deployment • Assemble test archives with ShrinkWrap • Bundles the - – Class/component to test – Supporting classes – Configuration and resource files – Dependent libraries
  • 25. Revisiting the deployment @Deployment // #1 public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class) // #2 .addClass(Greeter.class) // #3 .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); // #4 } 1. Annotate the method with @Deployment 2. Create a new JavaArchive. This will eventually create a JAR. 3. Add our Class-Under-Test to the archive. 4. Add an empty file named beans.xml to enable CDI.
  • 26. Test enrichment • Arquillian can enrich test class instances with dependencies. • Supports: – @EJB – @Inject – @Resource – @PersistenceContext – @PersistenceUnit – @ArquillianResource – …
  • 27. Revisiting dependency injection @Inject Greeter greeter; • The CDI BeanManager is used to create a new bean instance. • Arquillian injects the bean into the test class instance, before running any tests.
  • 28. Writing your tests • Write assertions as you normally would – No record-replay-verify model – Assert as you typically do – Use real objects in your assertions
  • 29. Running your tests • Run the tests from your IDE or from your CI server – Just like you would run unit tests • Run as JUnit test - Alt+Shift+X, T • Run as Maven goal - Alt+Shift+X, M
  • 30. Using Arquillian to test the repository TESTING THE REPOSITORY - DEMO
  • 31. The stuff that Arquillian does under the hood WHAT DID YOU JUST SEE?
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39. Arquillian changes the way you see tests WHY SHOULD YOU USE IT?
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48. Refining the tests involving a database THE PERSISTENCE EXTENSION
  • 49.
  • 50.