SlideShare a Scribd company logo
1 of 12
JunitOverview
Creating a test class in Junit:
• Define a subclass of TestCase
• Override the setUp() method to initialize object(s) under
test.
• Override the tearDown() method to release object(s) under
test.
• Define one or more public testXXX() methods that exercise
the object(s) under test and assert expected results.
• Define a static suite() factory method that creates a
TestSuite containing all the testXXX() methods of the
TestCase.
• Optionally define a main() method that runs the TestCase in
batch mode.
Example
public class CounterTest extends junit.framework.TestCase {
Counter counter1;
public CounterTest() { } // default constructor
protected void setUp() { // creates a (simple) test fixture
counter1 = new Counter();
}
protected void tearDown() { } // no resources to release
public void testIncrement() {
assertTrue(counter1.increment() == 1);
assertTrue(counter1.increment() == 2);
}
public void testDecrement() {
assertTrue(counter1.decrement() == -1);
}
}
Limitation : Mocking
Mocking Frameworks
PowerMock
EasyMock
Junit
EasyMock
Quick Review
PowerMock
• PowerMock is a framework that
extend other mock libraries
such as EasyMock with more
powerful capabilities.
• PowerMock uses a custom
classloader and bytecode
manipulation to enable
mocking of static methods,
constructors, final classes and
methods, private methods,
removal of static initializers and
more.
Mocking private methods
• Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the
test case.
• Use the @PrepareForTest(ClassWithPrivateMethod.class) annotation at the class-
level of the test case.
• Use PowerMock.createPartialMock(ClassWithPrivateMethod.class,
"nameOfTheMethodToMock") to create a mock object that onlymocks the method
with name nameOfTheMethodToMock in this class (let's call it mockObject).
• Use PowerMock.expectPrivate(mockObject, "nameOfTheMethodToMock",
argument1, argument2) to expect the method call
tonameOfTheMethodToMock with arguments argument1 and argument2.
• Use PowerMock.replay(mockObject) to change the mock object to replay mode.
• Use PowerMock.verify(mockObject) to change the mock object to verify mode.
Mocking static methods
• Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the
test case.
• Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the
class-level of the test case.
• Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all
methods of this class.
• Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class
to replay mode.
• Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class
to verify mode.
MockFinal
• Use the @RunWith(PowerMockRunner.class) annotation at
the class-level of the test case.
• Use the @PrepareForTest(ClassWithFinal.class) annotation
at the class-level of the test case.
• Use PowerMock.createMock(ClassWithFinal.class) to create
a mock object for all methods of this class (let's call
it mockObject).
• Use PowerMock.replay(mockObject) to change the mock
object to replay mode.
• Use PowerMock.verify(mockObject) to change the mock
object to verify mode.
Mocking static methods
• Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the
test case.
• Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the
class-level of the test case.
• Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all
methods of this class.
• Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class
to replay mode.
• Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class
to verify mode.
For more info: m@piyushmittal.com

More Related Content

What's hot

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016Vlad Mihalcea
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST API Best (Recommended) Practices
REST API Best (Recommended) PracticesRasheed Waraich
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
What is Test Plan? Edureka
What is Test Plan? EdurekaWhat is Test Plan? Edureka
What is Test Plan? EdurekaEdureka!
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETRajkumarsoy
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignYoung-Ho Cho
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
TEST EXECUTION AND REPORTING
TEST EXECUTION AND REPORTINGTEST EXECUTION AND REPORTING
TEST EXECUTION AND REPORTINGsuhasreddy1
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 

What's hot (20)

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST API Best (Recommended) Practices
REST API Best (Recommended) Practices
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Jsp element
Jsp elementJsp element
Jsp element
 
What is Test Plan? Edureka
What is Test Plan? EdurekaWhat is Test Plan? Edureka
What is Test Plan? Edureka
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Memory Analyzer Tool (MAT)
Memory Analyzer Tool (MAT) Memory Analyzer Tool (MAT)
Memory Analyzer Tool (MAT)
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
MERN PPT
MERN PPTMERN PPT
MERN PPT
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Node js Introduction
Node js IntroductionNode js Introduction
Node js Introduction
 
TEST EXECUTION AND REPORTING
TEST EXECUTION AND REPORTINGTEST EXECUTION AND REPORTING
TEST EXECUTION AND REPORTING
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Asp.net web api
Asp.net web apiAsp.net web api
Asp.net web api
 

Viewers also liked

Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mockPranalee Rokde
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Zohirul Alam Tiemoon
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)David Ehringer
 

Viewers also liked (7)

Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Mockito
MockitoMockito
Mockito
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 
OTA Models
OTA ModelsOTA Models
OTA Models
 

Similar to JunitOverview: Create Tests and Mock Objects (20)

JUnit
JUnitJUnit
JUnit
 
3 j unit
3 j unit3 j unit
3 j unit
 
Junit
JunitJunit
Junit
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Java custom annotations example
Java custom annotations exampleJava custom annotations example
Java custom annotations example
 
Unit testing
Unit testingUnit testing
Unit testing
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Junit
JunitJunit
Junit
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Unit test
Unit testUnit test
Unit test
 
Intro to Testing in Zope, Plone
Intro to Testing in Zope, PloneIntro to Testing in Zope, Plone
Intro to Testing in Zope, Plone
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 

More from Piyush Mittal

More from Piyush Mittal (20)

Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
 
Reflection
ReflectionReflection
Reflection
 
Gpu archi
Gpu archiGpu archi
Gpu archi
 
Cuda Architecture
Cuda ArchitectureCuda Architecture
Cuda Architecture
 
Intel open mp
Intel open mpIntel open mp
Intel open mp
 
Intro to parallel computing
Intro to parallel computingIntro to parallel computing
Intro to parallel computing
 
Cuda toolkit reference manual
Cuda toolkit reference manualCuda toolkit reference manual
Cuda toolkit reference manual
 
Matrix multiplication using CUDA
Matrix multiplication using CUDAMatrix multiplication using CUDA
Matrix multiplication using CUDA
 
Channel coding
Channel codingChannel coding
Channel coding
 
Basics of Coding Theory
Basics of Coding TheoryBasics of Coding Theory
Basics of Coding Theory
 
Java cheat sheet
Java cheat sheetJava cheat sheet
Java cheat sheet
 
Google app engine cheat sheet
Google app engine cheat sheetGoogle app engine cheat sheet
Google app engine cheat sheet
 
Git cheat sheet
Git cheat sheetGit cheat sheet
Git cheat sheet
 
Vi cheat sheet
Vi cheat sheetVi cheat sheet
Vi cheat sheet
 
Css cheat sheet
Css cheat sheetCss cheat sheet
Css cheat sheet
 
Cpp cheat sheet
Cpp cheat sheetCpp cheat sheet
Cpp cheat sheet
 
Ubuntu cheat sheet
Ubuntu cheat sheetUbuntu cheat sheet
Ubuntu cheat sheet
 
Php cheat sheet
Php cheat sheetPhp cheat sheet
Php cheat sheet
 
oracle 9i cheat sheet
oracle 9i cheat sheetoracle 9i cheat sheet
oracle 9i cheat sheet
 
Open ssh cheet sheat
Open ssh cheet sheatOpen ssh cheet sheat
Open ssh cheet sheat
 

Recently uploaded

welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringJuanCarlosMorales19600
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 

Recently uploaded (20)

welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Piping Basic stress analysis by engineering
Piping Basic stress analysis by engineeringPiping Basic stress analysis by engineering
Piping Basic stress analysis by engineering
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 

JunitOverview: Create Tests and Mock Objects

  • 1.
  • 2. JunitOverview Creating a test class in Junit: • Define a subclass of TestCase • Override the setUp() method to initialize object(s) under test. • Override the tearDown() method to release object(s) under test. • Define one or more public testXXX() methods that exercise the object(s) under test and assert expected results. • Define a static suite() factory method that creates a TestSuite containing all the testXXX() methods of the TestCase. • Optionally define a main() method that runs the TestCase in batch mode.
  • 3. Example public class CounterTest extends junit.framework.TestCase { Counter counter1; public CounterTest() { } // default constructor protected void setUp() { // creates a (simple) test fixture counter1 = new Counter(); } protected void tearDown() { } // no resources to release public void testIncrement() { assertTrue(counter1.increment() == 1); assertTrue(counter1.increment() == 2); } public void testDecrement() { assertTrue(counter1.decrement() == -1); } }
  • 7. PowerMock • PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. • PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more.
  • 8. Mocking private methods • Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case. • Use the @PrepareForTest(ClassWithPrivateMethod.class) annotation at the class- level of the test case. • Use PowerMock.createPartialMock(ClassWithPrivateMethod.class, "nameOfTheMethodToMock") to create a mock object that onlymocks the method with name nameOfTheMethodToMock in this class (let's call it mockObject). • Use PowerMock.expectPrivate(mockObject, "nameOfTheMethodToMock", argument1, argument2) to expect the method call tonameOfTheMethodToMock with arguments argument1 and argument2. • Use PowerMock.replay(mockObject) to change the mock object to replay mode. • Use PowerMock.verify(mockObject) to change the mock object to verify mode.
  • 9. Mocking static methods • Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case. • Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case. • Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class. • Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode. • Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.
  • 10. MockFinal • Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case. • Use the @PrepareForTest(ClassWithFinal.class) annotation at the class-level of the test case. • Use PowerMock.createMock(ClassWithFinal.class) to create a mock object for all methods of this class (let's call it mockObject). • Use PowerMock.replay(mockObject) to change the mock object to replay mode. • Use PowerMock.verify(mockObject) to change the mock object to verify mode.
  • 11. Mocking static methods • Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case. • Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case. • Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class. • Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode. • Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.
  • 12. For more info: m@piyushmittal.com