SlideShare uma empresa Scribd logo
1 de 55
Baixar para ler offline
Arquillian : An introduction
      Testing with real objects
          Vineet Reynolds
            March 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
Let’s recap
@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.
}
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
ATDD/BDD with Arquillian

THE DRONE AND JBEHAVE
EXTENSIONS
Arquillian : An introduction
Arquillian : An introduction
Arquillian : An introduction
Arquillian : An introduction

Mais conteúdo relacionado

Mais procurados

Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustInfinum
 
September 2010 - Arquillian
September 2010 - ArquillianSeptember 2010 - Arquillian
September 2010 - ArquillianJBug Italy
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit7mind
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection7mind
 
Izumi 1.0: Your Next Scala Stack
Izumi 1.0: Your Next Scala StackIzumi 1.0: Your Next Scala Stack
Izumi 1.0: Your Next Scala Stack7mind
 
Intro to front-end testing
Intro to front-end testingIntro to front-end testing
Intro to front-end testingJuriy Zaytsev
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Appschrisb206 chrisb206
 
Testing Web Apps with Spring Framework
Testing Web Apps with Spring FrameworkTesting Web Apps with Spring Framework
Testing Web Apps with Spring FrameworkDmytro Chyzhykov
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity7mind
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven developmentStephen Fuqua
 
Testing Java Web Apps With Selenium
Testing Java Web Apps With SeleniumTesting Java Web Apps With Selenium
Testing Java Web Apps With SeleniumMarakana Inc.
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projectsVincent Massol
 
JavaLand - Integration Testing How-to
JavaLand - Integration Testing How-toJavaLand - Integration Testing How-to
JavaLand - Integration Testing How-toNicolas Fränkel
 
Implementing quality in Java projects
Implementing quality in Java projectsImplementing quality in Java projects
Implementing quality in Java projectsVincent Massol
 
Riga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous IntegrationRiga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous IntegrationNicolas Fränkel
 
First adoption hackathon at BGJUG
First adoption hackathon at BGJUGFirst adoption hackathon at BGJUG
First adoption hackathon at BGJUGIvan Ivanov
 
Testing in Ballerina Language
Testing in Ballerina LanguageTesting in Ballerina Language
Testing in Ballerina LanguageLynn Langit
 

Mais procurados (20)

Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan KustAndroid Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
 
September 2010 - Arquillian
September 2010 - ArquillianSeptember 2010 - Arquillian
September 2010 - Arquillian
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection
 
Izumi 1.0: Your Next Scala Stack
Izumi 1.0: Your Next Scala StackIzumi 1.0: Your Next Scala Stack
Izumi 1.0: Your Next Scala Stack
 
Intro to front-end testing
Intro to front-end testingIntro to front-end testing
Intro to front-end testing
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
 
Testing Web Apps with Spring Framework
Testing Web Apps with Spring FrameworkTesting Web Apps with Spring Framework
Testing Web Apps with Spring Framework
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Testing Java Web Apps With Selenium
Testing Java Web Apps With SeleniumTesting Java Web Apps With Selenium
Testing Java Web Apps With Selenium
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projects
 
JavaLand - Integration Testing How-to
JavaLand - Integration Testing How-toJavaLand - Integration Testing How-to
JavaLand - Integration Testing How-to
 
Implementing quality in Java projects
Implementing quality in Java projectsImplementing quality in Java projects
Implementing quality in Java projects
 
Riga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous IntegrationRiga Dev Day - Automated Android Continuous Integration
Riga Dev Day - Automated Android Continuous Integration
 
First adoption hackathon at BGJUG
First adoption hackathon at BGJUGFirst adoption hackathon at BGJUG
First adoption hackathon at BGJUG
 
Testing in Ballerina Language
Testing in Ballerina LanguageTesting in Ballerina Language
Testing in Ballerina Language
 
Using Maven2
Using Maven2Using Maven2
Using Maven2
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
 

Destaque

Rich Web Interfaces with JSF2 - An Introduction
Rich Web Interfaces with JSF2 - An IntroductionRich Web Interfaces with JSF2 - An Introduction
Rich Web Interfaces with JSF2 - An Introductioneduardo_mendonca
 
Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2tahirraza
 
Making Your Results Visible - A Test Result Dashboard and Comparison Tool
Making Your Results Visible - A Test Result Dashboard and Comparison ToolMaking Your Results Visible - A Test Result Dashboard and Comparison Tool
Making Your Results Visible - A Test Result Dashboard and Comparison ToolXiaoxing Hu
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, SuccessfullySauce Labs
 
Testing Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianTesting Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianReza Rahman
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Oren Rubin
 
Reactive Java EE - Let Me Count the Ways!
Reactive Java EE - Let Me Count the Ways!Reactive Java EE - Let Me Count the Ways!
Reactive Java EE - Let Me Count the Ways!Reza Rahman
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Docker introduction
Docker introductionDocker introduction
Docker introductiondotCloud
 
QA Automation Solution
QA Automation SolutionQA Automation Solution
QA Automation SolutionDataArt
 

Destaque (14)

Testing the Java EE
Testing the Java EETesting the Java EE
Testing the Java EE
 
Rich Web Interfaces with JSF2 - An Introduction
Rich Web Interfaces with JSF2 - An IntroductionRich Web Interfaces with JSF2 - An Introduction
Rich Web Interfaces with JSF2 - An Introduction
 
Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2
 
3-oop java-inheritance
3-oop java-inheritance3-oop java-inheritance
3-oop java-inheritance
 
Arquillian
ArquillianArquillian
Arquillian
 
Making Your Results Visible - A Test Result Dashboard and Comparison Tool
Making Your Results Visible - A Test Result Dashboard and Comparison ToolMaking Your Results Visible - A Test Result Dashboard and Comparison Tool
Making Your Results Visible - A Test Result Dashboard and Comparison Tool
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, Successfully
 
Testing Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianTesting Java EE Applications Using Arquillian
Testing Java EE Applications Using Arquillian
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014
 
Reactive Java EE - Let Me Count the Ways!
Reactive Java EE - Let Me Count the Ways!Reactive Java EE - Let Me Count the Ways!
Reactive Java EE - Let Me Count the Ways!
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Docker by Example - Basics
Docker by Example - Basics Docker by Example - Basics
Docker by Example - Basics
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
 
QA Automation Solution
QA Automation SolutionQA Automation Solution
QA Automation Solution
 

Semelhante a Arquillian : An introduction

A fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with ArquillianA fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with ArquillianVineet Reynolds
 
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
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim 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
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
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
 
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Dan Allen
 

Semelhante a Arquillian : An introduction (20)

A fresh look at Java Enterprise Application testing with Arquillian
A fresh look at Java Enterprise Application testing with ArquillianA fresh look at Java Enterprise Application testing with Arquillian
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 ...
 
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
 
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
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
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
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
3 j unit
3 j unit3 j unit
3 j unit
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
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
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
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
 
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
 

Último

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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
 
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
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
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
 
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
 
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
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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...
 
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
 
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...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
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...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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)
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
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
 

Arquillian : An introduction

  • 1. Arquillian : An introduction Testing with real objects Vineet Reynolds March 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. Let’s recap @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. }
  • 31. Using Arquillian to test the repository TESTING THE REPOSITORY - DEMO
  • 32. The stuff that Arquillian does under the hood WHAT DID YOU JUST SEE?
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. Arquillian changes the way you see tests WHY SHOULD YOU USE IT?
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50. Refining the tests involving a database THE PERSISTENCE EXTENSION
  • 51. ATDD/BDD with Arquillian THE DRONE AND JBEHAVE EXTENSIONS