SlideShare a Scribd company logo
1 of 19
Download to read offline
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.

More Related Content

What's hot

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 

What's hot (20)

Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
3 j unit
3 j unit3 j unit
3 j unit
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Junit
JunitJunit
Junit
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
testng
testngtestng
testng
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 
TestNG
TestNGTestNG
TestNG
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Testers guide to unit testing
Testers guide to unit testingTesters guide to unit testing
Testers guide to unit testing
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
J Unit
J UnitJ Unit
J Unit
 
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
 
TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
Junit
JunitJunit
Junit
 

Viewers also liked

Current Resume, 2016
Current Resume, 2016Current Resume, 2016
Current Resume, 2016
Lee Hunter
 
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
 

Viewers also liked (18)

Momin Resume V4
Momin Resume V4Momin Resume V4
Momin Resume V4
 
Report-FrenchVillEdge
Report-FrenchVillEdgeReport-FrenchVillEdge
Report-FrenchVillEdge
 
Current Resume, 2016
Current Resume, 2016Current Resume, 2016
Current Resume, 2016
 
bgsu1349900740
bgsu1349900740bgsu1349900740
bgsu1349900740
 
understand challenges for infrastructure
understand challenges for infrastructureunderstand challenges for infrastructure
understand challenges for infrastructure
 
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
 
Front End development workflow
Front End development workflowFront End development workflow
Front End development workflow
 
Writing Tests Effectively
Writing Tests EffectivelyWriting Tests Effectively
Writing Tests Effectively
 
PostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit TestPostgreSQL Day italy 2016 Unit Test
PostgreSQL Day italy 2016 Unit Test
 
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?
 
How to write Testable Javascript
How to write Testable JavascriptHow to write Testable Javascript
How to write Testable Javascript
 
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
 
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!
 
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
 
Selenium
SeleniumSelenium
Selenium
 
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...
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
Automated Web Testing using JavaScript
Automated Web Testing using JavaScriptAutomated Web Testing using JavaScript
Automated Web Testing using JavaScript
 

Similar to Effective Unit Test Style Guide

J unit presentation
J unit presentationJ unit presentation
J unit presentation
Priya Sharma
 

Similar to Effective Unit Test Style Guide (20)

Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Unit testing
Unit testingUnit testing
Unit testing
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
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
 
Junit
JunitJunit
Junit
 
Testing And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionTesting And Mxunit In ColdFusion
Testing And Mxunit In ColdFusion
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Testing
TestingTesting
Testing
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
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
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 

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
 
Using splunk 6.4 e learning
Using splunk 6.4   e learningUsing splunk 6.4   e learning
Using splunk 6.4 e learning
 
Apache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjavaApache hadoop2xdeveloperjava
Apache hadoop2xdeveloperjava
 
0536 lai
0536 lai0536 lai
0536 lai
 
Cache invalidation
Cache invalidationCache invalidation
Cache invalidation
 
Simplify Complex Query with CQRS
Simplify Complex Query with CQRSSimplify Complex Query with CQRS
Simplify Complex Query with CQRS
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

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(){ … }