SlideShare a Scribd company logo
1 of 21
Download to read offline
FAQ ‐ why does my code throw a
null pointer exception
A: ‐ common reason #1 Variable Redeclaration
Alan Richardson
www.JavaForTesters.com
twitter:  @ eviltester
@eviltester 1
Does this happen to you?
@eviltester 2
FAQ ‐ why does my code throw a null
pointer exception ‐ common reason #1
Redeclaration
Using  @BeforeClass or  @Before can setup data for use in tests
Any 'variables' we instantiate need to be 'fields' rather than
variables
We want to instantiate them in the setup method rather than
redeclare them
@eviltester 3
Example of the Problem
I know I will use an  Adder in my test so I create it as a field:
public class WhyCodeThrowsNullPointerExceptionTest {
    Adder adder;
I don't want to re‐instantiate it each time so I make an
 @BeforeClass method to instantiate it:
@BeforeClass
public static void setupAdder(){
    Adder adder = new Adder();
}
Warning: Error in the above code
@eviltester 4
Semantic Error
I just made a Semantic coding error. This won't be caught by a
compiler, but it will cause my  @Test to fail with a Null Pointer
Exception.
@Test
public void canAddTwoPlusTwo(){
    Assert.assertEquals(4,adder.add(2,2));
}
The above test will fail with a  NullPointerException 
java.lang.NullPointerException
    at com.javafortesters.faq.nullpointerexception.
WhyCodeThrowsNullPointerExceptionTest.canAddTwoPlusTwo
(WhyCodeThrowsNullPointerExceptionTest.java:29)
...
@eviltester 5
What Went Wrong?
In the setup method I really wanted to assign a value to the field,
instead I created an new variable with the same name.
Adder adder = new Adder();
I really wanted:
adder = new Adder();
and to support that, the field really needs to be declared as  static 
static Adder adder;
@eviltester 6
How to avoid? IDE Syntax Highlighting
If I was editing this in an IDE, then I would see that the  adder in
the following line is never used :
Adder adder = new Adder();
It will be coloured grey or some other IDE indication.
@eviltester 7
 static methods need  static fields
In order for the field to be used in the static method it needed to
be static.
If I had used it in the setup method:
Adder adder;
@BeforeClass
public static void setupAdder(){
    adder = new Adder();
}
Then I would have seen a syntax error in the code because:
 Non‐static field 'adder' cannot be referenced from a
static context 
@eviltester 8
IDE will show this
@eviltester 9
Refactor to fields
Had I written the  @Test code first then I would have started with:
@Test
public void canAddTwoPlusTwo(){     
    Adder adder = new Adder();
    Assert.assertEquals(4,adder.add(2,2));
}
I can refactor this to avoid errors.
@eviltester 10
Automated refactoring of Extract to field
where initialized as 'field declaration
Might have generated the following code:
private final Adder adder = new Adder();
this removes the need for an  @BeforeClass or  @Before 
construct entirely
@eviltester 11
Automated refactoring of Extract to field
where initialized in constructor
private final Adder adder;
public WhyCodeThrowsNullPointerExceptionTest() {
    adder = new Adder();
}
this removes the need for an  @BeforeClass or  @Before 
construct entirely
@eviltester 12
Automatically Refactor prior to using
 @Before... 
I might still want to use an  @BeforeClass or  @Before 
To make the code readable
I could do that
but I don't think I would have declared a new variable after the
refactorings because I have a working code example that I'm
moving.
@eviltester 13
In General
Try to write one test at a time so that if you have a problem it is
easier to identify where the problem is
Try to write working isolated tests and then refactor to a more
general solution when you need it ‐ that way, you know it was
working, so you just have to work backwards to find out what
went wrong
Try to use automated IDE refactoring rather than move code
around manually
Use the IDE syntax highlighting to help spot any issues
@eviltester 14
Source Code
If you want to experiment with code that recreates this
problem then have a look at
WhyCodeThrowsNullPointerExceptionTest.java in
javaScratchpad
@eviltester 15
"Java For Testers" A Book for
learning how to code Java
All code written as Test methods
you learn TDD
your learn JUnit
you focus on code
you are not distracted by 'creating an application'
Affordably priced so that everyone can learn ﴾Free Download of
70+ Sample PDF﴿
@eviltester 16
BIO ‐ Alan Richardson
Alan Richardson has more than twenty years of professional IT
experience, working as a programmer and at every level of the
testing hierarchy from tester through head of testing. He has
performed keynote speeches and tutorials at conferences
worldwide. Author of multiple books on testing and automating.
Alan also has created online training courses to help people learn
Technical Web Testing and Selenium WebDriver with Java. He works
as an independent consultant, helping companies improve their use
of automation, agile, and exploratory technical testing.
@eviltester 17
Alan Richardson ﴾www﴿
www.compendiumdev.co.uk
www.eviltester.com
www.seleniumsimplified.com
www.javafortesters.com
uk.linkedin.com/in/eviltester
testerhq.com ‐ Aggregated Feed
@eviltester 18
Follow
Linkedin ‐ uk.linkedin.com/in/eviltester
Twitter ‐ twitter.com/eviltester
Instagram ‐ instagram.com/eviltester
Facebook ‐ facebook.com/eviltester
Youtube ‐ youtube.com/user/EviltesterVideos
Pinterest ‐ uk.pinterest.com/eviltester
Github ‐ github.com/eviltester
Slideshare ‐ slideshare.net/eviltester
@eviltester 19
Books Written By Alan Richardson
Java For Testers
Dear Evil Tester
Automating and Testing a REST API
Selenium Simplified
@eviltester 20
Online Training Courses By Alan
Richardson
Selenium Webdriver With Java
Technical Web Testing 101
Evil Tester Talks: Technical Testing
Case Study: Java Desktop Application Technical Training
@eviltester 21

More Related Content

What's hot

QA Fest 2017. Jeremias Rößler. Applying AI to testing
QA Fest 2017. Jeremias Rößler. Applying AI to testingQA Fest 2017. Jeremias Rößler. Applying AI to testing
QA Fest 2017. Jeremias Rößler. Applying AI to testingQAFest
 
Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Alan Richardson
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeAmar Shah
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsWebStackAcademy
 
Resource Leaks in Java
Resource Leaks in JavaResource Leaks in Java
Resource Leaks in JavaCoverity
 
Concurrency Errors in Java
Concurrency Errors in JavaConcurrency Errors in Java
Concurrency Errors in JavaCoverity
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Unit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkUnit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkLong Weekend LLC
 
Technology Based Testing
Technology Based TestingTechnology Based Testing
Technology Based TestingAlan Richardson
 
Evil testers guide to technical testing
Evil testers guide to technical testingEvil testers guide to technical testing
Evil testers guide to technical testingAlan Richardson
 
Add More Security To Your Testing and Automating - Saucecon 2021
Add More Security To Your Testing and Automating - Saucecon 2021Add More Security To Your Testing and Automating - Saucecon 2021
Add More Security To Your Testing and Automating - Saucecon 2021Alan Richardson
 
Effective Software Testing for Modern Software Development
Effective Software Testing for Modern Software DevelopmentEffective Software Testing for Modern Software Development
Effective Software Testing for Modern Software DevelopmentAlan Richardson
 
How To Test With Agility
How To Test With AgilityHow To Test With Agility
How To Test With AgilityAlan Richardson
 

What's hot (20)

QA Fest 2017. Jeremias Rößler. Applying AI to testing
QA Fest 2017. Jeremias Rößler. Applying AI to testingQA Fest 2017. Jeremias Rößler. Applying AI to testing
QA Fest 2017. Jeremias Rößler. Applying AI to testing
 
Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020
 
Devfest 2019-slides
Devfest 2019-slidesDevfest 2019-slides
Devfest 2019-slides
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and AssertionsCore Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
 
Resource Leaks in Java
Resource Leaks in JavaResource Leaks in Java
Resource Leaks in Java
 
Concurrency Errors in Java
Concurrency Errors in JavaConcurrency Errors in Java
Concurrency Errors in Java
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Unit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava TalkUnit Testing in iOS - Ninjava Talk
Unit Testing in iOS - Ninjava Talk
 
Technology Based Testing
Technology Based TestingTechnology Based Testing
Technology Based Testing
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
Evil testers guide to technical testing
Evil testers guide to technical testingEvil testers guide to technical testing
Evil testers guide to technical testing
 
Add More Security To Your Testing and Automating - Saucecon 2021
Add More Security To Your Testing and Automating - Saucecon 2021Add More Security To Your Testing and Automating - Saucecon 2021
Add More Security To Your Testing and Automating - Saucecon 2021
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
Effective Software Testing for Modern Software Development
Effective Software Testing for Modern Software DevelopmentEffective Software Testing for Modern Software Development
Effective Software Testing for Modern Software Development
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
How To Test With Agility
How To Test With AgilityHow To Test With Agility
How To Test With Agility
 

Similar to FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration

Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPressHarshad Mane
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Code igniter unittest-part1
Code igniter unittest-part1Code igniter unittest-part1
Code igniter unittest-part1Albert Rosa
 
The Testing Planet Issue 2
The Testing Planet Issue 2The Testing Planet Issue 2
The Testing Planet Issue 2Rosie Sherry
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
How to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check TuneupHow to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check TuneupBala Subra
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it rightDmytro Patserkovskyi
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
How to apply AI to Testing
How to apply AI to TestingHow to apply AI to Testing
How to apply AI to TestingSAP SE
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example usingIevgenii Katsan
 

Similar to FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration (20)

J Unit
J UnitJ Unit
J Unit
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPress
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Python and test
Python and testPython and test
Python and test
 
Code igniter unittest-part1
Code igniter unittest-part1Code igniter unittest-part1
Code igniter unittest-part1
 
The Testing Planet Issue 2
The Testing Planet Issue 2The Testing Planet Issue 2
The Testing Planet Issue 2
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
How to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check TuneupHow to ace your .NET technical interview :: .Net Technical Check Tuneup
How to ace your .NET technical interview :: .Net Technical Check Tuneup
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it right
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
How to apply AI to Testing
How to apply AI to TestingHow to apply AI to Testing
How to apply AI to Testing
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 

More from Alan Richardson

Open source tools - Test Management Summit - 2009
Open source tools - Test Management Summit - 2009Open source tools - Test Management Summit - 2009
Open source tools - Test Management Summit - 2009Alan Richardson
 
The Future of Testing Webinar
The Future of Testing WebinarThe Future of Testing Webinar
The Future of Testing WebinarAlan Richardson
 
Secrets and Mysteries of Automated Execution Keynote slides
Secrets and Mysteries of Automated Execution Keynote slidesSecrets and Mysteries of Automated Execution Keynote slides
Secrets and Mysteries of Automated Execution Keynote slidesAlan Richardson
 
Automating Pragmatically - Testival 20190604
Automating Pragmatically - Testival 20190604Automating Pragmatically - Testival 20190604
Automating Pragmatically - Testival 20190604Alan Richardson
 
Joy of Coding Conference 2019 slides - Alan Richardson
Joy of Coding Conference 2019 slides - Alan RichardsonJoy of Coding Conference 2019 slides - Alan Richardson
Joy of Coding Conference 2019 slides - Alan RichardsonAlan Richardson
 
About Consultant Alan Richardson Compendium Developments Evil Tester
About Consultant Alan Richardson Compendium Developments Evil TesterAbout Consultant Alan Richardson Compendium Developments Evil Tester
About Consultant Alan Richardson Compendium Developments Evil TesterAlan Richardson
 
Automating and Testing a REST API
Automating and Testing a REST APIAutomating and Testing a REST API
Automating and Testing a REST APIAlan Richardson
 
Technical and Testing Challenges: Using the "Protect The Square" Game
Technical and Testing Challenges: Using the "Protect The Square" GameTechnical and Testing Challenges: Using the "Protect The Square" Game
Technical and Testing Challenges: Using the "Protect The Square" GameAlan Richardson
 
TDD - Test Driven Development - Java JUnit FizzBuzz
TDD - Test Driven Development - Java JUnit FizzBuzzTDD - Test Driven Development - Java JUnit FizzBuzz
TDD - Test Driven Development - Java JUnit FizzBuzzAlan Richardson
 
If you want to automate, you learn to code
If you want to automate, you learn to codeIf you want to automate, you learn to code
If you want to automate, you learn to codeAlan Richardson
 
Your Automated Execution Does Not Have to be Flaky
Your Automated Execution Does Not Have to be FlakyYour Automated Execution Does Not Have to be Flaky
Your Automated Execution Does Not Have to be FlakyAlan Richardson
 
What is Testability vs Automatability? How to improve your Software Testing.
What is Testability vs Automatability? How to improve your Software Testing.What is Testability vs Automatability? How to improve your Software Testing.
What is Testability vs Automatability? How to improve your Software Testing.Alan Richardson
 
What is Agile Testing? A MindMap
What is Agile Testing? A MindMapWhat is Agile Testing? A MindMap
What is Agile Testing? A MindMapAlan Richardson
 
Evil Tester's Guide to Agile Testing
Evil Tester's Guide to Agile TestingEvil Tester's Guide to Agile Testing
Evil Tester's Guide to Agile TestingAlan Richardson
 
The Evil Tester Show - Episode 001 Halloween 2017
The Evil Tester Show - Episode 001 Halloween 2017The Evil Tester Show - Episode 001 Halloween 2017
The Evil Tester Show - Episode 001 Halloween 2017Alan Richardson
 
Simple ways to add and work with a `.jar` file in your local maven setup
Simple ways to add and work with a `.jar` file in your local maven setupSimple ways to add and work with a `.jar` file in your local maven setup
Simple ways to add and work with a `.jar` file in your local maven setupAlan Richardson
 
Learning in Public - A How to Speak in Public Workshop
Learning in Public - A How to Speak in Public WorkshopLearning in Public - A How to Speak in Public Workshop
Learning in Public - A How to Speak in Public WorkshopAlan Richardson
 
How to Practise to Remove Fear of Public Speaking
How to Practise to Remove Fear of Public SpeakingHow to Practise to Remove Fear of Public Speaking
How to Practise to Remove Fear of Public SpeakingAlan Richardson
 

More from Alan Richardson (19)

Open source tools - Test Management Summit - 2009
Open source tools - Test Management Summit - 2009Open source tools - Test Management Summit - 2009
Open source tools - Test Management Summit - 2009
 
The Future of Testing Webinar
The Future of Testing WebinarThe Future of Testing Webinar
The Future of Testing Webinar
 
Secrets and Mysteries of Automated Execution Keynote slides
Secrets and Mysteries of Automated Execution Keynote slidesSecrets and Mysteries of Automated Execution Keynote slides
Secrets and Mysteries of Automated Execution Keynote slides
 
Automating Pragmatically - Testival 20190604
Automating Pragmatically - Testival 20190604Automating Pragmatically - Testival 20190604
Automating Pragmatically - Testival 20190604
 
Joy of Coding Conference 2019 slides - Alan Richardson
Joy of Coding Conference 2019 slides - Alan RichardsonJoy of Coding Conference 2019 slides - Alan Richardson
Joy of Coding Conference 2019 slides - Alan Richardson
 
About Consultant Alan Richardson Compendium Developments Evil Tester
About Consultant Alan Richardson Compendium Developments Evil TesterAbout Consultant Alan Richardson Compendium Developments Evil Tester
About Consultant Alan Richardson Compendium Developments Evil Tester
 
Shift left-testing
Shift left-testingShift left-testing
Shift left-testing
 
Automating and Testing a REST API
Automating and Testing a REST APIAutomating and Testing a REST API
Automating and Testing a REST API
 
Technical and Testing Challenges: Using the "Protect The Square" Game
Technical and Testing Challenges: Using the "Protect The Square" GameTechnical and Testing Challenges: Using the "Protect The Square" Game
Technical and Testing Challenges: Using the "Protect The Square" Game
 
TDD - Test Driven Development - Java JUnit FizzBuzz
TDD - Test Driven Development - Java JUnit FizzBuzzTDD - Test Driven Development - Java JUnit FizzBuzz
TDD - Test Driven Development - Java JUnit FizzBuzz
 
If you want to automate, you learn to code
If you want to automate, you learn to codeIf you want to automate, you learn to code
If you want to automate, you learn to code
 
Your Automated Execution Does Not Have to be Flaky
Your Automated Execution Does Not Have to be FlakyYour Automated Execution Does Not Have to be Flaky
Your Automated Execution Does Not Have to be Flaky
 
What is Testability vs Automatability? How to improve your Software Testing.
What is Testability vs Automatability? How to improve your Software Testing.What is Testability vs Automatability? How to improve your Software Testing.
What is Testability vs Automatability? How to improve your Software Testing.
 
What is Agile Testing? A MindMap
What is Agile Testing? A MindMapWhat is Agile Testing? A MindMap
What is Agile Testing? A MindMap
 
Evil Tester's Guide to Agile Testing
Evil Tester's Guide to Agile TestingEvil Tester's Guide to Agile Testing
Evil Tester's Guide to Agile Testing
 
The Evil Tester Show - Episode 001 Halloween 2017
The Evil Tester Show - Episode 001 Halloween 2017The Evil Tester Show - Episode 001 Halloween 2017
The Evil Tester Show - Episode 001 Halloween 2017
 
Simple ways to add and work with a `.jar` file in your local maven setup
Simple ways to add and work with a `.jar` file in your local maven setupSimple ways to add and work with a `.jar` file in your local maven setup
Simple ways to add and work with a `.jar` file in your local maven setup
 
Learning in Public - A How to Speak in Public Workshop
Learning in Public - A How to Speak in Public WorkshopLearning in Public - A How to Speak in Public Workshop
Learning in Public - A How to Speak in Public Workshop
 
How to Practise to Remove Fear of Public Speaking
How to Practise to Remove Fear of Public SpeakingHow to Practise to Remove Fear of Public Speaking
How to Practise to Remove Fear of Public Speaking
 

Recently uploaded

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 

Recently uploaded (20)

Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 

FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration

  • 1. FAQ ‐ why does my code throw a null pointer exception A: ‐ common reason #1 Variable Redeclaration Alan Richardson www.JavaForTesters.com twitter:  @ eviltester @eviltester 1
  • 2. Does this happen to you? @eviltester 2
  • 3. FAQ ‐ why does my code throw a null pointer exception ‐ common reason #1 Redeclaration Using  @BeforeClass or  @Before can setup data for use in tests Any 'variables' we instantiate need to be 'fields' rather than variables We want to instantiate them in the setup method rather than redeclare them @eviltester 3
  • 4. Example of the Problem I know I will use an  Adder in my test so I create it as a field: public class WhyCodeThrowsNullPointerExceptionTest {     Adder adder; I don't want to re‐instantiate it each time so I make an  @BeforeClass method to instantiate it: @BeforeClass public static void setupAdder(){     Adder adder = new Adder(); } Warning: Error in the above code @eviltester 4
  • 5. Semantic Error I just made a Semantic coding error. This won't be caught by a compiler, but it will cause my  @Test to fail with a Null Pointer Exception. @Test public void canAddTwoPlusTwo(){     Assert.assertEquals(4,adder.add(2,2)); } The above test will fail with a  NullPointerException  java.lang.NullPointerException     at com.javafortesters.faq.nullpointerexception. WhyCodeThrowsNullPointerExceptionTest.canAddTwoPlusTwo (WhyCodeThrowsNullPointerExceptionTest.java:29) ... @eviltester 5
  • 6. What Went Wrong? In the setup method I really wanted to assign a value to the field, instead I created an new variable with the same name. Adder adder = new Adder(); I really wanted: adder = new Adder(); and to support that, the field really needs to be declared as  static  static Adder adder; @eviltester 6
  • 7. How to avoid? IDE Syntax Highlighting If I was editing this in an IDE, then I would see that the  adder in the following line is never used : Adder adder = new Adder(); It will be coloured grey or some other IDE indication. @eviltester 7
  • 8.  static methods need  static fields In order for the field to be used in the static method it needed to be static. If I had used it in the setup method: Adder adder; @BeforeClass public static void setupAdder(){     adder = new Adder(); } Then I would have seen a syntax error in the code because:  Non‐static field 'adder' cannot be referenced from a static context  @eviltester 8
  • 9. IDE will show this @eviltester 9
  • 10. Refactor to fields Had I written the  @Test code first then I would have started with: @Test public void canAddTwoPlusTwo(){          Adder adder = new Adder();     Assert.assertEquals(4,adder.add(2,2)); } I can refactor this to avoid errors. @eviltester 10
  • 11. Automated refactoring of Extract to field where initialized as 'field declaration Might have generated the following code: private final Adder adder = new Adder(); this removes the need for an  @BeforeClass or  @Before  construct entirely @eviltester 11
  • 12. Automated refactoring of Extract to field where initialized in constructor private final Adder adder; public WhyCodeThrowsNullPointerExceptionTest() {     adder = new Adder(); } this removes the need for an  @BeforeClass or  @Before  construct entirely @eviltester 12
  • 13. Automatically Refactor prior to using  @Before...  I might still want to use an  @BeforeClass or  @Before  To make the code readable I could do that but I don't think I would have declared a new variable after the refactorings because I have a working code example that I'm moving. @eviltester 13
  • 14. In General Try to write one test at a time so that if you have a problem it is easier to identify where the problem is Try to write working isolated tests and then refactor to a more general solution when you need it ‐ that way, you know it was working, so you just have to work backwards to find out what went wrong Try to use automated IDE refactoring rather than move code around manually Use the IDE syntax highlighting to help spot any issues @eviltester 14
  • 15. Source Code If you want to experiment with code that recreates this problem then have a look at WhyCodeThrowsNullPointerExceptionTest.java in javaScratchpad @eviltester 15
  • 16. "Java For Testers" A Book for learning how to code Java All code written as Test methods you learn TDD your learn JUnit you focus on code you are not distracted by 'creating an application' Affordably priced so that everyone can learn ﴾Free Download of 70+ Sample PDF﴿ @eviltester 16
  • 17. BIO ‐ Alan Richardson Alan Richardson has more than twenty years of professional IT experience, working as a programmer and at every level of the testing hierarchy from tester through head of testing. He has performed keynote speeches and tutorials at conferences worldwide. Author of multiple books on testing and automating. Alan also has created online training courses to help people learn Technical Web Testing and Selenium WebDriver with Java. He works as an independent consultant, helping companies improve their use of automation, agile, and exploratory technical testing. @eviltester 17
  • 19. Follow Linkedin ‐ uk.linkedin.com/in/eviltester Twitter ‐ twitter.com/eviltester Instagram ‐ instagram.com/eviltester Facebook ‐ facebook.com/eviltester Youtube ‐ youtube.com/user/EviltesterVideos Pinterest ‐ uk.pinterest.com/eviltester Github ‐ github.com/eviltester Slideshare ‐ slideshare.net/eviltester @eviltester 19
  • 20. Books Written By Alan Richardson Java For Testers Dear Evil Tester Automating and Testing a REST API Selenium Simplified @eviltester 20
  • 21. Online Training Courses By Alan Richardson Selenium Webdriver With Java Technical Web Testing 101 Evil Tester Talks: Technical Testing Case Study: Java Desktop Application Technical Training @eviltester 21