SlideShare une entreprise Scribd logo
1  sur  19
Télécharger pour lire hors ligne
JUnit 源码分析
 雷腾 L.T - leiteng@taobao.com
搜索算法与技术 – 搜索应用团队
一、代码层次结构
                                       org.junit




                               注解&断言



runner 描述/收          runners             rule      internal 内部实        experimental 试
集/运行/分析            Runner标准实现           规则              现                  用包

                                                      RunnerBuilder实
    manipulation         model
                                                            现
  测试过滤和排序               数据模型

                                                       Request实现
    notification
   收集测试信息
                                                       Matcher实现



                                                        Runner实现
二、测试执行流
Junit测试
                  执行
执行流程           @BeforeClass
                                 执行@Before

 @Befor
 @After
 @BeforClass          遍历测试,                  执行@Test
 @AfterClass            Next?

 @Test
 @Ignore
                                  执行@After
 @Rule

                     执行
执行状态Show           @AfterClass
三、测试数据流
Junit入口JUnitCore
测试请求封装Request
测试执行接口Runner
测试执行者BlockJUnit4ClassRunner

 Junit调用
             创建Request
   程序


                         Request.getRunner


JUnit调用结束   Runner.run
3.1 调用入口JUnitCore
JUnitCore接口:
–   public Result run(Class<?>... classes) ①
–   public Result run(Computer computer, Class<?>... classes) ②
–   public Result run(Request request) ③
–   public Result run(junit.framework.Test test) ④
–   public Result run(Runner runner) ⑤


方法①和方法②都会调用第三个方法③
方法③会调用request.getRunner
方法④用于执行JUnit3.8风格的测试用例
最后方法③和方法④都会调用方法⑤
3.2 请求封装Request
封装接口:
– public static Request method(Class<?> clazz, String method)
– public static Request aClass(Class<?> clazz)
– public static Request classWithoutSuiteMethod(Class<?> clazz)
– public static Request classes(Computer com Class<?>... classes)
– public static Request classes(Class<?>... classes)
– public static Request errorReport(Class<?> klass, Throwable cau
  se)
– public static Request runner(final Runner runner)


直接或者间接创建AllDefaultPossibilitiesBuilder 对象
RunnerBuilder决定用什么Runner执行测试
3.3 Request.getRunner流①
创建AllDefaultPossibilitiesBuilder
调用RunnerBuilder.safeRunnerForClass接口
调用DefaultRunnerBuilder.runnerForClass接口
选用Runner
3.4 选择Runner流③
Ignored注解忽略class
自定义RunWith
自定义Suite
JUnit3.x测试
默认JUnit4Runner
3.5 Runner.run流②
Run接口
– public void run(final RunNotifier notifier) {
  EachTestNotifier testNotifier= new
  EachTestNotifier(notifier,getDescription());
  Statement statement= classBlock(notifier);
  statement.evaluate();
  …}

 Runner.run
                               创建Test监控
   流程



                                                  创建Statement




run结果状态显示                  Statement.evaluate
3.6 创建Statement流④
创建Statement,覆盖evaluate
BeforeClass包装
AfterClass包装
  创建
            创建Statement,
Statement                    @BeforeClass?   是   BeforeClass包装器
             覆盖evaluate
  流程

                                   否


                              @AfterClass?   是   AfterClass包装器


            Statement实例对象    否
3.7 evaluate流程⑤
遍历可用测试
反射调用
监控测试状态
执行测试
3.8 执行测试流程⑥




ExpectException
Rule
FailOnTimeout
RunBefore
RunAfter
3.9 执行包装器Statement
类名                  作用
InvokeMethod        通过映射机制执行不带参数的测试方法
RunBefores          尝试先运行所有@BeforeClass和@Before方法,只要出
                    错就会终止连锁执行行为
RunAfters           在执行完测试目标方法之后,尝试执行所有的@After
                    和@AfterClass方法,并且把错误统一输出处理
                    注意即使测试方法本身出现错误,@After和
                    @AfterClass方法也会被执行一次
FailOnTimeout       开一个线程来跑测试方法,并且通过Thread.join来判定
                    该线程是否超时。如果出错或者超时都会认为是失败。
ExpectedException   用于检测标明期待出现错误的测试方法是否通过了测
                    试(无异常抛出),或者抛出的异常和期待值不一样。
Fail                直接出错,中断所有后续的步骤。
3.10 规则MethodRule
测试的运行及报告方式的一种替代方案
可以同时实施多个不同的MethodRule
junit默认提供MethodRule
–   ErrorCollector : 收集一个测试方法里面的错误
–   ExpectedException : 对抛出的异常提供灵活的判断
–   ExternalResource : 操控外部资源,如启动或者停止服务器
–   TemporaryFolder : 进行测试期间相关的测试操作。例如创建
    测试所需的临时文件,并且在测试完结之后删除它们。
–   TestName : 在测试方法中记住测试的名称
–   TestWatchman : 在方法执行的事件中添加额外的逻辑
–   Timeout : 当测试的执行超过特定时间后导致测试失败
–   Verifier : 假如对象状态不正确时让测试失败
3.10 规则MethodRule
测试的运行及报告方式的一种替代方案
可以同时实施多个不同的MethodRule
junit默认提供MethodRule
–   ErrorCollector : 收集一个测试方法里面的错误
–   ExpectedException : 对抛出的异常提供灵活的判断
–   ExternalResource : 操控外部资源,如启动或者停止服务器
–   TemporaryFolder : 进行测试期间相关的测试操作。例如创建
    测试所需的临时文件,并且在测试完结之后删除它们。
–   TestName : 在测试方法中记住测试的名称
–   TestWatchman : 在方法执行的事件中添加额外的逻辑
–   Timeout : 当测试的执行超过特定时间后导致测试失败
–   Verifier : 假如对象状态不正确时让测试失败
四、EasyMock测试

协同模块尚未开发完成
被测试模块需要和协同模块进行交互
Mock 对象能够模拟协同模块行为
手动Mock 带来额外的编码量
EasyMock录制、回放、检查
四、EasyMock测试
EasyMock录制、回放、检查测试流程
四、EasyMock测试
EasyMock测试样例
public void testSalesOrder() {
IMocksControl control = EasyMock.createControl();
ResultSet mockResultSet = control.createMock(ResultSet.class);
mockResultSet.next();
expectLastCall().andReturn(true).times(1);
expectLastCall().andReturn(false).times(1);
mockResultSet.getString(1);
expectLastCall().andReturn("DEMO_ORDER_001").times(1);
expectLastCall().andReturn("DEMO_ORDER_002").times(1);
control.replay();
//do test
control.verify();}
Q&A
         雷腾 L.T
Email:leiteng@taobao.com

Contenu connexe

Tendances

Test-Driven Development for TYPO3
Test-Driven Development for TYPO3Test-Driven Development for TYPO3
Test-Driven Development for TYPO3
Oliver Klee
 
Test-Driven Development for TYPO3 @ T3CON12DE
Test-Driven Development for TYPO3 @ T3CON12DETest-Driven Development for TYPO3 @ T3CON12DE
Test-Driven Development for TYPO3 @ T3CON12DE
Oliver Klee
 
Test-driven Development for TYPO3
Test-driven Development for TYPO3Test-driven Development for TYPO3
Test-driven Development for TYPO3
Oliver Klee
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
Unit testing for the TYPO3 4.x core (T3DD10)
Unit testing for the TYPO3 4.x core (T3DD10)Unit testing for the TYPO3 4.x core (T3DD10)
Unit testing for the TYPO3 4.x core (T3DD10)
Oliver Klee
 

Tendances (20)

Test-Driven Development for TYPO3
Test-Driven Development for TYPO3Test-Driven Development for TYPO3
Test-Driven Development for TYPO3
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Test-Driven Development for TYPO3 @ T3CON12DE
Test-Driven Development for TYPO3 @ T3CON12DETest-Driven Development for TYPO3 @ T3CON12DE
Test-Driven Development for TYPO3 @ T3CON12DE
 
Test-driven Development for TYPO3
Test-driven Development for TYPO3Test-driven Development for TYPO3
Test-driven Development for TYPO3
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Unit testing for the TYPO3 4.x core (T3DD10)
Unit testing for the TYPO3 4.x core (T3DD10)Unit testing for the TYPO3 4.x core (T3DD10)
Unit testing for the TYPO3 4.x core (T3DD10)
 
Power mock
Power mockPower mock
Power mock
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java review: try catch
Java review: try catchJava review: try catch
Java review: try catch
 

En vedette (14)

The role of the teacher
The role of the teacherThe role of the teacher
The role of the teacher
 
Ucberkeley educational services_for_foster_youth
Ucberkeley educational services_for_foster_youthUcberkeley educational services_for_foster_youth
Ucberkeley educational services_for_foster_youth
 
Effective parent teacher
Effective parent teacherEffective parent teacher
Effective parent teacher
 
Rights Training Powerpoint
Rights  Training  PowerpointRights  Training  Powerpoint
Rights Training Powerpoint
 
Adv
AdvAdv
Adv
 
Teachers induction program
Teachers induction programTeachers induction program
Teachers induction program
 
The Various Roles of the Teacher
The Various Roles of the TeacherThe Various Roles of the Teacher
The Various Roles of the Teacher
 
Parent Teacher Partnership
Parent  Teacher PartnershipParent  Teacher Partnership
Parent Teacher Partnership
 
The Roles of a Teacher
The Roles of a TeacherThe Roles of a Teacher
The Roles of a Teacher
 
Module 5 school and community partnership
Module 5 school and community partnershipModule 5 school and community partnership
Module 5 school and community partnership
 
Roles of the teacher inside the classroom
Roles of the teacher inside the classroomRoles of the teacher inside the classroom
Roles of the teacher inside the classroom
 
ROLES OF TEACHERS
ROLES OF TEACHERSROLES OF TEACHERS
ROLES OF TEACHERS
 
Duties and responsibilities of a teacher
Duties and responsibilities of a teacherDuties and responsibilities of a teacher
Duties and responsibilities of a teacher
 
The teacher role and expectation
The teacher role and expectationThe teacher role and expectation
The teacher role and expectation
 

Similaire à JUnit源码分析

Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 

Similaire à JUnit源码分析 (20)

Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
TestNG
TestNGTestNG
TestNG
 
Technical meeting automated testing with vs2010
Technical meeting automated testing with vs2010Technical meeting automated testing with vs2010
Technical meeting automated testing with vs2010
 
Automation Testing Syllabus - Checklist
Automation Testing Syllabus - ChecklistAutomation Testing Syllabus - Checklist
Automation Testing Syllabus - Checklist
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Scala test
Scala testScala test
Scala test
 
Scala test
Scala testScala test
Scala test
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Maf3 - Part 1
Maf3 - Part 1Maf3 - Part 1
Maf3 - Part 1
 
Testing Django Applications
Testing Django ApplicationsTesting Django Applications
Testing Django Applications
 
API Performance Testing
API Performance TestingAPI Performance Testing
API Performance Testing
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 

Dernier

Dernier (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

JUnit源码分析