SlideShare a Scribd company logo
Effective Unit Test
Style Guide
- Jacky Lai
Table of Contents
1. What NOT to Unit Test
2. What to Unit Test then?
3. Criteria of a Good Unit Test
4. Unit Test Method Name
5. Unit Test Content
1. What NOT to Unit Test
u Before we delve into this style guide, we need to know what not to unit test.
"What not to test" is very important because any unnecessary test code in our
code base will create noise in our code base and increase our maintenance
cost.
u We can roughly divide all classes into 3 types: Entity, Control, Boundary
(http://www.cs.sjsu.edu/~pearce/modules/patterns/enterprise/ecb/ecb.ht
m).
u Entity - Data Container, e.g. DTO
u Boundary - Classes that communicate directly to external services, via network
connection, e.g. REST API, DAO, HttpClient, MessageHandler etc.
u Control - Classes that normally make decision.
Fig 1. Unit test and CBE
u Out of these 3 types of classes, in general, we don't need to write unit test
for:
u Entity – Since it contains only logic-less getters and setters method, there is no
value in testing all these getters / setters.
u Boundary - We need to cover boundary class with integration test, we just don't
need to write unit test for it. If you need to unit test it just because your boundary
class (handler class etc.) contains processing logic, you probably need to delegate
the processing logic into control class.
u There are some exceptions for the rules above. We may need to write unit
test for the following conditions:
u If the Entity class has validation rules. We need unit test validation logic.
u If the Boundary class has event broadcasting capability, as the example below. We
need to verify that new event is being broadcasted.
u publishEvent(new DataUpdatedEvent()); // example
2. What to Unit Test then?
u Control - It makes decision, it has processing logic inside. It's like our brain.
We need to make sure it's processing logic is correct and yield correct output.
3. Criteria of a Good Unit Test
u A good unit test satisfy 3 criteria:
1. Test a single feature in isolation.
2. Easy to understand by other engineers.
3. Help to identify issue effectively during test failure.
u Most unit tests satisfy #1. This styling guide will focus on #2 and #3.
4. Unit Test Method Name
u A test method name should consist of
<targetMethod>_<expectedResult>_<initialState>.
u Example:
@Test
public void computeTotalWidth_shouldReturnTotalWidth_givenPositiveNumbers() {…}
@Test
public void computeTotalWidth_shouldThrowException_givenNegativeNumbers() {…}
@Test
public void generate_shouldGenerateXYZ_forABConly() {…}
method_expectedResult_initialState()
naming style
testTargetMethod()
naming style
u Engineers can fix test failures with confidence if they understand what is the
correct behavior of the code.
u Code reviewers on the other hand can easily spot on any missing test cases.
u As a side benefit, this naming style help programmer to keep his/her mind
flowing when he/she is writing the test. For example, when he/she is stuck at
what to test, he/she can think out loud saying "this method should return
something when xyz is given”.
u In contrast, using names like “testComputeTotalWidth()” gives less context
about it’s intent.
5. Unit Test Content
1. We use AAA style where every unit test has 3 sections - Arrange, Act,
Assert:
u Arrange - Set up initial state (this will normally occupy more than 80% of your test
code)
u Act - Perform action
u Assert - Verify the result
2. It is important to clearly identify these three sections with
comments, allowing us to quickly jump between the “arrange", "act" and
"assert" sections.
3. We use SUT (System Under Test) to denote target instance.
u This helps us identify the target instance from a swarm of mock objects.
✔️Do this
@Test
public void testSearch_shouldReturnTargetIndex_ifFoundInInputValues() {
// 1. arrange
List<Integer> sortedNumbers = Arrays.asList(1, 2, 3);
int targetValue = 2;
BinarySearcher sut = new BinarySearcher();
// 2. assert
int targetIndex = sut.search(sortedNumbers, targetValue);
// 3. assert
Assertions.assertThat(targetIndex).isEqualTo(1);
}
✔️ AAA Pattern
@Test
public void test() {
// 1. arrange
final int TARGET_VALUE = 2;
Node node1 = new Node(8);
Node node2 = new Node(4);
Node node3 = new Node(5);
Node node4 = new Node(3);
Node node5 = new Node(9);
Node node6 = new Node(2);
node1.addChildNode(node2);
node1.addChildNode(node3);
node3.addChildNode(node4);
node1.addChildNode(node5);
node5.addChildNode(node6);
BFSearcher sut = new BFSearcher();
// 2. act
Node node = sut.search(node1, TARGET_VALUE);
// 3. assert
Assertions.assertThat(node).isEqualTo(node6);
}
❌ Without AAA Patter
@Test
public void test() {
final int TARGET_VALUE = 2;
Node node1 = new Node(8);
Node node2 = new Node(4);
Node node3 = new Node(5);
Node node4 = new Node(3);
Node node5 = new Node(9);
Node node6 = new Node(2);
node1.addChildNode(node2);
node1.addChildNode(node3);
node3.addChildNode(node4);
node1.addChildNode(node5);
node5.addChildNode(node6);
BFSearcher sut = new BFSearcher();
Node node = sut.search(node1, TARGET_VALUE);
Assertions.assertThat(node).isEqualTo(node6);
}
u AAA Pattern:
u The Arrange section of AAA takes up over 80% of the code in our test, but we can
still easily jump to Act sections by looking at the comments.
u ”sut" naming makes the test target stand out.
u Without AAA Pattern
u We have to start reading the code from beginning.
u Test target buried in the sea of mock objects.
1. A test should be self-contained. We want to understand the code fast. We
don't want to jump around different methods to understand the test flow.
u It is preferred that you do not follow the DRY (Don't Repeat Yourself) principle.
Striving for code reuse will lead to tightly coupled and inflexible test, which
discourages refactoring.
❌ Don’t do this
// Do not do this. Code reader has to scroll
// up and down to understand the whole test logic.
@Test
public void testXYZ(){
// 1. arrange
setup1();
setup2();
doSomething();
Target sut = new Target();
// 2. act
actualResult = sut.doSomething();
// 3. assert
Asserts.assertThat(222, actualResult);
}
private void setup1(){ … }
private void setup2(){ … }
private void doSomething(){ … }
The End.
Ad

More Related Content

What's hot (20)

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
mcollison
 
3 j unit
3 j unit3 j unit
3 j unit
kishoregali
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
Devvrat Shukla
 
Junit
JunitJunit
Junit
FAROOK Samath
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
testng
testngtestng
testng
harithakannan
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
Abhishek Yadav
 
TestNG
TestNGTestNG
TestNG
Prabhanshu Saraswat
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
java8certificationquestions
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
Levon Apreyan
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
Srikrishna k
 
Testers guide to unit testing
Testers guide to unit testingTesters guide to unit testing
Testers guide to unit testing
Craig Risi
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
Gousalya Ramachandran
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
It Academy
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
J Unit
J UnitJ Unit
J Unit
guest333f37c3
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
Bethmi Gunasekara
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
Andrey Oleynik
 
Junit
JunitJunit
Junit
Abdullah Shahneel
 

Viewers also liked (18)

Momin Resume V4
Momin Resume V4Momin Resume V4
Momin Resume V4
Mujatabamahadi Momin
 
Report-FrenchVillEdge
Report-FrenchVillEdgeReport-FrenchVillEdge
Report-FrenchVillEdge
Kathryn Drumheller
 
Current Resume, 2016
Current Resume, 2016Current Resume, 2016
Current Resume, 2016
Lee Hunter
 
bgsu1349900740
bgsu1349900740bgsu1349900740
bgsu1349900740
Arisca Droog
 
understand challenges for infrastructure
understand challenges for infrastructureunderstand challenges for infrastructure
understand challenges for infrastructure
christopher nyabulegesi
 
Curriculum Vitae - Sharon G Naidoo June 2016
Curriculum Vitae - Sharon G Naidoo June 2016Curriculum Vitae - Sharon G Naidoo June 2016
Curriculum Vitae - Sharon G Naidoo June 2016
Sharon Naidoo
 
Front End development workflow
Front End development workflowFront End development workflow
Front End development workflow
Matteo Scandolo
 
Writing Tests Effectively
Writing Tests EffectivelyWriting Tests Effectively
Writing Tests Effectively
Paul Boocock
 
PostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit TestPostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit Test
Andrea Adami
 
Unit Test Lab - Why Write Unit Tests?
Unit Test Lab - Why Write Unit Tests?Unit Test Lab - Why Write Unit Tests?
Unit Test Lab - Why Write Unit Tests?
Danny van Kasteel
 
How to write Testable Javascript
How to write Testable JavascriptHow to write Testable Javascript
How to write Testable Javascript
ColdFusionConference
 
Web based automation testing on Node.js environment
Web based automation testing on Node.js environmentWeb based automation testing on Node.js environment
Web based automation testing on Node.js environment
Yu-Lin Huang
 
Selenium Automation Like You’ve Never Seen!
Selenium Automation Like You’ve Never Seen!Selenium Automation Like You’ve Never Seen!
Selenium Automation Like You’ve Never Seen!
Perfecto by Perforce
 
Continuous Delivery With Selenium Grid And Docker
Continuous Delivery With Selenium Grid And DockerContinuous Delivery With Selenium Grid And Docker
Continuous Delivery With Selenium Grid And Docker
Barbara Gonzalez
 
Selenium
SeleniumSelenium
Selenium
Sun Technlogies
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Edureka!
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
Pavan Kumar
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 
Current Resume, 2016
Current Resume, 2016Current Resume, 2016
Current Resume, 2016
Lee Hunter
 
understand challenges for infrastructure
understand challenges for infrastructureunderstand challenges for infrastructure
understand challenges for infrastructure
christopher nyabulegesi
 
Curriculum Vitae - Sharon G Naidoo June 2016
Curriculum Vitae - Sharon G Naidoo June 2016Curriculum Vitae - Sharon G Naidoo June 2016
Curriculum Vitae - Sharon G Naidoo June 2016
Sharon Naidoo
 
Front End development workflow
Front End development workflowFront End development workflow
Front End development workflow
Matteo Scandolo
 
Writing Tests Effectively
Writing Tests EffectivelyWriting Tests Effectively
Writing Tests Effectively
Paul Boocock
 
PostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit TestPostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit Test
Andrea Adami
 
Unit Test Lab - Why Write Unit Tests?
Unit Test Lab - Why Write Unit Tests?Unit Test Lab - Why Write Unit Tests?
Unit Test Lab - Why Write Unit Tests?
Danny van Kasteel
 
Web based automation testing on Node.js environment
Web based automation testing on Node.js environmentWeb based automation testing on Node.js environment
Web based automation testing on Node.js environment
Yu-Lin Huang
 
Selenium Automation Like You’ve Never Seen!
Selenium Automation Like You’ve Never Seen!Selenium Automation Like You’ve Never Seen!
Selenium Automation Like You’ve Never Seen!
Perfecto by Perforce
 
Continuous Delivery With Selenium Grid And Docker
Continuous Delivery With Selenium Grid And DockerContinuous Delivery With Selenium Grid And Docker
Continuous Delivery With Selenium Grid And Docker
Barbara Gonzalez
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Edureka!
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
Simon Guest
 
Ad

Similar to Effective Unit Test Style Guide (20)

Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
SumitKumar918321
 
Unit testing
Unit testingUnit testing
Unit testing
Pooya Sagharchiha
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
Aktuğ Urun
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
Knoldus Inc.
 
Junit
JunitJunit
Junit
Vivek Kulkarni
 
Testing And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionTesting And Mxunit In ColdFusion
Testing And Mxunit In ColdFusion
Denard Springle IV
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
Priya Sharma
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
Testing
TestingTesting
Testing
nazeer pasha
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
Amila Paranawithana
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
Marcelo Busico
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
Pokpitch Patcharadamrongkul
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
Damian Sromek
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
Derek Smith
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
pallavikhandekar212
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
Sanjib Dhar
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
Isham Rashik
 
Ad

More from Jacky Lai (6)

Searching and reporting with splunk 6.x e learning
Searching and reporting with splunk 6.x   e learningSearching and reporting with splunk 6.x   e learning
Searching and reporting with splunk 6.x e learning
Jacky Lai
 
Using splunk 6.4 e learning
Using splunk 6.4   e learningUsing splunk 6.4   e learning
Using splunk 6.4 e learning
Jacky Lai
 
Apache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjavaApache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjava
Jacky Lai
 
0536 lai
0536 lai0536 lai
0536 lai
Jacky Lai
 
Cache invalidation
Cache invalidationCache invalidation
Cache invalidation
Jacky Lai
 
Simplify Complex Query with CQRS
Simplify Complex Query with CQRSSimplify Complex Query with CQRS
Simplify Complex Query with CQRS
Jacky Lai
 
Searching and reporting with splunk 6.x e learning
Searching and reporting with splunk 6.x   e learningSearching and reporting with splunk 6.x   e learning
Searching and reporting with splunk 6.x e learning
Jacky Lai
 
Using splunk 6.4 e learning
Using splunk 6.4   e learningUsing splunk 6.4   e learning
Using splunk 6.4 e learning
Jacky Lai
 
Apache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjavaApache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjava
Jacky Lai
 
Cache invalidation
Cache invalidationCache invalidation
Cache invalidation
Jacky Lai
 
Simplify Complex Query with CQRS
Simplify Complex Query with CQRSSimplify Complex Query with CQRS
Simplify Complex Query with CQRS
Jacky Lai
 

Recently uploaded (20)

Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 

Effective Unit Test Style Guide

  • 1. Effective Unit Test Style Guide - Jacky Lai
  • 2. Table of Contents 1. What NOT to Unit Test 2. What to Unit Test then? 3. Criteria of a Good Unit Test 4. Unit Test Method Name 5. Unit Test Content
  • 3. 1. What NOT to Unit Test u Before we delve into this style guide, we need to know what not to unit test. "What not to test" is very important because any unnecessary test code in our code base will create noise in our code base and increase our maintenance cost.
  • 4. u We can roughly divide all classes into 3 types: Entity, Control, Boundary (http://www.cs.sjsu.edu/~pearce/modules/patterns/enterprise/ecb/ecb.ht m). u Entity - Data Container, e.g. DTO u Boundary - Classes that communicate directly to external services, via network connection, e.g. REST API, DAO, HttpClient, MessageHandler etc. u Control - Classes that normally make decision.
  • 5. Fig 1. Unit test and CBE
  • 6. u Out of these 3 types of classes, in general, we don't need to write unit test for: u Entity – Since it contains only logic-less getters and setters method, there is no value in testing all these getters / setters. u Boundary - We need to cover boundary class with integration test, we just don't need to write unit test for it. If you need to unit test it just because your boundary class (handler class etc.) contains processing logic, you probably need to delegate the processing logic into control class.
  • 7. u There are some exceptions for the rules above. We may need to write unit test for the following conditions: u If the Entity class has validation rules. We need unit test validation logic. u If the Boundary class has event broadcasting capability, as the example below. We need to verify that new event is being broadcasted. u publishEvent(new DataUpdatedEvent()); // example
  • 8. 2. What to Unit Test then? u Control - It makes decision, it has processing logic inside. It's like our brain. We need to make sure it's processing logic is correct and yield correct output.
  • 9. 3. Criteria of a Good Unit Test u A good unit test satisfy 3 criteria: 1. Test a single feature in isolation. 2. Easy to understand by other engineers. 3. Help to identify issue effectively during test failure. u Most unit tests satisfy #1. This styling guide will focus on #2 and #3.
  • 10. 4. Unit Test Method Name u A test method name should consist of <targetMethod>_<expectedResult>_<initialState>. u Example: @Test public void computeTotalWidth_shouldReturnTotalWidth_givenPositiveNumbers() {…} @Test public void computeTotalWidth_shouldThrowException_givenNegativeNumbers() {…} @Test public void generate_shouldGenerateXYZ_forABConly() {…}
  • 12. u Engineers can fix test failures with confidence if they understand what is the correct behavior of the code. u Code reviewers on the other hand can easily spot on any missing test cases. u As a side benefit, this naming style help programmer to keep his/her mind flowing when he/she is writing the test. For example, when he/she is stuck at what to test, he/she can think out loud saying "this method should return something when xyz is given”. u In contrast, using names like “testComputeTotalWidth()” gives less context about it’s intent.
  • 13. 5. Unit Test Content 1. We use AAA style where every unit test has 3 sections - Arrange, Act, Assert: u Arrange - Set up initial state (this will normally occupy more than 80% of your test code) u Act - Perform action u Assert - Verify the result 2. It is important to clearly identify these three sections with comments, allowing us to quickly jump between the “arrange", "act" and "assert" sections. 3. We use SUT (System Under Test) to denote target instance. u This helps us identify the target instance from a swarm of mock objects.
  • 14. ✔️Do this @Test public void testSearch_shouldReturnTargetIndex_ifFoundInInputValues() { // 1. arrange List<Integer> sortedNumbers = Arrays.asList(1, 2, 3); int targetValue = 2; BinarySearcher sut = new BinarySearcher(); // 2. assert int targetIndex = sut.search(sortedNumbers, targetValue); // 3. assert Assertions.assertThat(targetIndex).isEqualTo(1); }
  • 15. ✔️ AAA Pattern @Test public void test() { // 1. arrange final int TARGET_VALUE = 2; Node node1 = new Node(8); Node node2 = new Node(4); Node node3 = new Node(5); Node node4 = new Node(3); Node node5 = new Node(9); Node node6 = new Node(2); node1.addChildNode(node2); node1.addChildNode(node3); node3.addChildNode(node4); node1.addChildNode(node5); node5.addChildNode(node6); BFSearcher sut = new BFSearcher(); // 2. act Node node = sut.search(node1, TARGET_VALUE); // 3. assert Assertions.assertThat(node).isEqualTo(node6); } ❌ Without AAA Patter @Test public void test() { final int TARGET_VALUE = 2; Node node1 = new Node(8); Node node2 = new Node(4); Node node3 = new Node(5); Node node4 = new Node(3); Node node5 = new Node(9); Node node6 = new Node(2); node1.addChildNode(node2); node1.addChildNode(node3); node3.addChildNode(node4); node1.addChildNode(node5); node5.addChildNode(node6); BFSearcher sut = new BFSearcher(); Node node = sut.search(node1, TARGET_VALUE); Assertions.assertThat(node).isEqualTo(node6); }
  • 16. u AAA Pattern: u The Arrange section of AAA takes up over 80% of the code in our test, but we can still easily jump to Act sections by looking at the comments. u ”sut" naming makes the test target stand out. u Without AAA Pattern u We have to start reading the code from beginning. u Test target buried in the sea of mock objects.
  • 17. 1. A test should be self-contained. We want to understand the code fast. We don't want to jump around different methods to understand the test flow. u It is preferred that you do not follow the DRY (Don't Repeat Yourself) principle. Striving for code reuse will lead to tightly coupled and inflexible test, which discourages refactoring.
  • 18. ❌ Don’t do this // Do not do this. Code reader has to scroll // up and down to understand the whole test logic. @Test public void testXYZ(){ // 1. arrange setup1(); setup2(); doSomething(); Target sut = new Target(); // 2. act actualResult = sut.doSomething(); // 3. assert Asserts.assertThat(222, actualResult); } private void setup1(){ … } private void setup2(){ … } private void doSomething(){ … }