SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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用
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 

Kürzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.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
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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.