SlideShare a Scribd company logo
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

More Related Content

What's hot

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
Infinum
 
September 2010 - Arquillian
September 2010 - ArquillianSeptember 2010 - Arquillian
September 2010 - Arquillian
JBug 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-testkit
7mind
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection
7mind
 
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
7mind
 
Intro to front-end testing
Intro to front-end testingIntro to front-end testing
Intro to front-end testing
Juriy 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-Apps
chrisb206 chrisb206
 
Testing Web Apps with Spring Framework
Testing Web Apps with Spring FrameworkTesting Web Apps with Spring Framework
Testing Web Apps with Spring Framework
Dmytro Chyzhykov
 
Scala, Functional Programming and Team Productivity
Scala, Functional Programming and Team ProductivityScala, Functional Programming and Team Productivity
Scala, Functional Programming and Team Productivity
7mind
 
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
Stephen Fuqua
 
Testing Java Web Apps With Selenium
Testing Java Web Apps With SeleniumTesting Java Web Apps With Selenium
Testing Java Web Apps With Selenium
Marakana 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 Automation
Stephen 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 projects
Vincent Massol
 
JavaLand - Integration Testing How-to
JavaLand - Integration Testing How-toJavaLand - Integration Testing How-to
JavaLand - Integration Testing How-to
Nicolas Fränkel
 
Implementing quality in Java projects
Implementing quality in Java projectsImplementing quality in Java projects
Implementing quality in Java projects
Vincent 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 Integration
Nicolas Fränkel
 
First adoption hackathon at BGJUG
First adoption hackathon at BGJUGFirst adoption hackathon at BGJUG
First adoption hackathon at BGJUG
Ivan Ivanov
 
Testing in Ballerina Language
Testing in Ballerina LanguageTesting in Ballerina Language
Testing in Ballerina Language
Lynn Langit
 
Using Maven2
Using Maven2Using Maven2
Using Maven2
elliando dias
 
Building XWiki
Building XWikiBuilding XWiki
Building XWiki
Vincent Massol
 

What's hot (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
 

Viewers also liked

Testing the Java EE
Testing the Java EETesting the Java EE
Testing the Java EE
Dmitry Alexandrov
 
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
eduardo_mendonca
 
Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2Migrating from JSF1 to JSF2
Migrating from JSF1 to JSF2
tahirraza
 
3-oop java-inheritance
3-oop java-inheritance3-oop java-inheritance
3-oop java-inheritance
Amr Elghadban (AmrAngry)
 
Arquillian
ArquillianArquillian
Arquillian
Korhan Gülseven
 
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
Xiaoxing Hu
 
How to Use Selenium, Successfully
How to Use Selenium, SuccessfullyHow to Use Selenium, Successfully
How to Use Selenium, Successfully
Sauce Labs
 
Testing Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianTesting Java EE Applications Using Arquillian
Testing Java EE Applications Using Arquillian
Reza 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 2014
Oren 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 - Core
Dzmitry Naskou
 
Docker by Example - Basics
Docker by Example - Basics Docker by Example - Basics
Docker by Example - Basics
Ganesh Samarthyam
 
Docker introduction
Docker introductionDocker introduction
Docker introduction
dotCloud
 
QA Automation Solution
QA Automation SolutionQA Automation Solution
QA Automation Solution
DataArt
 

Viewers also liked (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
 

Similar to 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 Arquillian
Vineet Reynolds
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with Arquillian
Virtual JBoss User Group
 
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
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
Brockhaus Group
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
Brockhaus Consulting GmbH
 
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 practices
Narendra Pathai
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
Anung Ariwibowo
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
Sunil kumar Mohanty
 
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
Alexis Hassler
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
Anton Udovychenko
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
Sunghyouk Bae
 
3 j unit
3 j unit3 j unit
3 j unit
kishoregali
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
Jim 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 Arquillian
Alexis Hassler
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea 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 Purnama
Enterprise 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
 

Similar to 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, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, 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 ...
 
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...
 

Recently uploaded

Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
flufftailshop
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 

Recently uploaded (20)

Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 

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