SlideShare ist ein Scribd-Unternehmen logo
1 von 79
JUnit PowerUP
Practical Testing Tips
James McGivern
About James
Likes cats

Talks fast
Technical Evangelist
Hates Marmite

Mathematician turned
Computer Scientist

Lives in London
JUnit
vs
TestNG
One Busy Day On
Concurrent Island...

Intro
Concurrency?
concurrent - adjective
1. occurring or existing simultaneously or side by
side: concurrent attacks by land, sea, and air.
2. acting in conjunction; co-operating.
3. having equal authority or jurisdiction.
4. accordant or agreeing.
5. tending to or intersecting at the same point: four
concurrent lines.
The behaviour of a single threaded application is
deterministic
A multithreaded application may appear
stochastic
Concurrency introduces new problems:
deadlocks
resource starvation (e.g livelocks)
race conditions
contention

•
•
•
•
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
But Why?
Consider the old singleton pattern
getInstance() method:
public Singleton getInstance() {
if(INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}

and two threads: Thread A, Thread B
Each statement is an atomic block
Each thread executes a non-negative number of
atomic blocks
Threads take turns but order is not guaranteed
Given a number of threads t, and a group of
statements s, the number of execution order
permutations is given by:

interleavings(t, s) =

(ts)!
t
(s!)
The JUnit Cup
Challenge

Level 0
public class FibonacciSequenceTest {
FibonacciSequence fib = new FibonacciSequence();
@Test public void shouldOutputZeroWhenInputIsZero() {
assertThat(fib.get(0), is(0))
}
@Test public void shouldOutputOneWhenInputIsOne() {
assertThat(fib.get(1), is(1));
}
@Test public void shouldCalculateNthNumber(){
for(int i = 2; i <= 10; i++) {
int x = fib.get(i-1);
int y = fib.get(i-2);
int sum = x + y;
assertThat(fib.calculate(i), is(sum);
}
}
}
Cost/Benefit Ratio
(TDD) Unit tests are executable specifications of
the code
Unit (+ integration tests) will never find all the bugs
Writing tests takes time
Time is limited
Which tests should I write and which should I
forgo?
JUnit Runners
Bundled
Suite, Parameterized

•
• Theories, Categories, Enclosed

Popular 3rd party runners
Mockito, PowerMock(ito)

•

Custom
JBehave, Spock

•
• dynamic tests?
Custom Runner
public abstract class Runner
implements Describable {
public Runner(Class<?> testClass){...}
public abstract Description getDescription();
public abstract void run(RunNotifier n);
public int testCount() {
return getDescription().testCount();
}
}
Description
Description.createSuiteDescription(...)
Description.createTestDescription(...)
Description#addChild(Description d)
RunNotifier
fireTestStarted(Description d)
fireTestFinished(Description d)
fireTestFailure(Failure f)
fireTestIgnored(Description d)
fireTestAssumptionFailed(Failure f)
Warning
• A very coarse way of modifying test execution
• Even when extending from BlockJUnit4ClassRunner
there is a degree of complex code

• Runners can not be composed e.g.
@RunWith(MockitoJUnitRunner.class}
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest {...}
@RunWith({MockitoRunner.class,
SpringJUnit4ClassRunner.class})
public class SomeTest {...}
JUnit Rules

PowerUP
Rules can:
Read/Write test metadata
Modify the test before execution
Modify the result after execution
Suite vs Class == @ClassRule vs @MethodRule
public interface TestRule {
Statement apply(Statement base,
Description description);
}
public class MockRule implements TestRule {
private final Object target;
public MockRule(Object target) {
this.target = target;
}
public Statement apply(final Statement base,
Description description) {
return new Statement() {
public void evaluate() throws Throwable {
MockitoAnnotations.initMocks(target);
base.evaluate();
}
};
}
}
The Thread
Challenge

Level 1
static class VolatileInt { volatile int num = 0; }
public void shouldIncrementCounter() {
final int count = 32 * 1000;
final int nThreads = 64;
ExecutorService es = Executors.newFixedThreadPool(nThreads);
final VolatileInt vi = new VolatileInt();
for (int i = 0; i < nThreads; i++) {
es.submit(new Runnable() {
public void run() {
for (int j = 0; j < count; j += nThreads)
vi.num++;
}
});
es.shutdown();
es.awaitTermination(10, TimeUnit.SECONDS);
assertEquals(count, vi.num);

}

http://vanillajava.blogspot.co.uk/2011/08/why-testing-code-for-thread-safety-is.html
Weapons Guide
• Java Concurrency in Practice - Brian Goetz
• Java Performance - Charlie Hunt
• Effective Unit Testing: A guide for Java developers Lasse Koskela

• Programming Concurrency on the JVM -Venkat
Subramaniam
Choreographer’s
Workshop

Level 2
http://www.recessframework.org/page/map-reduce-anonymous-functions-lambdas-php

Text
Awaitility

PowerUP
A Simple DSL
No more Thread.sleep(), or while loops
await().until(
new Callable<Boolean>() {
public Boolean call() throws Exception {
return userRepository.size() == 1;
}
};
)
The previous example was not particularly re-usable.
Let’s fix that!
await().until(sizeOf(repository), equalTo(1));

where
private Callable<Integer> sizeOf(Collection c){
return new Callable<Integer>() {
public Boolean call() throws Exception {
return c.size();
}
};
}
Advanced Waiting
• Callable is still a lot of boiler plate...
await().untilCall(to(repository).size(), equalTo(3));

• Using reflection
await().until(
fieldIn(repository).ofType(int.class)
.andWithName(“size”), equalTo(3)
);

• Polling

with()
.pollInterval(ONE_HUNDERED_MILLISECONDS)
.and().with().pollDelay(20, MILLISECONDS)
.await("user registration").until(
userStatus(), equalTo(REGISTERED));
The Shared
Resource Contest

Level 3
Race Conditions
A race condition is a situation in which two or more
threads or processes are reading or writing some
shared data, and the final result depends on the timing
of how the threads are scheduled.
public class Counter {
protected long count = 0;
public void add(long value){
this.count = this.count + value;
}
}
ThreadWeaver

PowerUP
public class ConcurrentHashMapTest {
ConcurrentMap<String, Integer> map;
@ThreadedBefore
public void before() {
map = new ConcurrentHashMap();
}
@ThreadedMain
public void mainThread() {
map.putIfAbsent("A", 1);
}
@ThreadedSecondary
public void secondThread() {
map.putIfAbsent("A", 2);
}

}

@ThreadedAfter
public void after() {
assertEquals(map.get(“A”), 1);
}
Works by instrumenting bytecode at runtime
Does not integrate with JUnit but can be embedded
@Test
public void testThreading() {
new AnnotatedTestRunner()
.runTests(
this.getClass(),
ConcurrentHashMapTest.class
);
}

Has fine-grained control over breakpoints/code position
Documentation is ok but not a lot on in-depth material
PROJECT STATUS UNKNOWN, MAYBE INACTIVE
Princess
Protection HQ

Level 4
A recurrent
producer-consumer
information
processing network
for anomaly
detection
Java Path Finder
http://babelfish.arc.nasa.gov/trac/jpf
JPF created by NASA
Open-sourced in 2005
Is a JVM written in Java that runs on the JVM
Primarily used as a model checker for concurrent
programs, e.g deadlocks, race conditions, NPEs
Very powerful
Not very usable (e.g. limited CI support)
Byteman

PowerUP
Java Bytecode Manipulating Agent - Byteman
Uses java.lang.intrument as an agent
Can be used for:
fault injection testing, tracing during test and in
production, an alternative AOP (e.g. cross-cutting
logging)
Using instrumentation in tests means:
fewer mocks
less boilerplate to generate abnormal senarios
Why Byteman?
AOP is powerful but complex:

• code is targeted indirectly rather than at the class/
method declaration site

• AOP definition languages can be a bit odd/hard to
work with

• Impact at runtime is sometimes significant to

application performance due to pointcut definitions

• not always trivial to turn-off, alter, or remove advice
EBCA Rules
A Byteman rule consists of:

• Event - the class/interface/method target
• Binding - initialise rule values
• Condition - a boolean expression (optional)
• Action - some Java code that may return or
throw (can not break contracts)

Rules may have state, i.e 1st invocation do A, 2nd
invocation do B, etc.
Fault Injection
RULE simulate exception from Executor
INTERFACE ^java.util.Executor
METHOD execute
AT ENTRY
IF callerEquals("ServiceInstanceImpl.execute", true)
DO traceln(“Throwing exception in execute”);
THROW new java.util.concurrent.RejectedExecutionException();
ENDRULE
In-built Rules
Tracing
traceOpen, traceClose, traceln, traceStack
Shared Rule State
flag, clear, flagged, countDown, incrementCounter
Synchronization
waitFor, signalWake, rendezvous, delay
Timing
createTimer, getElapsedTime, resetTimer
Call Stack Checking
callerEquals, callerMatches
Recursive Triggering
disable/enableTriggering
BMUnit
@RunWith(BMUnitRunner.class)
@BMScript(value="traceRules", dir="scripts")
class DBTests1 {
@Test
@BMRule(
className="UserRepository”,
methodName="findByName",
condition=
"$1.getName().contains("James")",
action="THROW new UserNotFoundException")
public void shouldErrorIfNoUserFound()
{
...
}
}
Machine Lab

Bouns LeveL
ConcurrentUnit
Website: https://github.com/jhalterman/concurrentunit
JUnit addon library
Comprised of:

• A thread co-ordinator Waiter
• Allows assertions to be made in worker threads
• Waiter collects and returns outcomes of
assertions
FindBugs
Website: http://findbugs.sourceforge.net
Integrates with Maven, Gradle, Sonar, etc
Multithreaded correctness group:

• Inconsistent synchronization
• Field not guarded against concurrent access
• Method calls Thread.sleep() with a lock held
• Creation of ScheduledThreadPoolExecutor with
zero core threads
Freud
Website: https://github.com/LMAX-Exchange/freud
A framework for writing static analysis tests
Lacks good documentation except code examples
Has rules for:
✦
✦

✦
✦

Java sources
Java class objects. (i.e analysing the java.lang.Class
object)
Java class files (i.e analysing the ".class" file)
Spring framework XML configuration files
Summary

Scores
Lv.0 - Testing Tutorial

• TDD is your friend
• Prefer rules over runners
• Don’t be afraid to write custom rules and
runners

• Ensure you spend your time on the
important tests
Lv.1 - The Thread
Challenge

• Modelling real world behaviour of your application
is hard

• Don’t assume your tests are exhaustively testing
the scenarios

• Behaviour depends heavily on the system (e.g. load)
• Know your stuff - read read read
Lv2. Choreographer’s
Workshop

• It is essential to test the co-ordinated
behaviour of threads

• If threads are not sharing resources we

don’t need to care about synchronisation
between thread

• Awaitility allows us to check that some end
state if finally reached (within the given
time)
Lv.3 - The Shared
Resource Contest

• When a resource is shared between

threads new problem cases can arise, e.g.
races

• Often the problem can be simplified to the
case of 2 threads

• To test the orders of execution of 2
threads we can use ThreadWeaver
Lv.4 - Princess
Protection HQ

• Many problems can’t be reduced to a 2 thread
model

• JPF can provide some automated analysis of
concurrency issues

• Byteman allows us to take control of the whole
application

• Both are very heavy weight and should not be
JUnit PowerUP

GAME OVER
Credits
JUnit
http://www.junit.org
Awaitility
http://code.google.com/p/awaitility
ByteMan
http://www.jboss.org/byteman

ThreadWeaver
http://code.google.com/p/thread-weaver
ConcurrentUnit
https://github.com/jhalterman/concurrentunit

FindBugs
http://findbugs.sourceforge.net
Freud
https://github.com/LMAX-Exchange/freud

Java PathFinder
http://babelfish.arc.nasa.gov/trac/jpf
JUnit PowerUP
Practical Testing Tips
James McGivern

Weitere ähnliche Inhalte

Was ist angesagt?

Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments rajni kaushal
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
SchNet: A continuous-filter convolutional neural network for modeling quantum...
SchNet: A continuous-filter convolutional neural network for modeling quantum...SchNet: A continuous-filter convolutional neural network for modeling quantum...
SchNet: A continuous-filter convolutional neural network for modeling quantum...Kazuki Fujikawa
 
Exercise 1a transfer functions - solutions
Exercise 1a   transfer functions - solutionsExercise 1a   transfer functions - solutions
Exercise 1a transfer functions - solutionswondimu wolde
 
Systems Analysis & Control: Steady State Errors
Systems Analysis & Control: Steady State ErrorsSystems Analysis & Control: Steady State Errors
Systems Analysis & Control: Steady State ErrorsJARossiter
 

Was ist angesagt? (20)

Thread
ThreadThread
Thread
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
 
Lecture k-sorting
Lecture k-sortingLecture k-sorting
Lecture k-sorting
 
Java lab 2
Java lab 2Java lab 2
Java lab 2
 
LogicObjects
LogicObjectsLogicObjects
LogicObjects
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Matlab file
Matlab fileMatlab file
Matlab file
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
SchNet: A continuous-filter convolutional neural network for modeling quantum...
SchNet: A continuous-filter convolutional neural network for modeling quantum...SchNet: A continuous-filter convolutional neural network for modeling quantum...
SchNet: A continuous-filter convolutional neural network for modeling quantum...
 
Exercise 1a transfer functions - solutions
Exercise 1a   transfer functions - solutionsExercise 1a   transfer functions - solutions
Exercise 1a transfer functions - solutions
 
1 Recur
1 Recur1 Recur
1 Recur
 
Java programs
Java programsJava programs
Java programs
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Systems Analysis & Control: Steady State Errors
Systems Analysis & Control: Steady State ErrorsSystems Analysis & Control: Steady State Errors
Systems Analysis & Control: Steady State Errors
 

Andere mochten auch

Andere mochten auch (13)

JUnit Sample
JUnit SampleJUnit Sample
JUnit Sample
 
Junit
JunitJunit
Junit
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
Test Driven Development and JUnit
Test Driven Development and JUnitTest Driven Development and JUnit
Test Driven Development and JUnit
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Junit
JunitJunit
Junit
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Introduction To UnitTesting & JUnit
Introduction To UnitTesting & JUnitIntroduction To UnitTesting & JUnit
Introduction To UnitTesting & JUnit
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Android Unit Tesing at I/O rewind 2015
Android Unit Tesing at I/O rewind 2015Android Unit Tesing at I/O rewind 2015
Android Unit Tesing at I/O rewind 2015
 

Ähnlich wie JUnit PowerUp

COS30008 Semester 1, 2016 Dr. Markus Lumpe 1 Swinbu.docx
COS30008 Semester 1, 2016 Dr. Markus Lumpe  1 Swinbu.docxCOS30008 Semester 1, 2016 Dr. Markus Lumpe  1 Swinbu.docx
COS30008 Semester 1, 2016 Dr. Markus Lumpe 1 Swinbu.docxvanesaburnand
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contdraksharao
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfmail931892
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talkrahulrevo
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureZidny Nafan
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data StructureSriram Raj
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trAbramMartino96
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 

Ähnlich wie JUnit PowerUp (20)

COS30008 Semester 1, 2016 Dr. Markus Lumpe 1 Swinbu.docx
COS30008 Semester 1, 2016 Dr. Markus Lumpe  1 Swinbu.docxCOS30008 Semester 1, 2016 Dr. Markus Lumpe  1 Swinbu.docx
COS30008 Semester 1, 2016 Dr. Markus Lumpe 1 Swinbu.docx
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Chap2 class,objects contd
Chap2 class,objects contdChap2 class,objects contd
Chap2 class,objects contd
 
Java Generics
Java GenericsJava Generics
Java Generics
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
 
Concurrent talk
Concurrent talkConcurrent talk
Concurrent talk
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Java file
Java fileJava file
Java file
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Mcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search trMcq 15-20Q15Which of the following trees are binary search tr
Mcq 15-20Q15Which of the following trees are binary search tr
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
3 j unit
3 j unit3 j unit
3 j unit
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 

Kürzlich hochgeladen

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessWSO2
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentMahmoud Rabie
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...amber724300
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Karmanjay Verma
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 

Kürzlich hochgeladen (20)

Accelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with PlatformlessAccelerating Enterprise Software Engineering with Platformless
Accelerating Enterprise Software Engineering with Platformless
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Digital Tools & AI in Career Development
Digital Tools & AI in Career DevelopmentDigital Tools & AI in Career Development
Digital Tools & AI in Career Development
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
JET Technology Labs White Paper for Virtualized Security and Encryption Techn...
 
Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#Microservices, Docker deploy and Microservices source code in C#
Microservices, Docker deploy and Microservices source code in C#
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 

JUnit PowerUp

  • 1. JUnit PowerUP Practical Testing Tips James McGivern
  • 2. About James Likes cats Talks fast Technical Evangelist Hates Marmite Mathematician turned Computer Scientist Lives in London
  • 4. One Busy Day On Concurrent Island... Intro
  • 5.
  • 6. Concurrency? concurrent - adjective 1. occurring or existing simultaneously or side by side: concurrent attacks by land, sea, and air. 2. acting in conjunction; co-operating. 3. having equal authority or jurisdiction. 4. accordant or agreeing. 5. tending to or intersecting at the same point: four concurrent lines.
  • 7. The behaviour of a single threaded application is deterministic A multithreaded application may appear stochastic Concurrency introduces new problems: deadlocks resource starvation (e.g livelocks) race conditions contention • • • •
  • 8. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 9. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 10. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 11. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 12. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 13. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 14. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 15. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 16. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 17. But Why? Consider the old singleton pattern getInstance() method: public Singleton getInstance() { if(INSTANCE == null) { INSTANCE = new Singleton(); } return INSTANCE; } and two threads: Thread A, Thread B
  • 18. Each statement is an atomic block Each thread executes a non-negative number of atomic blocks Threads take turns but order is not guaranteed Given a number of threads t, and a group of statements s, the number of execution order permutations is given by: interleavings(t, s) = (ts)! t (s!)
  • 20.
  • 21. public class FibonacciSequenceTest { FibonacciSequence fib = new FibonacciSequence(); @Test public void shouldOutputZeroWhenInputIsZero() { assertThat(fib.get(0), is(0)) } @Test public void shouldOutputOneWhenInputIsOne() { assertThat(fib.get(1), is(1)); } @Test public void shouldCalculateNthNumber(){ for(int i = 2; i <= 10; i++) { int x = fib.get(i-1); int y = fib.get(i-2); int sum = x + y; assertThat(fib.calculate(i), is(sum); } } }
  • 22. Cost/Benefit Ratio (TDD) Unit tests are executable specifications of the code Unit (+ integration tests) will never find all the bugs Writing tests takes time Time is limited Which tests should I write and which should I forgo?
  • 23. JUnit Runners Bundled Suite, Parameterized • • Theories, Categories, Enclosed Popular 3rd party runners Mockito, PowerMock(ito) • Custom JBehave, Spock • • dynamic tests?
  • 24. Custom Runner public abstract class Runner implements Describable { public Runner(Class<?> testClass){...} public abstract Description getDescription(); public abstract void run(RunNotifier n); public int testCount() { return getDescription().testCount(); } }
  • 26. RunNotifier fireTestStarted(Description d) fireTestFinished(Description d) fireTestFailure(Failure f) fireTestIgnored(Description d) fireTestAssumptionFailed(Failure f)
  • 27. Warning • A very coarse way of modifying test execution • Even when extending from BlockJUnit4ClassRunner there is a degree of complex code • Runners can not be composed e.g. @RunWith(MockitoJUnitRunner.class} @RunWith(SpringJUnit4ClassRunner.class) public class SomeTest {...} @RunWith({MockitoRunner.class, SpringJUnit4ClassRunner.class}) public class SomeTest {...}
  • 29. Rules can: Read/Write test metadata Modify the test before execution Modify the result after execution Suite vs Class == @ClassRule vs @MethodRule
  • 30. public interface TestRule { Statement apply(Statement base, Description description); } public class MockRule implements TestRule { private final Object target; public MockRule(Object target) { this.target = target; } public Statement apply(final Statement base, Description description) { return new Statement() { public void evaluate() throws Throwable { MockitoAnnotations.initMocks(target); base.evaluate(); } }; } }
  • 32.
  • 33. static class VolatileInt { volatile int num = 0; } public void shouldIncrementCounter() { final int count = 32 * 1000; final int nThreads = 64; ExecutorService es = Executors.newFixedThreadPool(nThreads); final VolatileInt vi = new VolatileInt(); for (int i = 0; i < nThreads; i++) { es.submit(new Runnable() { public void run() { for (int j = 0; j < count; j += nThreads) vi.num++; } }); es.shutdown(); es.awaitTermination(10, TimeUnit.SECONDS); assertEquals(count, vi.num); } http://vanillajava.blogspot.co.uk/2011/08/why-testing-code-for-thread-safety-is.html
  • 34. Weapons Guide • Java Concurrency in Practice - Brian Goetz • Java Performance - Charlie Hunt • Effective Unit Testing: A guide for Java developers Lasse Koskela • Programming Concurrency on the JVM -Venkat Subramaniam
  • 36.
  • 39. A Simple DSL No more Thread.sleep(), or while loops await().until( new Callable<Boolean>() { public Boolean call() throws Exception { return userRepository.size() == 1; } }; )
  • 40. The previous example was not particularly re-usable. Let’s fix that! await().until(sizeOf(repository), equalTo(1)); where private Callable<Integer> sizeOf(Collection c){ return new Callable<Integer>() { public Boolean call() throws Exception { return c.size(); } }; }
  • 41. Advanced Waiting • Callable is still a lot of boiler plate... await().untilCall(to(repository).size(), equalTo(3)); • Using reflection await().until( fieldIn(repository).ofType(int.class) .andWithName(“size”), equalTo(3) ); • Polling with() .pollInterval(ONE_HUNDERED_MILLISECONDS) .and().with().pollDelay(20, MILLISECONDS) .await("user registration").until( userStatus(), equalTo(REGISTERED));
  • 43.
  • 44. Race Conditions A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. public class Counter { protected long count = 0; public void add(long value){ this.count = this.count + value; } }
  • 46. public class ConcurrentHashMapTest { ConcurrentMap<String, Integer> map; @ThreadedBefore public void before() { map = new ConcurrentHashMap(); } @ThreadedMain public void mainThread() { map.putIfAbsent("A", 1); } @ThreadedSecondary public void secondThread() { map.putIfAbsent("A", 2); } } @ThreadedAfter public void after() { assertEquals(map.get(“A”), 1); }
  • 47. Works by instrumenting bytecode at runtime Does not integrate with JUnit but can be embedded @Test public void testThreading() { new AnnotatedTestRunner() .runTests( this.getClass(), ConcurrentHashMapTest.class ); } Has fine-grained control over breakpoints/code position Documentation is ok but not a lot on in-depth material PROJECT STATUS UNKNOWN, MAYBE INACTIVE
  • 49.
  • 51.
  • 52. Java Path Finder http://babelfish.arc.nasa.gov/trac/jpf JPF created by NASA Open-sourced in 2005 Is a JVM written in Java that runs on the JVM Primarily used as a model checker for concurrent programs, e.g deadlocks, race conditions, NPEs Very powerful Not very usable (e.g. limited CI support)
  • 54. Java Bytecode Manipulating Agent - Byteman Uses java.lang.intrument as an agent Can be used for: fault injection testing, tracing during test and in production, an alternative AOP (e.g. cross-cutting logging) Using instrumentation in tests means: fewer mocks less boilerplate to generate abnormal senarios
  • 55. Why Byteman? AOP is powerful but complex: • code is targeted indirectly rather than at the class/ method declaration site • AOP definition languages can be a bit odd/hard to work with • Impact at runtime is sometimes significant to application performance due to pointcut definitions • not always trivial to turn-off, alter, or remove advice
  • 56. EBCA Rules A Byteman rule consists of: • Event - the class/interface/method target • Binding - initialise rule values • Condition - a boolean expression (optional) • Action - some Java code that may return or throw (can not break contracts) Rules may have state, i.e 1st invocation do A, 2nd invocation do B, etc.
  • 57. Fault Injection RULE simulate exception from Executor INTERFACE ^java.util.Executor METHOD execute AT ENTRY IF callerEquals("ServiceInstanceImpl.execute", true) DO traceln(“Throwing exception in execute”); THROW new java.util.concurrent.RejectedExecutionException(); ENDRULE
  • 58. In-built Rules Tracing traceOpen, traceClose, traceln, traceStack Shared Rule State flag, clear, flagged, countDown, incrementCounter Synchronization waitFor, signalWake, rendezvous, delay Timing createTimer, getElapsedTime, resetTimer Call Stack Checking callerEquals, callerMatches Recursive Triggering disable/enableTriggering
  • 59. BMUnit @RunWith(BMUnitRunner.class) @BMScript(value="traceRules", dir="scripts") class DBTests1 { @Test @BMRule( className="UserRepository”, methodName="findByName", condition= "$1.getName().contains("James")", action="THROW new UserNotFoundException") public void shouldErrorIfNoUserFound() { ... } }
  • 61.
  • 62. ConcurrentUnit Website: https://github.com/jhalterman/concurrentunit JUnit addon library Comprised of: • A thread co-ordinator Waiter • Allows assertions to be made in worker threads • Waiter collects and returns outcomes of assertions
  • 63. FindBugs Website: http://findbugs.sourceforge.net Integrates with Maven, Gradle, Sonar, etc Multithreaded correctness group: • Inconsistent synchronization • Field not guarded against concurrent access • Method calls Thread.sleep() with a lock held • Creation of ScheduledThreadPoolExecutor with zero core threads
  • 64. Freud Website: https://github.com/LMAX-Exchange/freud A framework for writing static analysis tests Lacks good documentation except code examples Has rules for: ✦ ✦ ✦ ✦ Java sources Java class objects. (i.e analysing the java.lang.Class object) Java class files (i.e analysing the ".class" file) Spring framework XML configuration files
  • 66.
  • 67. Lv.0 - Testing Tutorial • TDD is your friend • Prefer rules over runners • Don’t be afraid to write custom rules and runners • Ensure you spend your time on the important tests
  • 68. Lv.1 - The Thread Challenge • Modelling real world behaviour of your application is hard • Don’t assume your tests are exhaustively testing the scenarios • Behaviour depends heavily on the system (e.g. load) • Know your stuff - read read read
  • 69. Lv2. Choreographer’s Workshop • It is essential to test the co-ordinated behaviour of threads • If threads are not sharing resources we don’t need to care about synchronisation between thread • Awaitility allows us to check that some end state if finally reached (within the given time)
  • 70. Lv.3 - The Shared Resource Contest • When a resource is shared between threads new problem cases can arise, e.g. races • Often the problem can be simplified to the case of 2 threads • To test the orders of execution of 2 threads we can use ThreadWeaver
  • 71. Lv.4 - Princess Protection HQ • Many problems can’t be reduced to a 2 thread model • JPF can provide some automated analysis of concurrency issues • Byteman allows us to take control of the whole application • Both are very heavy weight and should not be
  • 72.
  • 79. JUnit PowerUP Practical Testing Tips James McGivern