SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
Make it test-driven with CDI!




Rafael Liu
the red




          2
Runtime environment




                      3
Test environment




                   4
Unit test




            5
What about...
●
    Access level modifiers limitations?
    ●
        Injection uses reflection
●
    “Unit” related stuff?
    ●
        Bean lifecycle (@PostConstruct, @PreDestroy)
    ●
        Interceptors / Decorators
    ●
        Events



                                                       6
Integration test




                   7
the green(s)




               8
1. CDI @Alternatives
●
    Typesafe bean resolution
●
    Abstraction + implementation
    ●
        “Real” implementation
    ●
        Mock implementation
●
    Runtime vs. test classpath
    ●
        beans.xml



                                      9
Extracting an interface




                          10
Creating a mock @Alternative




                               11
The classpath magic




                      12
2. Arquillian
●
    JBoss Testing initiative
●
    Test enrichment
●
    Inside-container testing
    ●
        JBoss AS 5 and 6
    ●
        GlassFish 3
    ●
        Tomcat 6
    ●
        Jetty 6 and 7

                                        13
A code is worth a thousand words
@RunWith(Arquillian.class)
public class TemperatureConverterTest {

      @Inject
      private TemperatureConverter converter;

      @Deployment
      public static JavaArchive createTestArchive() {
            return ShrinkWrap.create(JavaArchive.class, "test.jar")
                  .addClasses(TemperatureConverter.class)
                  .addAsManifestResource(
                        EmptyAsset.INSTANCE,  
                        ArchivePaths.create("beans.xml"));  
      }

      @Test
      public void testConvertToCelsius() {
            Assert.assertEquals(converter.convertToCelsius(32d), 0d);
            Assert.assertEquals(converter.convertToCelsius(212d), 100d);
      }
}

                                                                           14
The Arquillian way




                     15
Nice!
●
    We can check state
●
    More meaningful units, the CDI beans!
    ●
        A one unit integration test
●
    Mocks can replace beans easily
●
    Custom builds
    ●
        Descriptors and classes



                                            16
But...
●
    Still a class per mock
●
    Various @Deployments
●
    The single implementation dilema
●
    We can't use mock frameworks anymore!




                                            17
refactoring




              18
What we want?




                19
Write a portable extension!
●
    Choose certain injection points
●
    Resolve beans to custom mocks
●
    Define mocks at runtime
●
    Power of mock frameworks


●
    Thanks to our clever Expert Group!


                                         20
A “real” case
@Named
public class MyBean {

   @Inject
   private MyDependency myDependency;

   public String calculate(int a, int b) {
      return "multiplication is " + myDependency.multiply(a, b);
   }

}

@Named
public class MyDependency {

   public int multiply(int a, int b) {
      return a*b;
   }

}


                                                                   21
A code is worth.. you know
public class MyTest extends WeldMockTest {
   
    @Test
    public void testMock() {
       mockContext.addExpectations(new Expectations<MyDependency>() {
          @Override
          public void defineExpectations(MyDependency mock) {
            when(mock.multiply(2, 3)).thenReturn(5);
         }
      });
      
       MyBean bean = getBean(MyBean.class);

      String calculate = bean.calculate(2, 3);
      assertThat(calculate, is("multiplication is 5"));

      calculate = bean.calculate(2, 4);
      assertThat(calculate, is(not("multiplication is 8")));
   }

}


                                                                        22
And a spy
public class MyTest extends WeldMockTest {
      
   @Test
   public void testSpy() {
       mockContext.addExpectations(DoubleType.SPY,
             new Expectations<MyDependency>() {

          @Override
          public void defineExpectations(MyDependency mock) {
            when(mock.multiply(2, 3)).thenReturn(5);
         }
      });
      
       MyBean bean = getBean(MyBean.class);

      String calculate = bean.calculate(2, 3);
      assertThat(calculate, is("multiplication is 5"));

      calculate = bean.calculate(2, 4);
      assertThat(calculate, is("multiplication is 8"));
   }

}
                                                                23
What we get
●
    It's an extension
    ●
        Arquillian friendly
    ●
        Can easy the pain of @Deployments
●
    Mock frameworks and all their greatness!
●
    Choose precisely where to meddle
    ●
        Fine grained integration test
●
    Get a hold of your test code base!

                                               24
Fork me!




http://github.com/rafaelliu
                              25
Questions?

     @rafaelliu



     http://rafaelliu.net



                            26
References
 ●
     http://tinyurl.com/5mjgc8
 (http://code.google.com/p/mockito)

 ●
     http://tinyurl.com/cxshm2f
 (http://seamframework.org/Weld)

 ●
     http://tinyurl.com/c8qdtx8
 (http://monografias.cic.unb.br/dspace/bitstream/123456789/258/1/monografia.pdf)




                                                                                   27

Contenu connexe

Tendances

Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
knight1128
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
Andres Almiray
 

Tendances (20)

JSR-303 Bean Validation API
JSR-303 Bean Validation APIJSR-303 Bean Validation API
JSR-303 Bean Validation API
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
MUTANTS KILLER - PIT: state of the art of mutation testing system
MUTANTS KILLER - PIT: state of the art of mutation testing system MUTANTS KILLER - PIT: state of the art of mutation testing system
MUTANTS KILLER - PIT: state of the art of mutation testing system
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo ŽilićJavantura v2 - Making Java web-apps Groovy - Franjo Žilić
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
 
Mutation testing in Java
Mutation testing in JavaMutation testing in Java
Mutation testing in Java
 
Change Anything with Cucumber and ATDD
Change Anything with Cucumber and ATDDChange Anything with Cucumber and ATDD
Change Anything with Cucumber and ATDD
 
JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Reading
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
 
glideinWMS validation scirpts - glideinWMS Training Jan 2012
glideinWMS validation scirpts - glideinWMS Training Jan 2012glideinWMS validation scirpts - glideinWMS Training Jan 2012
glideinWMS validation scirpts - glideinWMS Training Jan 2012
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
How to unit test your React/Redux app
How to unit test your React/Redux appHow to unit test your React/Redux app
How to unit test your React/Redux app
 
PVS-Studio for Linux (CoreHard presentation)
PVS-Studio for Linux (CoreHard presentation)PVS-Studio for Linux (CoreHard presentation)
PVS-Studio for Linux (CoreHard presentation)
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010Gradle talk, Javarsovia 2010
Gradle talk, Javarsovia 2010
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
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
 

Similaire à Make it test-driven with CDI!

Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
 
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
inovex GmbH
 
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
 

Similaire à Make it test-driven with CDI! (20)

Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
Test-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptxTest-Driven Design Insights@DevoxxBE 2023.pptx
Test-Driven Design Insights@DevoxxBE 2023.pptx
 
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...
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning TalksBuilding Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
 
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
 
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?Hadoop:  Big Data Stacks validation w/ iTest  How to tame the elephant?
Hadoop: Big Data Stacks validation w/ iTest How to tame the elephant?
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
Bug bites Elephant? Test-driven Quality Assurance in Big Data Application Dev...
 
GR8Conf 2009: Industrial Strength Groovy by Paul King
GR8Conf 2009: Industrial Strength Groovy by Paul KingGR8Conf 2009: Industrial Strength Groovy by Paul King
GR8Conf 2009: Industrial Strength Groovy by Paul King
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a Code / Александр Тарасов (Одноклассники)
 
Everything as a code
Everything as a codeEverything as a code
Everything as a code
 
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
 

Dernier

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 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
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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
 
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
 

Make it test-driven with CDI!

  • 1. Make it test-driven with CDI! Rafael Liu
  • 6. What about... ● Access level modifiers limitations? ● Injection uses reflection ● “Unit” related stuff? ● Bean lifecycle (@PostConstruct, @PreDestroy) ● Interceptors / Decorators ● Events 6
  • 9. 1. CDI @Alternatives ● Typesafe bean resolution ● Abstraction + implementation ● “Real” implementation ● Mock implementation ● Runtime vs. test classpath ● beans.xml 9
  • 11. Creating a mock @Alternative 11
  • 13. 2. Arquillian ● JBoss Testing initiative ● Test enrichment ● Inside-container testing ● JBoss AS 5 and 6 ● GlassFish 3 ● Tomcat 6 ● Jetty 6 and 7 13
  • 14. A code is worth a thousand words @RunWith(Arquillian.class) public class TemperatureConverterTest {       @Inject       private TemperatureConverter converter;       @Deployment       public static JavaArchive createTestArchive() {             return ShrinkWrap.create(JavaArchive.class, "test.jar")                   .addClasses(TemperatureConverter.class)                   .addAsManifestResource(                         EmptyAsset.INSTANCE,                           ArchivePaths.create("beans.xml"));         }       @Test       public void testConvertToCelsius() {             Assert.assertEquals(converter.convertToCelsius(32d), 0d);             Assert.assertEquals(converter.convertToCelsius(212d), 100d);       } } 14
  • 16. Nice! ● We can check state ● More meaningful units, the CDI beans! ● A one unit integration test ● Mocks can replace beans easily ● Custom builds ● Descriptors and classes 16
  • 17. But... ● Still a class per mock ● Various @Deployments ● The single implementation dilema ● We can't use mock frameworks anymore! 17
  • 20. Write a portable extension! ● Choose certain injection points ● Resolve beans to custom mocks ● Define mocks at runtime ● Power of mock frameworks ● Thanks to our clever Expert Group! 20
  • 21. A “real” case @Named public class MyBean {    @Inject private MyDependency myDependency; public String calculate(int a, int b) { return "multiplication is " + myDependency.multiply(a, b);    } } @Named public class MyDependency { public int multiply(int a, int b) { return a*b;    } } 21
  • 22. A code is worth.. you know public class MyTest extends WeldMockTest {     @Test public void testMock() { mockContext.addExpectations(new Expectations<MyDependency>() { @Override public void defineExpectations(MyDependency mock) {             when(mock.multiply(2, 3)).thenReturn(5);          }       });        MyBean bean = getBean(MyBean.class);       String calculate = bean.calculate(2, 3); assertThat(calculate, is("multiplication is 5"));       calculate = bean.calculate(2, 4); assertThat(calculate, is(not("multiplication is 8")));    } } 22
  • 23. And a spy public class MyTest extends WeldMockTest {        @Test public void testSpy() { mockContext.addExpectations(DoubleType.SPY, new Expectations<MyDependency>() { @Override public void defineExpectations(MyDependency mock) {             when(mock.multiply(2, 3)).thenReturn(5);          }       });        MyBean bean = getBean(MyBean.class);       String calculate = bean.calculate(2, 3); assertThat(calculate, is("multiplication is 5"));       calculate = bean.calculate(2, 4); assertThat(calculate, is("multiplication is 8"));    } } 23
  • 24. What we get ● It's an extension ● Arquillian friendly ● Can easy the pain of @Deployments ● Mock frameworks and all their greatness! ● Choose precisely where to meddle ● Fine grained integration test ● Get a hold of your test code base! 24
  • 26. Questions? @rafaelliu http://rafaelliu.net 26
  • 27. References ● http://tinyurl.com/5mjgc8 (http://code.google.com/p/mockito) ● http://tinyurl.com/cxshm2f (http://seamframework.org/Weld) ● http://tinyurl.com/c8qdtx8 (http://monografias.cic.unb.br/dspace/bitstream/123456789/258/1/monografia.pdf) 27