SlideShare une entreprise Scribd logo
1  sur  37
Unit Test Candidate Solutions

       Xuefeng.Wu 2012.05
Types of Tests
Types of Tests

        use mock environment : isolation
        single responsibility

        use simulation 3rd applications,
        system ,drivers


        use real 3rd applications, system ,
        drivers
Test context

CSDM

CSDM Demo,
   CSDM
                CSDM Service
 Controller

                Soap services
                                Domain Manager
Applications-
                                Business logic
  2D etc,                                        Model DAO   Files
                    Jetty         managers
  Drivers
Test Targets
Technology Problems
•   Environment and Context for developer
•   Test database prepare for developer
•   Test sample files prepare for developer
•   XML String parameter in service for soap services test
•   XML verify for soap services test
•   Mock Object for domain logic test
•   Model Date verify for domain logic test
•   Files verify for domain logic test
•   Notification verify for domain logic test
•   Unit testing styles for better test code
Test database prepare
• DB Unit/ unitils
• Derby backup, restore on line
• Derby date file recovery with RAM Disk
Test database prepare
• Baseline data
• Each Test data is individual and isolation
DB Unit
    • DbUnit has the ability to export and import
      your database data to and from XML datasets.
public DBUnitSampleTest(String name) { super( name );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "org.apache.derby.jdbc.ClientDriver" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:derby://localhost:1527/pas;create=true" );
}

protected IDataSet getDataSet() throws Exception {

    return new FlatXmlDataSetBuilder().build(new FileInputStream("D:/Test/pas.xml"));
}

protected DatabaseOperation getSetUpOperation() throws Exception {
    return DatabaseOperation.REFRESH;
}

protected DatabaseOperation getTearDownOperation() throws Exception {
    return DatabaseOperation.NONE;
}




       Perform setup of stale data once for entire test class or test suite
Derby backup, restore on line


String dbURL = "jdbc:derby:salesdb;restoreFrom=D:/dbbackups/salesdb";
Connection conn = DriverManager.getConnection(dbURL);
Derby date file recovery
 • Hey! We use derby!
 • Use Embedded Derbey
 • Restore data files which in RAM Disk

<property name="hibernate.connection.url">
jdbc:derby:database/pas;create=true
</property>

<property name="hibernate.connection.driver_class">
org.apache.derby.jdbc.EmbeddedDriver
</property>
Test sample files prepare
• Dicom files,images,3D files
• Custom file providers
XML String parameter in service
• Soap service is all about xml string in and out
• But it's not easy to provide XML format
  string in Java.
Java StringBuffer

String buildXML() {
StringBuffer sb = new StringBuffer();
 sb.append("<EXPRESSION>");
 sb.append(" <EQUAL>");
 sb.append(" <IDENT>x</IDENT>");
 sb.append(" <PLUS>");
 sb.append(" <INT>3</INT>");
 sb.append(" <TIMES>");
 sb.append(" <INT>4</INT>");
 sb.append(" <INT>5</INT>");
 sb.append(" </TIMES>");
 sb.append(" </PLUS>");
 sb.append(" </EQUAL>");
 sb.append("</EXPRESSION>");
 return sb.toString();
} // buildXML
Read xml file as input



      readFileToString.java
Use Other Language raw string

val input = """
<trophy type="request" version="1.0">
 <patient>
  <parameter key="patient_id" value="" /> C (If patient_id and DPMS_id are both null, PAS shall set Patient=patient_internal_id and
  <parameter key="dpms_id" value=""/> C (If both parameter are not null, use input value. Only above two conditions, others will be
  <parameter key="first_name" value=""/> O
  <parameter key="last_name" value=""/> O
  <parameter key="middle_name" value=""/> O
  <parameter key="prefix" value=""/> O
  <parameter key="suffix" value=""/> O
  <parameter key="birth_date" value=""/> O ("yyyy-MM-dd")
  <parameter key="sex" value=""/> O (male,female,other)
  <parameter key="pregnancy" value=""/> O (not pregnant,possibly pregnant,definitively pregnant,unknown) empty string means not app
  <parameter key="insurance_number" value=""/> O <parameter key="address" value=""/> O
  <parameter key="town" value=""/> O
  <parameter key="postal_code" value=""/> O
  <parameter key="cellular_phone" value=""/> O
  <parameter key="home_phone" value=""/> O
  <parameter key="work_phone" value=""/> O
  <parameter key="comments" value=""/> O
  <parameter key="email" value=""/> O
  <parameter key="photo" value=""/> O
  <parameter key="kdis6_patient_directory" value=""/> O (used for import kdis6 images)
  <parameter key="images_imported" value=""/> C ("true/false", must be pair with kdis6_patient_directory)
  </patient>
</trophy>
"""
XML verify
• The soap service output is xml string
• You can use contains to verify simple value
• But not easy to verify specific value
XmlUnit
• XML can be used for just about anything so
  deciding if two documents are equal to each
  other isn't as easy as a character for character
  match
public void testXPathValues() throws Exception {
 String myJavaFlavours = "<java-flavours><jvm current='some platforms'>1.1.x</jvm>" +
 "<jvm current='no'>1.2.x</jvm><jvm current='yes'>1.3.x</jvm>" +
 "<jvm current='yes' latest='yes'>1.4.x</jvm></java-flavours>";

 assertXpathEvaluatesTo("1.4.x", "//jvm[@latest='yes']", myJavaFlavours);
 assertXpathEvaluatesTo("2", "count(//jvm[@current='yes'])", myJavaFlavours);
 assertXpathValuesEqual("//jvm[4]/@latest", "//jvm[4]/@current", myJavaFlavours);
 assertXpathValuesNotEqual("//jvm[2]/@current", "//jvm[3]/@current", myJavaFlavours);
}
Scala XML

val ns = <foo><bar><baz/>Text</bar><bin/></foo>

ns  "foo" // => <foo><bar>...</bar><bin/></foo>

ns  "foo"  "bar" // => <bar><baz/>Text</bar>


val ns = <foo id="bar"/>

ns  "@id" // => Text(bar)
JRuby REXML


xml = File.read('posts.xml')
puts Benchmark.measure {
   doc, posts = REXML::Document.new(xml), []
   doc.elements.each('posts/post') do |p|
   posts << p.attributes
End
}
Model Date verify
• After execute the method you want to know
  every thing is correct.
Solutions
• DbUnit can also help you to verify that your
  database data match an expected set of
  values.
• Call hibernate Dao Directly
• Verify by other business method
Files verify
• Custom utile

• public static void checkDuplicateFiles(File dir)
Notification verify
• An ActiveMQ client utile
• It should run in other thread and subscript
  before call method
• It should time out if no message received after
  long time
Wait future notification

"There should have imageCreated notification after image is created " should {

    " ok " in {

       val srcPid = DataPrepare.createPatient
       val msg = future(ActiveMQ.receive("topic.imageCreated"))
       val imgId = DataPrepare.prepareImage(srcPid)._1 //wait a 3 second
       awaitAll(3000,msg) foreach{ v => v match {
         case Some(m) => { m.toString must contain (srcPid)
                          m.toString must contain (imgId) }
         case None => 1 must_== 2 }
       }
      }
}
Mock Object
EasyMock
public void testTransferShouldDebitSourceAccount(){

    AccountController controller = new AccountController();

    Account from = createMock(Account.class)

    Account to = createMock(Account.class)

    from.debit(42);

    replay(from);

    replay(to);

    controller.transfer(from,to,42);

    verify(from);

}
jMock
Mockery context = new Mockery();
public void testTransferShouldDebitSourceAccount(){

    AccountController controller = new AccountController();

    Account from = context.mock(Account.class)

    Account to = context.mock(Account.class)

    context.checking(new Expectations() {{

         oneOf(from).debit(42);

    }}

    controller.transfer(from,to,42);

    context.assertIsSatisfied();

}
mockito


public void testTransferShouldDebitSourceAccount(){

    AccountController controller = new AccountController();

    Account from = mock(Account.class)

    Account to = mock(Account.class)

    controller.transfer(from,to,42);

    verify(from).debit(42);

}
public void testTransferShouldDebitSourceAccount(){

                                     AccountController controller = new AccountController();

                                     Account from = createMock(Account.class)

                                     Account to = createMock(Account.class)

                                     from.debit(42);

                                     replay(from);

                                     replay(to);

                                     controller.transfer(from,to,42);

                                     verify(from);
                            }


Mockery context = new Mockery();
public void testTransferShouldDebitSourceAccount(){

      AccountController controller = new AccountController();

      Account from = context.mock(Account.class)

      Account to = context.mock(Account.class)

      context.checking(new Expectations() {{
              oneOf(from).debit(42);
      }}

      controller.transfer(from,to,42);

      context.assertIsSatisfied();
}


          public void testTransferShouldDebitSourceAccount(){

                 AccountController controller = new AccountController();

                 Account from = mock(Account.class)

                 Account to = mock(Account.class)

                 controller.transfer(from,to,42);

                 verify(from).debit(42);

          }
Mock what?
Environment and Context
Name                  Location   Interaction

DB                    Internal   JDBC connect with hibernate

ActiveMQ              Internal   socket,ActiveMQ library

Demo                  External   cmd,socket

Config file           External   read/write file

Registration table    External   system tool,reg

Schedule              External   trigger

2D                    External   cmd,socket

Object Applications   External   cmd
Unit testing styles
• BDD
• Better test code
• It’s better not only for developer. If P.O. can
  read our test code is better
• The test code should like specifics
Traditional Status assert test

 public void testAdd() {

     int num1 = 3;

     int num2 = 2;

     int total = 5;

     int sum = 0;

     sum = Math.add(num1, num2);

     assertEquals(sum, total);
 }
BDD specifications style
class HelloWorldSpec extends Specification {

    "The 'Hello world' string" should {

        "contain 11 characters" in {
            "Hello world" must have size(11)
        }

        "start with 'Hello'" in {
            "Hello world" must startWith("Hello")
        }

        "end with 'world'" in {
            "Hello world" must endWith("world")
        }
    }

    "The sum" should {
         “ equals total " in {
             val num1 = 2,num2 = 3, total = 5
            Math.add(num1, num2) must equalsTo(total)
        }
    }

}
Unit test candidate solutions
Unit test candidate solutions

Contenu connexe

Tendances

Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testingPeter Edwards
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBOren Eini
 
Data in Motion: Streaming Static Data Efficiently 2
Data in Motion: Streaming Static Data Efficiently 2Data in Motion: Streaming Static Data Efficiently 2
Data in Motion: Streaming Static Data Efficiently 2Martin Zapletal
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09Daniel Bryant
 
How to implement g rpc services in nodejs
How to implement g rpc services in nodejsHow to implement g rpc services in nodejs
How to implement g rpc services in nodejsKaty Slemon
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterReact table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterKaty Slemon
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
SQL Server SQL Server
SQL Server SQL ServerSQL Server SQL Server
SQL Server SQL Serverwebhostingguy
 
SAP Testing Training
SAP Testing TrainingSAP Testing Training
SAP Testing TrainingVGlobal Govi
 
No more promises lets RxJS 2 Edit
No more promises lets RxJS 2 EditNo more promises lets RxJS 2 Edit
No more promises lets RxJS 2 EditIlia Idakiev
 
Sustaining Test-Driven Development
Sustaining Test-Driven DevelopmentSustaining Test-Driven Development
Sustaining Test-Driven DevelopmentAgileOnTheBeach
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8Michael Miles
 
Example First / A Sane Test-Driven Approach to Programming
Example First / A Sane Test-Driven Approach to ProgrammingExample First / A Sane Test-Driven Approach to Programming
Example First / A Sane Test-Driven Approach to ProgrammingJonathan Acker
 
Fighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsetsFighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsetsddeogun
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 

Tendances (20)

Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testing
 
Implementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDBImplementing CQRS and Event Sourcing with RavenDB
Implementing CQRS and Event Sourcing with RavenDB
 
Data in Motion: Streaming Static Data Efficiently 2
Data in Motion: Streaming Static Data Efficiently 2Data in Motion: Streaming Static Data Efficiently 2
Data in Motion: Streaming Static Data Efficiently 2
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
How to implement g rpc services in nodejs
How to implement g rpc services in nodejsHow to implement g rpc services in nodejs
How to implement g rpc services in nodejs
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Oleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoCOleksandr Valetskyy - DI vs. IoC
Oleksandr Valetskyy - DI vs. IoC
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilterReact table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilter
 
11-DWR-and-JQuery
11-DWR-and-JQuery11-DWR-and-JQuery
11-DWR-and-JQuery
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
SQL Server SQL Server
SQL Server SQL ServerSQL Server SQL Server
SQL Server SQL Server
 
SAP Testing Training
SAP Testing TrainingSAP Testing Training
SAP Testing Training
 
No more promises lets RxJS 2 Edit
No more promises lets RxJS 2 EditNo more promises lets RxJS 2 Edit
No more promises lets RxJS 2 Edit
 
Sustaining Test-Driven Development
Sustaining Test-Driven DevelopmentSustaining Test-Driven Development
Sustaining Test-Driven Development
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
MidCamp 2016 - Demystifying AJAX Callback Commands in Drupal 8
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
Example First / A Sane Test-Driven Approach to Programming
Example First / A Sane Test-Driven Approach to ProgrammingExample First / A Sane Test-Driven Approach to Programming
Example First / A Sane Test-Driven Approach to Programming
 
Fighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsetsFighting security trolls_with_high-quality_mindsets
Fighting security trolls_with_high-quality_mindsets
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 

En vedette

En vedette (10)

Bis Chapter5
Bis Chapter5Bis Chapter5
Bis Chapter5
 
Faq
FaqFaq
Faq
 
Andrew Atroshenko Painter
Andrew Atroshenko PainterAndrew Atroshenko Painter
Andrew Atroshenko Painter
 
Intellectual Property Rights
Intellectual Property RightsIntellectual Property Rights
Intellectual Property Rights
 
Bis Chapter2
Bis Chapter2Bis Chapter2
Bis Chapter2
 
Telecommunication and networks
Telecommunication and networksTelecommunication and networks
Telecommunication and networks
 
Journalism in Pakistan - Training Needs Assessment
Journalism in Pakistan - Training Needs AssessmentJournalism in Pakistan - Training Needs Assessment
Journalism in Pakistan - Training Needs Assessment
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
polymorphism
polymorphism polymorphism
polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similaire à Unit test candidate solutions

Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09Michelangelo van Dam
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every dayVadym Khondar
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance testBryan Liu
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach placesdn
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGvraopolisetti
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Frédéric Delorme
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.pptSwapnil Kale
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Modernising Legacy Code
Modernising Legacy CodeModernising Legacy Code
Modernising Legacy CodeSamThePHPDev
 
SpringOne 2GX 2013 - Spring Testing
SpringOne 2GX 2013 - Spring TestingSpringOne 2GX 2013 - Spring Testing
SpringOne 2GX 2013 - Spring TestingMattias Severson
 

Similaire à Unit test candidate solutions (20)

Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
 
Testing in those hard to reach places
Testing in those hard to reach placesTesting in those hard to reach places
Testing in those hard to reach places
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
TDD, BDD and mocks
TDD, BDD and mocksTDD, BDD and mocks
TDD, BDD and mocks
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8Bdd for-dso-1227123516572504-8
Bdd for-dso-1227123516572504-8
 
Jdbc
JdbcJdbc
Jdbc
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Modernising Legacy Code
Modernising Legacy CodeModernising Legacy Code
Modernising Legacy Code
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
SpringOne 2GX 2013 - Spring Testing
SpringOne 2GX 2013 - Spring TestingSpringOne 2GX 2013 - Spring Testing
SpringOne 2GX 2013 - Spring Testing
 

Dernier

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Dernier (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Unit test candidate solutions

  • 1. Unit Test Candidate Solutions Xuefeng.Wu 2012.05
  • 3. Types of Tests use mock environment : isolation single responsibility use simulation 3rd applications, system ,drivers use real 3rd applications, system , drivers
  • 4. Test context CSDM CSDM Demo, CSDM CSDM Service Controller Soap services Domain Manager Applications- Business logic 2D etc, Model DAO Files Jetty managers Drivers
  • 6. Technology Problems • Environment and Context for developer • Test database prepare for developer • Test sample files prepare for developer • XML String parameter in service for soap services test • XML verify for soap services test • Mock Object for domain logic test • Model Date verify for domain logic test • Files verify for domain logic test • Notification verify for domain logic test • Unit testing styles for better test code
  • 7. Test database prepare • DB Unit/ unitils • Derby backup, restore on line • Derby date file recovery with RAM Disk
  • 8. Test database prepare • Baseline data • Each Test data is individual and isolation
  • 9. DB Unit • DbUnit has the ability to export and import your database data to and from XML datasets. public DBUnitSampleTest(String name) { super( name ); System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "org.apache.derby.jdbc.ClientDriver" ); System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:derby://localhost:1527/pas;create=true" ); } protected IDataSet getDataSet() throws Exception { return new FlatXmlDataSetBuilder().build(new FileInputStream("D:/Test/pas.xml")); } protected DatabaseOperation getSetUpOperation() throws Exception { return DatabaseOperation.REFRESH; } protected DatabaseOperation getTearDownOperation() throws Exception { return DatabaseOperation.NONE; } Perform setup of stale data once for entire test class or test suite
  • 10. Derby backup, restore on line String dbURL = "jdbc:derby:salesdb;restoreFrom=D:/dbbackups/salesdb"; Connection conn = DriverManager.getConnection(dbURL);
  • 11. Derby date file recovery • Hey! We use derby! • Use Embedded Derbey • Restore data files which in RAM Disk <property name="hibernate.connection.url"> jdbc:derby:database/pas;create=true </property> <property name="hibernate.connection.driver_class"> org.apache.derby.jdbc.EmbeddedDriver </property>
  • 12. Test sample files prepare • Dicom files,images,3D files • Custom file providers
  • 13. XML String parameter in service • Soap service is all about xml string in and out • But it's not easy to provide XML format string in Java.
  • 14. Java StringBuffer String buildXML() { StringBuffer sb = new StringBuffer(); sb.append("<EXPRESSION>"); sb.append(" <EQUAL>"); sb.append(" <IDENT>x</IDENT>"); sb.append(" <PLUS>"); sb.append(" <INT>3</INT>"); sb.append(" <TIMES>"); sb.append(" <INT>4</INT>"); sb.append(" <INT>5</INT>"); sb.append(" </TIMES>"); sb.append(" </PLUS>"); sb.append(" </EQUAL>"); sb.append("</EXPRESSION>"); return sb.toString(); } // buildXML
  • 15. Read xml file as input readFileToString.java
  • 16. Use Other Language raw string val input = """ <trophy type="request" version="1.0"> <patient> <parameter key="patient_id" value="" /> C (If patient_id and DPMS_id are both null, PAS shall set Patient=patient_internal_id and <parameter key="dpms_id" value=""/> C (If both parameter are not null, use input value. Only above two conditions, others will be <parameter key="first_name" value=""/> O <parameter key="last_name" value=""/> O <parameter key="middle_name" value=""/> O <parameter key="prefix" value=""/> O <parameter key="suffix" value=""/> O <parameter key="birth_date" value=""/> O ("yyyy-MM-dd") <parameter key="sex" value=""/> O (male,female,other) <parameter key="pregnancy" value=""/> O (not pregnant,possibly pregnant,definitively pregnant,unknown) empty string means not app <parameter key="insurance_number" value=""/> O <parameter key="address" value=""/> O <parameter key="town" value=""/> O <parameter key="postal_code" value=""/> O <parameter key="cellular_phone" value=""/> O <parameter key="home_phone" value=""/> O <parameter key="work_phone" value=""/> O <parameter key="comments" value=""/> O <parameter key="email" value=""/> O <parameter key="photo" value=""/> O <parameter key="kdis6_patient_directory" value=""/> O (used for import kdis6 images) <parameter key="images_imported" value=""/> C ("true/false", must be pair with kdis6_patient_directory) </patient> </trophy> """
  • 17. XML verify • The soap service output is xml string • You can use contains to verify simple value • But not easy to verify specific value
  • 18. XmlUnit • XML can be used for just about anything so deciding if two documents are equal to each other isn't as easy as a character for character match public void testXPathValues() throws Exception { String myJavaFlavours = "<java-flavours><jvm current='some platforms'>1.1.x</jvm>" + "<jvm current='no'>1.2.x</jvm><jvm current='yes'>1.3.x</jvm>" + "<jvm current='yes' latest='yes'>1.4.x</jvm></java-flavours>"; assertXpathEvaluatesTo("1.4.x", "//jvm[@latest='yes']", myJavaFlavours); assertXpathEvaluatesTo("2", "count(//jvm[@current='yes'])", myJavaFlavours); assertXpathValuesEqual("//jvm[4]/@latest", "//jvm[4]/@current", myJavaFlavours); assertXpathValuesNotEqual("//jvm[2]/@current", "//jvm[3]/@current", myJavaFlavours); }
  • 19. Scala XML val ns = <foo><bar><baz/>Text</bar><bin/></foo> ns "foo" // => <foo><bar>...</bar><bin/></foo> ns "foo" "bar" // => <bar><baz/>Text</bar> val ns = <foo id="bar"/> ns "@id" // => Text(bar)
  • 20. JRuby REXML xml = File.read('posts.xml') puts Benchmark.measure { doc, posts = REXML::Document.new(xml), [] doc.elements.each('posts/post') do |p| posts << p.attributes End }
  • 21. Model Date verify • After execute the method you want to know every thing is correct.
  • 22. Solutions • DbUnit can also help you to verify that your database data match an expected set of values. • Call hibernate Dao Directly • Verify by other business method
  • 23. Files verify • Custom utile • public static void checkDuplicateFiles(File dir)
  • 24. Notification verify • An ActiveMQ client utile • It should run in other thread and subscript before call method • It should time out if no message received after long time
  • 25. Wait future notification "There should have imageCreated notification after image is created " should { " ok " in { val srcPid = DataPrepare.createPatient val msg = future(ActiveMQ.receive("topic.imageCreated")) val imgId = DataPrepare.prepareImage(srcPid)._1 //wait a 3 second awaitAll(3000,msg) foreach{ v => v match { case Some(m) => { m.toString must contain (srcPid) m.toString must contain (imgId) } case None => 1 must_== 2 } } } }
  • 27. EasyMock public void testTransferShouldDebitSourceAccount(){ AccountController controller = new AccountController(); Account from = createMock(Account.class) Account to = createMock(Account.class) from.debit(42); replay(from); replay(to); controller.transfer(from,to,42); verify(from); }
  • 28. jMock Mockery context = new Mockery(); public void testTransferShouldDebitSourceAccount(){ AccountController controller = new AccountController(); Account from = context.mock(Account.class) Account to = context.mock(Account.class) context.checking(new Expectations() {{ oneOf(from).debit(42); }} controller.transfer(from,to,42); context.assertIsSatisfied(); }
  • 29. mockito public void testTransferShouldDebitSourceAccount(){ AccountController controller = new AccountController(); Account from = mock(Account.class) Account to = mock(Account.class) controller.transfer(from,to,42); verify(from).debit(42); }
  • 30. public void testTransferShouldDebitSourceAccount(){ AccountController controller = new AccountController(); Account from = createMock(Account.class) Account to = createMock(Account.class) from.debit(42); replay(from); replay(to); controller.transfer(from,to,42); verify(from); } Mockery context = new Mockery(); public void testTransferShouldDebitSourceAccount(){ AccountController controller = new AccountController(); Account from = context.mock(Account.class) Account to = context.mock(Account.class) context.checking(new Expectations() {{ oneOf(from).debit(42); }} controller.transfer(from,to,42); context.assertIsSatisfied(); } public void testTransferShouldDebitSourceAccount(){ AccountController controller = new AccountController(); Account from = mock(Account.class) Account to = mock(Account.class) controller.transfer(from,to,42); verify(from).debit(42); }
  • 32. Environment and Context Name Location Interaction DB Internal JDBC connect with hibernate ActiveMQ Internal socket,ActiveMQ library Demo External cmd,socket Config file External read/write file Registration table External system tool,reg Schedule External trigger 2D External cmd,socket Object Applications External cmd
  • 33. Unit testing styles • BDD • Better test code • It’s better not only for developer. If P.O. can read our test code is better • The test code should like specifics
  • 34. Traditional Status assert test public void testAdd() { int num1 = 3; int num2 = 2; int total = 5; int sum = 0; sum = Math.add(num1, num2); assertEquals(sum, total); }
  • 35. BDD specifications style class HelloWorldSpec extends Specification { "The 'Hello world' string" should { "contain 11 characters" in { "Hello world" must have size(11) } "start with 'Hello'" in { "Hello world" must startWith("Hello") } "end with 'world'" in { "Hello world" must endWith("world") } } "The sum" should { “ equals total " in { val num1 = 2,num2 = 3, total = 5 Math.add(num1, num2) must equalsTo(total) } } }