SlideShare une entreprise Scribd logo
1  sur  39
Java Unit Test and Coverage Introduction
Alex Su
2010/07/21

                                   Copyright 2010 TCloud Computing Inc.
Agenda

•Test-driven development
•Junit
   •Ant Integration
•Mock Object
   • Mockito
•Code Coverage Analysis
•Coverage Tool
   • Emma
   • Cobertura
•Case Study



                       Trend Micro Confidential
Test-driven development

Test-driven development (TDD) is a software development
 technique that relies on the repetition of a very short
 development cycle

•Add a test
•Run all tests and see if the new one fails
•Write some code
•Run the automated tests and see them succeed
•Refactor code




                        Trend Micro Confidential
Test-driven development - Scenario

Given/When/Then

Example 1: New lists are empty
Given a new list
Then the list should be empty.

Example 2: Lists with things in them are not empty.
Given a new list
When we add an object
Then the list should not be empty.



                          Trend Micro Confidential
Test-driven development - Scenario
class ListTest {
    @Test
    public void shouldKnowWhetherItIsEmpty() {
       List<String> list1 = new ArrayList<String>();
       assertTrue(list1.isEmpty());

        List<String> list2 = new ArrayList<String>();
        list2.add("element");
        assertFalse(list2.isEmpty());
    }
}




                        Trend Micro Confidential
Test-driven development




       Trend Micro Confidential
JUnit

• JUnit is a unit testing framework for the Java programming
  language.

• JUnit is linked as a JAR at compile-time; the framework
  resides under packages junit.framework for JUnit 3.8 and
  earlier and under org.junit for JUnit 4 and later.




                          Trend Micro Confidential
JUnit
• Test Runner
  A Runner runs tests. You will need to subclass Runner when using
  RunWith to invoke a custom runner.

• Test Fixture
  A test fixture represents the preparation needed to perform one or more
  tests

• Test Case
  A test case defines the fixture to run multiple tests.

• Test Suite
  A Test Suite is a Composite of Tests. It runs a collection of test cases.



                                 Trend Micro Confidential
Junit – Test Result

• Success

• Failure
  A failure is when one of your assertions fails, and your JUnit
  test notices and reports the fact.

• Error
  An error is when some other Exception occurs--one you
  haven't tested for and didn't expect, such as a
  NullPointerException or an
  ArrayIndexOutOfBoundsException.


                           Trend Micro Confidential
Junit – Annotation

• @BeforeClass
• @AfterClass
• @Before
• @After
• @Test
• @Ignore




                     Trend Micro Confidential
JUnit
public class DummyTest {
    private static List<String> list;

    @BeforeClass public static void beforeClass() {
        list = new ArrayList<String>();
    }
    @AfterClass public static void afterClass() {
        list = null;
    }
    @Before public void before() {
        list.add("Alex");
    }
    @After public void after() {
        list.remove("Alex");
    }
    @Test public void getElement() {
        String element = list.get(0);
        assertEquals(element, "Alex");
    }
    @Ignore("Not Ready to Run") @Test public void notRun() {
        assertEquals(list.size(), 2);
    }
    @Test(expected = IndexOutOfBoundsException.class)
    public void getElementWithException() {
        list.get(1);
    }
}



                                   Trend Micro Confidential
JUnit

@RunWith(Suite.class)
@SuiteClasses({
DummyTest1.class, DummyTest2.class})
public class DummyTestSuite {
}




                 Trend Micro Confidential
JUnit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations =
{ "classpath:appContext.xml" })
public class DummyTest {
    @Resource
    private DummyService dummyService;

    @Test
    public void createDummy() {
        Dummy dummy = new Dummy();
        dummy.setId(ID);
        dummy.setName("Hermione Granger");
        dummy.setDescription("Gryffindor");

        dummyService.createDummy(dummy);

        dummy = dummyService.getDummy(ID);
        assertNotNull(dummy);
    }
}


                          Trend Micro Confidential
Junit – Ant Integration
<junit showoutput="${build.test.dir}" printsummary="on"
fork="yes" haltonfailure="false>
   <classpath refid="classpath" />
   <formatter type="xml" />

   <batchtest todir="${build.test.dir}">
       <fileset dir="${test.dir}">
              <include name="**/*Test.java" />
       </fileset>
   </batchtest>
</junit>

<junitreport todir="${doc.test.dir}">
   <fileset dir="${build.test.dir}">
       <include name="**/TEST-*.xml" />
   </fileset>
    <report format="frames" todir="${doc.test.dir}" />
</junitreport>

                        Trend Micro Confidential
Mock Object

•supplies non-deterministic results (e.g. the current
 time or the current temperature);
•has states that are difficult to create or reproduce
 (e.g. a network error);
•is slow (e.g. a complete database, which would
 have to be initialized before the test);
•does not yet exist or may change behavior;
•would have to include information and methods
 exclusively for testing purposes (and not for its
 actual task).




                          Trend Micro Confidential
Mock Object - Mockito

•Argument matchers
•Verifying exact number of invocations / at least x /
 never
•Verification in order
•Shorthand for mocks creation - @Mock annotation
•Stubbing consecutive calls
•Spying on real objects
•Aliases for behavior driven development




                          Trend Micro Confidential
Mock Object - Mockito
public class ListTest {
    private List<String> mockedList;

    @Before
    public void initMocks() {
        mockedList = mock(List.class);


given(mockedList.get(0)).willReturn("first", "second");
        given(mockedList.get(1)).willThrow(new
IndexOutOfBoundsException());
    }

    @Test
    public void getList() {
        assertEquals("first", mockedList.get(0));
        assertEquals("second", mockedList.get(0));
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void getListWithException() {
        mockedList.get(1);
    }
}

                              Trend Micro Confidential
Code Coverage Analysis

•Finding areas of a program not exercised by a set
 of test cases.
•Creating additional test cases to increase coverage.
•Determining a quantitative measure of code
 coverage, which is an indirect measure of quality.
•Identifying redundant test cases that do not
 increase coverage.




                          Trend Micro Confidential
Code Coverage Analysis

•Basic Metrics
   •Statement Coverage(Line)
   •Basic Block Coverage
   •Decision Coverage(Branch)
   •Condition Coverage
   •Multiple Condition Coverage
   •Condition/Decision Coverage
   •Modified Condition/Decision Coverage
   •Path Coverage




                       Trend Micro Confidential
Code Coverage Analysis

•Statement Coverage(Line)
•Basic Block Coverage
•Decision Coverage(Branch)
•Condition Coverage
•Multiple Condition Coverage

boolean a = true, b = true;
if(a && b) {
    System.out.println("true");
} else {
    System.out.println("false");
}




                          Trend Micro Confidential
Code Coverage Analysis

•Condition/Decision Coverage(C/DC)
•Modified Condition/Decision Coverage(MC/DC)

boolean a = true, b = true;
if(a && b) {
    System.out.println("true");
} else {
    System.out.println("false");
}

if(a || b) {
    System.out.println("true");
} else {
    System.out.println("false");
}




                          Trend Micro Confidential
Code Coverage Analysis

•Path Coverage

                                                    Y
 A = 3 and X = 5                  A>1
 A = 0 and X = 3

 A = 0 and X = 0                N                        X=0
 A = 2 and X = 0

                                 A=2                Y
                                  or
                                 X>1


                               N                        X = 20



                                print x

                         Trend Micro Confidential
Code Coverage Analysis

•Other Metrics
   •Function Coverage
   •Data Flow Coverage
   •Loop Coverage
   •Race Coverage
   •Relational Operator Coverage




                        Trend Micro Confidential
Coverage Tool

•Instrumentation
   • Source code instrumentation
   • Bytecode instrumentation
   • Runtime instrumentation




                        Trend Micro Confidential
Coverage Tool

       Possible feature                   Runtime                      Bytecode              Source code

Gathers method coverage      yes                            yes                   yes

Gathers statement coverage line only                        yes                   yes

Gathers branch coverage      indirectly                     yes                   yes
Can work without source      yes                            yes                   no
Requires separate build      no                             no                    yes

Requires specialised runtime yes                            not accurate          no

View coverage data inline
                             not accurate                   yes                   yes
with source


Source level directives to
                             no                             no                    yes
control coverage gathering

Runtime performace           high impact                    variable              variable
Container friendly           no                             not accurate          yes




                                                Trend Micro Confidential
Coverage Tool

•Reports are filterable so you can tell what needs to
 be evaluated for code coverage.
•offline and on-the-fly instrumentation.
•Ant integration.
•JUnit integration.




                          Trend Micro Confidential
Coverage Tool - Emma

•Last update : 2005-06-13
•Stats on both class and method coverage
•Partial/fractional line coverages is unique trait -
 shown in yellow when there are multiple
 conditions in a conditional block
•Stricter code coverage.
•Integration with Eclipse available -
 http://www.eclemma.org/
•Better documentation than cobertura.
•Instrumentation process is faster than cobertura.
•Standalone library and does not have any external
 dependencies.
•Common public license 1.0 friendlier that GPL.
                          Trend Micro Confidential
Coverage Tool - Cobertura

• Last update : 2010-03-03
• GPL'd version of JCoverage (which is commercial).
• Prettier reports.
• Branch/block and line coverages only - no class or
  method level coverage.
• How many times a line has been executed
• <cobertura-check> where one can specify percentage
  of coverage that's a MUST or else build fails.
• Data merge feature - good for QA labs... for merging
  coverage data to prepare historical trend graphs.
• Depends on other third party libraries.
• Integration with Eclipse available -
  http://ecobertura.johoop.de/

                           Trend Micro Confidential
Coverage Tool – Comparsion(Exception)

• Source Code
String str = "abc";
System.out.println(str.substring(5));


•Decompile Result
String str = "abc";
System.out.println(str.substring(5));




                                        Trend Micro Confidential
Coverage Tool - Comparsion(Exception)

• Emma
boolean aflag[] = ($VRc != null ? $VRc : $VRi())[3];
String s = "abc";
System.out.println(s.substring(5));
aflag[0] = true;




                                    Trend Micro Confidential
Coverage Tool - Comparsion(Exception)

• Cobertura
boolean flag = false;
int __cobertura__branch__number__ = -1;
TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 25);
String str = "abc";
TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 26);
System.out.println(str.substring(5));
TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 27);




                                   Trend Micro Confidential
Coverage Tool - Comparsion(Exception)

• Clover
__CLR3_0_217a17agbtkjkdv.R.inc(1571);
__CLR3_0_217a17agbtkjkdv.R.inc(1572);
String str = "abc";
__CLR3_0_217a17agbtkjkdv.R.inc(1573);
System.out.println(str.substring(5));




                                   Trend Micro Confidential
Coverage Tool – Comparsion(Loop)

•Source Code
List<String> list = new ArrayList<String>();
for(String element : list) {
  System.out.println(element);
}


• Decompile result
String element;
for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(element))
  element = (String)iterator.next();




                                         Trend Micro Confidential
Coverage Tool - Comparsion(Loop)

• Emma
boolean aflag[] = ($VRc != null ? $VRc : $VRi())[4];
List list = new ArrayList();
Iterator iterator = list.iterator();
aflag[0] = true;
do
{
   aflag[2] = true;
   if(iterator.hasNext())
   {
               String s = (String)iterator.next();
               System.out.println(s);
               aflag[1] = true;
   } else
   {
               break;
   }
} while(true);
aflag[3] = true;


                                          Trend Micro Confidential
Coverage Tool - Comparsion(Loop)

• Cobertura
boolean flag = false;
int __cobertura__branch__number__ = -1;
TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 36);
List list = new ArrayList();
TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 37);
Iterator iterator = list.iterator();
do
{
      TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 37);
      __cobertura__line__number__ = 37;
      __cobertura__branch__number__ = 0;
      if(iterator.hasNext())
      {
                          if(__cobertura__branch__number__ >= 0)
                          {

                     TouchCollector.touchJump("tcloud.dummy.service.CoverageTestMain", __cobertura__line__number__, __cobertura__branch__numb
    er__, false);
                                            __cobertura__branch__number__ = -1;
                     }
                     String element = (String)iterator.next();
                     TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 38);
                     System.out.println(element);
    } else
    {
                     if(__cobertura__line__number__ == 37 && __cobertura__branch__number__ == 0)
                     {

                     TouchCollector.touchJump("tcloud.dummy.service.CoverageTestMain", __cobertura__line__number__, __cobertura__branch__numb
    er__, true);
                                          __cobertura__branch__number__ = -1;
                     }
                     TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 40);
                     return;
    }
} while(true);                                                             Trend Micro Confidential
Coverage Tool - Comparsion(Loop)

• Clover
__CLR3_0_2145145gbu63tpg.R.inc(1462);
__CLR3_0_2145145gbu63tpg.R.inc(1463);
List list = new ArrayList();
__CLR3_0_2145145gbu63tpg.R.inc(1464);
String element;
for(Iterator iterator = list.iterator(); iterator.hasNext();
  System.out.println(element))
  {
       element = (String)iterator.next();
       __CLR3_0_2145145gbu63tpg.R.inc(1465);
  }




                                          Trend Micro Confidential
Coverage Tool - Comparsion(Loop)

• Clover with decompile result
  Iterator iterator;
   __CLR3_0_2166166gbu71moi.R.inc(1535);
   __CLR3_0_2166166gbu71moi.R.inc(1536);
   List list = new ArrayList();
   __CLR3_0_2166166gbu71moi.R.inc(1537);
   __CLR3_0_2166166gbu71moi.R.inc(1538);
   iterator = list.iterator();
_L4:
   if(iterator.hasNext())
   {
                  __CLR3_0_2166166gbu71moi.R.iget(1539);
   } else
   {
                  __CLR3_0_2166166gbu71moi.R.iget(1540);
                  return;
   }
   if(true) goto _L2; else goto _L1
_L1:
   break; /* Loop/switch isn't completed */
_L2:
   __CLR3_0_2166166gbu71moi.R.inc(1541);
   String element = (String)iterator.next();
   System.out.println(element);
   if(true) goto _L4; else goto _L3
_L3:
                                                     Trend Micro Confidential
Case Study




 Trend Micro Confidential
THANK YOU!




  Trend Micro Confidential

Contenu connexe

Tendances

Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldDror Helper
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnitinTwentyEight Minutes
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesNarendra Pathai
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010kgayda
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done RightBrian Fenton
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 

Tendances (20)

Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real World
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnit
 
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
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit Testing Done Right
Unit Testing Done RightUnit Testing Done Right
Unit Testing Done Right
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 

En vedette

What test coverage mean to us
What test coverage mean to usWhat test coverage mean to us
What test coverage mean to usJoseph Yao
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in RailsJames Gray
 
Effective test coverage Techniques
Effective test coverage TechniquesEffective test coverage Techniques
Effective test coverage TechniquesPhanindra Kishore
 
Test Coverage: An Art and a Science
Test Coverage: An Art and a ScienceTest Coverage: An Art and a Science
Test Coverage: An Art and a ScienceTeamQualityPro
 
[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuit[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuitNAVER D2
 
[223] h base consistent secondary indexing
[223] h base consistent secondary indexing[223] h base consistent secondary indexing
[223] h base consistent secondary indexingNAVER D2
 
[232] 수퍼컴퓨팅과 데이터 어낼리틱스
[232] 수퍼컴퓨팅과 데이터 어낼리틱스[232] 수퍼컴퓨팅과 데이터 어낼리틱스
[232] 수퍼컴퓨팅과 데이터 어낼리틱스NAVER D2
 
[113] lessons from realm
[113] lessons from realm[113] lessons from realm
[113] lessons from realmNAVER D2
 
[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기
[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기
[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기NAVER D2
 
[224] 번역 모델 기반_질의_교정_시스템
[224] 번역 모델 기반_질의_교정_시스템[224] 번역 모델 기반_질의_교정_시스템
[224] 번역 모델 기반_질의_교정_시스템NAVER D2
 
[131] packetbeat과 elasticsearch
[131] packetbeat과 elasticsearch[131] packetbeat과 elasticsearch
[131] packetbeat과 elasticsearchNAVER D2
 
[142] how riot works
[142] how riot works[142] how riot works
[142] how riot worksNAVER D2
 
[112] 실전 스위프트 프로그래밍
[112] 실전 스위프트 프로그래밍[112] 실전 스위프트 프로그래밍
[112] 실전 스위프트 프로그래밍NAVER D2
 
[252] 증분 처리 플랫폼 cana 개발기
[252] 증분 처리 플랫폼 cana 개발기[252] 증분 처리 플랫폼 cana 개발기
[252] 증분 처리 플랫폼 cana 개발기NAVER D2
 
[161] 데이터사이언스팀 빌딩
[161] 데이터사이언스팀 빌딩[161] 데이터사이언스팀 빌딩
[161] 데이터사이언스팀 빌딩NAVER D2
 
[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2NAVER D2
 
[153] apache reef
[153] apache reef[153] apache reef
[153] apache reefNAVER D2
 
[243] turning data into value
[243] turning data into value[243] turning data into value
[243] turning data into valueNAVER D2
 
[133] 브라우저는 vsync를 어떻게 활용하고 있을까
[133] 브라우저는 vsync를 어떻게 활용하고 있을까[133] 브라우저는 vsync를 어떻게 활용하고 있을까
[133] 브라우저는 vsync를 어떻게 활용하고 있을까NAVER D2
 

En vedette (20)

What test coverage mean to us
What test coverage mean to usWhat test coverage mean to us
What test coverage mean to us
 
Structure testing
Structure testingStructure testing
Structure testing
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in Rails
 
Effective test coverage Techniques
Effective test coverage TechniquesEffective test coverage Techniques
Effective test coverage Techniques
 
Test Coverage: An Art and a Science
Test Coverage: An Art and a ScienceTest Coverage: An Art and a Science
Test Coverage: An Art and a Science
 
[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuit[231] the simplicity of cluster apps with circuit
[231] the simplicity of cluster apps with circuit
 
[223] h base consistent secondary indexing
[223] h base consistent secondary indexing[223] h base consistent secondary indexing
[223] h base consistent secondary indexing
 
[232] 수퍼컴퓨팅과 데이터 어낼리틱스
[232] 수퍼컴퓨팅과 데이터 어낼리틱스[232] 수퍼컴퓨팅과 데이터 어낼리틱스
[232] 수퍼컴퓨팅과 데이터 어낼리틱스
 
[113] lessons from realm
[113] lessons from realm[113] lessons from realm
[113] lessons from realm
 
[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기
[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기
[234] 산업 현장을 위한 증강 현실 기기 daqri helmet 개발기
 
[224] 번역 모델 기반_질의_교정_시스템
[224] 번역 모델 기반_질의_교정_시스템[224] 번역 모델 기반_질의_교정_시스템
[224] 번역 모델 기반_질의_교정_시스템
 
[131] packetbeat과 elasticsearch
[131] packetbeat과 elasticsearch[131] packetbeat과 elasticsearch
[131] packetbeat과 elasticsearch
 
[142] how riot works
[142] how riot works[142] how riot works
[142] how riot works
 
[112] 실전 스위프트 프로그래밍
[112] 실전 스위프트 프로그래밍[112] 실전 스위프트 프로그래밍
[112] 실전 스위프트 프로그래밍
 
[252] 증분 처리 플랫폼 cana 개발기
[252] 증분 처리 플랫폼 cana 개발기[252] 증분 처리 플랫폼 cana 개발기
[252] 증분 처리 플랫폼 cana 개발기
 
[161] 데이터사이언스팀 빌딩
[161] 데이터사이언스팀 빌딩[161] 데이터사이언스팀 빌딩
[161] 데이터사이언스팀 빌딩
 
[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2
 
[153] apache reef
[153] apache reef[153] apache reef
[153] apache reef
 
[243] turning data into value
[243] turning data into value[243] turning data into value
[243] turning data into value
 
[133] 브라우저는 vsync를 어떻게 활용하고 있을까
[133] 브라우저는 vsync를 어떻게 활용하고 있을까[133] 브라우저는 vsync를 어떻게 활용하고 있을까
[133] 브라우저는 vsync를 어떻게 활용하고 있을까
 

Similaire à Java Unit Test and Coverage Introduction

TDD and mock objects
TDD and mock objectsTDD and mock objects
TDD and mock objectsSteve Zhang
 
Software testing: an introduction - 2017
Software testing: an introduction - 2017Software testing: an introduction - 2017
Software testing: an introduction - 2017XavierDevroey
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in JavaAnkur Maheshwari
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Ukraine
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developersAnton Udovychenko
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testabilitydrewz lin
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projectsVincent Massol
 
Testing and Building Android
Testing and Building AndroidTesting and Building Android
Testing and Building AndroidDroidcon Berlin
 
Search-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing SystemsSearch-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing SystemsLionel Briand
 
Современные технологии и инструменты анализа вредоносного ПО
Современные технологии и инструменты анализа вредоносного ПОСовременные технологии и инструменты анализа вредоносного ПО
Современные технологии и инструменты анализа вредоносного ПОPositive Hack Days
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Ivan Piskunov
 

Similaire à Java Unit Test and Coverage Introduction (20)

Test driven development
Test driven developmentTest driven development
Test driven development
 
TDD and mock objects
TDD and mock objectsTDD and mock objects
TDD and mock objects
 
Software testing: an introduction - 2017
Software testing: an introduction - 2017Software testing: an introduction - 2017
Software testing: an introduction - 2017
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability谷歌 Scott-lessons learned in testability
谷歌 Scott-lessons learned in testability
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
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
 
Testing and Building Android
Testing and Building AndroidTesting and Building Android
Testing and Building Android
 
Mini training - Moving to xUnit.net
Mini training - Moving to xUnit.netMini training - Moving to xUnit.net
Mini training - Moving to xUnit.net
 
Search-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing SystemsSearch-Based Robustness Testing of Data Processing Systems
Search-Based Robustness Testing of Data Processing Systems
 
Современные технологии и инструменты анализа вредоносного ПО
Современные технологии и инструменты анализа вредоносного ПОСовременные технологии и инструменты анализа вредоносного ПО
Современные технологии и инструменты анализа вредоносного ПО
 
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
Современные технологии и инструменты анализа вредоносного ПО_PHDays_2017_Pisk...
 

Plus de Alex Su

Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
One click deployment
One click deploymentOne click deployment
One click deploymentAlex Su
 
Scrum Introduction
Scrum IntroductionScrum Introduction
Scrum IntroductionAlex Su
 
Redis Introduction
Redis IntroductionRedis Introduction
Redis IntroductionAlex Su
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Using puppet
Using puppetUsing puppet
Using puppetAlex Su
 
JMS Introduction
JMS IntroductionJMS Introduction
JMS IntroductionAlex Su
 
Spring Framework Introduction
Spring Framework IntroductionSpring Framework Introduction
Spring Framework IntroductionAlex Su
 
Cascading introduction
Cascading introductionCascading introduction
Cascading introductionAlex Su
 

Plus de Alex Su (9)

Node js introduction
Node js introductionNode js introduction
Node js introduction
 
One click deployment
One click deploymentOne click deployment
One click deployment
 
Scrum Introduction
Scrum IntroductionScrum Introduction
Scrum Introduction
 
Redis Introduction
Redis IntroductionRedis Introduction
Redis Introduction
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Using puppet
Using puppetUsing puppet
Using puppet
 
JMS Introduction
JMS IntroductionJMS Introduction
JMS Introduction
 
Spring Framework Introduction
Spring Framework IntroductionSpring Framework Introduction
Spring Framework Introduction
 
Cascading introduction
Cascading introductionCascading introduction
Cascading introduction
 

Dernier

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

Java Unit Test and Coverage Introduction

  • 1. Java Unit Test and Coverage Introduction Alex Su 2010/07/21 Copyright 2010 TCloud Computing Inc.
  • 2. Agenda •Test-driven development •Junit •Ant Integration •Mock Object • Mockito •Code Coverage Analysis •Coverage Tool • Emma • Cobertura •Case Study Trend Micro Confidential
  • 3. Test-driven development Test-driven development (TDD) is a software development technique that relies on the repetition of a very short development cycle •Add a test •Run all tests and see if the new one fails •Write some code •Run the automated tests and see them succeed •Refactor code Trend Micro Confidential
  • 4. Test-driven development - Scenario Given/When/Then Example 1: New lists are empty Given a new list Then the list should be empty. Example 2: Lists with things in them are not empty. Given a new list When we add an object Then the list should not be empty. Trend Micro Confidential
  • 5. Test-driven development - Scenario class ListTest { @Test public void shouldKnowWhetherItIsEmpty() { List<String> list1 = new ArrayList<String>(); assertTrue(list1.isEmpty()); List<String> list2 = new ArrayList<String>(); list2.add("element"); assertFalse(list2.isEmpty()); } } Trend Micro Confidential
  • 6. Test-driven development Trend Micro Confidential
  • 7. JUnit • JUnit is a unit testing framework for the Java programming language. • JUnit is linked as a JAR at compile-time; the framework resides under packages junit.framework for JUnit 3.8 and earlier and under org.junit for JUnit 4 and later. Trend Micro Confidential
  • 8. JUnit • Test Runner A Runner runs tests. You will need to subclass Runner when using RunWith to invoke a custom runner. • Test Fixture A test fixture represents the preparation needed to perform one or more tests • Test Case A test case defines the fixture to run multiple tests. • Test Suite A Test Suite is a Composite of Tests. It runs a collection of test cases. Trend Micro Confidential
  • 9. Junit – Test Result • Success • Failure A failure is when one of your assertions fails, and your JUnit test notices and reports the fact. • Error An error is when some other Exception occurs--one you haven't tested for and didn't expect, such as a NullPointerException or an ArrayIndexOutOfBoundsException. Trend Micro Confidential
  • 10. Junit – Annotation • @BeforeClass • @AfterClass • @Before • @After • @Test • @Ignore Trend Micro Confidential
  • 11. JUnit public class DummyTest { private static List<String> list; @BeforeClass public static void beforeClass() { list = new ArrayList<String>(); } @AfterClass public static void afterClass() { list = null; } @Before public void before() { list.add("Alex"); } @After public void after() { list.remove("Alex"); } @Test public void getElement() { String element = list.get(0); assertEquals(element, "Alex"); } @Ignore("Not Ready to Run") @Test public void notRun() { assertEquals(list.size(), 2); } @Test(expected = IndexOutOfBoundsException.class) public void getElementWithException() { list.get(1); } } Trend Micro Confidential
  • 13. JUnit @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:appContext.xml" }) public class DummyTest { @Resource private DummyService dummyService; @Test public void createDummy() { Dummy dummy = new Dummy(); dummy.setId(ID); dummy.setName("Hermione Granger"); dummy.setDescription("Gryffindor"); dummyService.createDummy(dummy); dummy = dummyService.getDummy(ID); assertNotNull(dummy); } } Trend Micro Confidential
  • 14. Junit – Ant Integration <junit showoutput="${build.test.dir}" printsummary="on" fork="yes" haltonfailure="false> <classpath refid="classpath" /> <formatter type="xml" /> <batchtest todir="${build.test.dir}"> <fileset dir="${test.dir}"> <include name="**/*Test.java" /> </fileset> </batchtest> </junit> <junitreport todir="${doc.test.dir}"> <fileset dir="${build.test.dir}"> <include name="**/TEST-*.xml" /> </fileset> <report format="frames" todir="${doc.test.dir}" /> </junitreport> Trend Micro Confidential
  • 15. Mock Object •supplies non-deterministic results (e.g. the current time or the current temperature); •has states that are difficult to create or reproduce (e.g. a network error); •is slow (e.g. a complete database, which would have to be initialized before the test); •does not yet exist or may change behavior; •would have to include information and methods exclusively for testing purposes (and not for its actual task). Trend Micro Confidential
  • 16. Mock Object - Mockito •Argument matchers •Verifying exact number of invocations / at least x / never •Verification in order •Shorthand for mocks creation - @Mock annotation •Stubbing consecutive calls •Spying on real objects •Aliases for behavior driven development Trend Micro Confidential
  • 17. Mock Object - Mockito public class ListTest { private List<String> mockedList; @Before public void initMocks() { mockedList = mock(List.class); given(mockedList.get(0)).willReturn("first", "second"); given(mockedList.get(1)).willThrow(new IndexOutOfBoundsException()); } @Test public void getList() { assertEquals("first", mockedList.get(0)); assertEquals("second", mockedList.get(0)); } @Test(expected = IndexOutOfBoundsException.class) public void getListWithException() { mockedList.get(1); } } Trend Micro Confidential
  • 18. Code Coverage Analysis •Finding areas of a program not exercised by a set of test cases. •Creating additional test cases to increase coverage. •Determining a quantitative measure of code coverage, which is an indirect measure of quality. •Identifying redundant test cases that do not increase coverage. Trend Micro Confidential
  • 19. Code Coverage Analysis •Basic Metrics •Statement Coverage(Line) •Basic Block Coverage •Decision Coverage(Branch) •Condition Coverage •Multiple Condition Coverage •Condition/Decision Coverage •Modified Condition/Decision Coverage •Path Coverage Trend Micro Confidential
  • 20. Code Coverage Analysis •Statement Coverage(Line) •Basic Block Coverage •Decision Coverage(Branch) •Condition Coverage •Multiple Condition Coverage boolean a = true, b = true; if(a && b) { System.out.println("true"); } else { System.out.println("false"); } Trend Micro Confidential
  • 21. Code Coverage Analysis •Condition/Decision Coverage(C/DC) •Modified Condition/Decision Coverage(MC/DC) boolean a = true, b = true; if(a && b) { System.out.println("true"); } else { System.out.println("false"); } if(a || b) { System.out.println("true"); } else { System.out.println("false"); } Trend Micro Confidential
  • 22. Code Coverage Analysis •Path Coverage Y A = 3 and X = 5 A>1 A = 0 and X = 3 A = 0 and X = 0 N X=0 A = 2 and X = 0 A=2 Y or X>1 N X = 20 print x Trend Micro Confidential
  • 23. Code Coverage Analysis •Other Metrics •Function Coverage •Data Flow Coverage •Loop Coverage •Race Coverage •Relational Operator Coverage Trend Micro Confidential
  • 24. Coverage Tool •Instrumentation • Source code instrumentation • Bytecode instrumentation • Runtime instrumentation Trend Micro Confidential
  • 25. Coverage Tool Possible feature Runtime Bytecode Source code Gathers method coverage yes yes yes Gathers statement coverage line only yes yes Gathers branch coverage indirectly yes yes Can work without source yes yes no Requires separate build no no yes Requires specialised runtime yes not accurate no View coverage data inline not accurate yes yes with source Source level directives to no no yes control coverage gathering Runtime performace high impact variable variable Container friendly no not accurate yes Trend Micro Confidential
  • 26. Coverage Tool •Reports are filterable so you can tell what needs to be evaluated for code coverage. •offline and on-the-fly instrumentation. •Ant integration. •JUnit integration. Trend Micro Confidential
  • 27. Coverage Tool - Emma •Last update : 2005-06-13 •Stats on both class and method coverage •Partial/fractional line coverages is unique trait - shown in yellow when there are multiple conditions in a conditional block •Stricter code coverage. •Integration with Eclipse available - http://www.eclemma.org/ •Better documentation than cobertura. •Instrumentation process is faster than cobertura. •Standalone library and does not have any external dependencies. •Common public license 1.0 friendlier that GPL. Trend Micro Confidential
  • 28. Coverage Tool - Cobertura • Last update : 2010-03-03 • GPL'd version of JCoverage (which is commercial). • Prettier reports. • Branch/block and line coverages only - no class or method level coverage. • How many times a line has been executed • <cobertura-check> where one can specify percentage of coverage that's a MUST or else build fails. • Data merge feature - good for QA labs... for merging coverage data to prepare historical trend graphs. • Depends on other third party libraries. • Integration with Eclipse available - http://ecobertura.johoop.de/ Trend Micro Confidential
  • 29. Coverage Tool – Comparsion(Exception) • Source Code String str = "abc"; System.out.println(str.substring(5)); •Decompile Result String str = "abc"; System.out.println(str.substring(5)); Trend Micro Confidential
  • 30. Coverage Tool - Comparsion(Exception) • Emma boolean aflag[] = ($VRc != null ? $VRc : $VRi())[3]; String s = "abc"; System.out.println(s.substring(5)); aflag[0] = true; Trend Micro Confidential
  • 31. Coverage Tool - Comparsion(Exception) • Cobertura boolean flag = false; int __cobertura__branch__number__ = -1; TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 25); String str = "abc"; TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 26); System.out.println(str.substring(5)); TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 27); Trend Micro Confidential
  • 32. Coverage Tool - Comparsion(Exception) • Clover __CLR3_0_217a17agbtkjkdv.R.inc(1571); __CLR3_0_217a17agbtkjkdv.R.inc(1572); String str = "abc"; __CLR3_0_217a17agbtkjkdv.R.inc(1573); System.out.println(str.substring(5)); Trend Micro Confidential
  • 33. Coverage Tool – Comparsion(Loop) •Source Code List<String> list = new ArrayList<String>(); for(String element : list) { System.out.println(element); } • Decompile result String element; for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(element)) element = (String)iterator.next(); Trend Micro Confidential
  • 34. Coverage Tool - Comparsion(Loop) • Emma boolean aflag[] = ($VRc != null ? $VRc : $VRi())[4]; List list = new ArrayList(); Iterator iterator = list.iterator(); aflag[0] = true; do { aflag[2] = true; if(iterator.hasNext()) { String s = (String)iterator.next(); System.out.println(s); aflag[1] = true; } else { break; } } while(true); aflag[3] = true; Trend Micro Confidential
  • 35. Coverage Tool - Comparsion(Loop) • Cobertura boolean flag = false; int __cobertura__branch__number__ = -1; TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 36); List list = new ArrayList(); TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 37); Iterator iterator = list.iterator(); do { TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 37); __cobertura__line__number__ = 37; __cobertura__branch__number__ = 0; if(iterator.hasNext()) { if(__cobertura__branch__number__ >= 0) { TouchCollector.touchJump("tcloud.dummy.service.CoverageTestMain", __cobertura__line__number__, __cobertura__branch__numb er__, false); __cobertura__branch__number__ = -1; } String element = (String)iterator.next(); TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 38); System.out.println(element); } else { if(__cobertura__line__number__ == 37 && __cobertura__branch__number__ == 0) { TouchCollector.touchJump("tcloud.dummy.service.CoverageTestMain", __cobertura__line__number__, __cobertura__branch__numb er__, true); __cobertura__branch__number__ = -1; } TouchCollector.touch("tcloud.dummy.service.CoverageTestMain", 40); return; } } while(true); Trend Micro Confidential
  • 36. Coverage Tool - Comparsion(Loop) • Clover __CLR3_0_2145145gbu63tpg.R.inc(1462); __CLR3_0_2145145gbu63tpg.R.inc(1463); List list = new ArrayList(); __CLR3_0_2145145gbu63tpg.R.inc(1464); String element; for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(element)) { element = (String)iterator.next(); __CLR3_0_2145145gbu63tpg.R.inc(1465); } Trend Micro Confidential
  • 37. Coverage Tool - Comparsion(Loop) • Clover with decompile result Iterator iterator; __CLR3_0_2166166gbu71moi.R.inc(1535); __CLR3_0_2166166gbu71moi.R.inc(1536); List list = new ArrayList(); __CLR3_0_2166166gbu71moi.R.inc(1537); __CLR3_0_2166166gbu71moi.R.inc(1538); iterator = list.iterator(); _L4: if(iterator.hasNext()) { __CLR3_0_2166166gbu71moi.R.iget(1539); } else { __CLR3_0_2166166gbu71moi.R.iget(1540); return; } if(true) goto _L2; else goto _L1 _L1: break; /* Loop/switch isn't completed */ _L2: __CLR3_0_2166166gbu71moi.R.inc(1541); String element = (String)iterator.next(); System.out.println(element); if(true) goto _L4; else goto _L3 _L3: Trend Micro Confidential
  • 38. Case Study Trend Micro Confidential
  • 39. THANK YOU! Trend Micro Confidential