SlideShare a Scribd company logo
Unit tests: testing individual methods (low-level)
Integration tests: interaction with the database or making sure that microservices work together as expected
Functional tests: only verify the output of an action and do not check the intermediate states
End-to-end tests: more complex scenarios verifying email notifications, online payments (high-level)
Acceptance testing: replicating user behaviors (entire application)
Performance testing: behaviors of the system when it is under significant load
Smoke testing: after a deployment to make sure that they application is running properly
...
...
...
TestNG: Unit testing
Cucumber: Integration testing
Robot Framework: Acceptance testing
Mockito: PowerMock/JMock ...
Selenium: Acceptance testing
"Test" suffix at the end of test classes names.
a test name should explain what the test does
Given[ExplainYourInput]When[WhatIsDone]Then[ExpectedResult]
You should use the "Test" suffix for test classes. The Maven automatically includes such classes in its test scope
JUnit assumes that all test methods can be executed in an arbitrary order.
- test code should not assume any order,
- tests should not depend on other tests.
annotation.
@Test : Declares a test method @Test(timeout=2000)
@BeforeClass - @BeforeAll : method will be executed before all test methods
@AfterClass - @AfterAll : method will be executed after all test methods
@Before - @BeforeEach : method will be executed before each test method
@After- @AfterEach : method will be executed after each test method
@Ignore- @Disable : Disable a test method or a test class
@Category- @Tag : Declare tags for filtering tests
fail : Let the method fail.
assertTrue : (message , condition) Checks that the boolean condition is true.
assertFalse : (message , condition) Checks that the boolean condition is false.
assertEquals : (message , expected, actual) Tests that two values are the same.
assertEquals : (message , expected, actual , tolerance) float or double values match
assertNull : (message , object) Checks that the object is null.
assertNotNull
assertSame : (message , expected, actual) Checks that both variables refer to the same
object.assertNotSame :
assertThat : (actual, matcher) Checks that with CoreMatchers. *****
any(): Matches any object passed to it.
is(): A matcher that checks if the given objects are equal.
describeAs(): adds a description to the matcher
allOf(): Takes an array of matchers and must all match the expected object.
anyOf(): Takes an array of matcher and must match at least one of the matchers must report that it matches the target object.
not(): Check if the object negates what was passed.
equalTo(): Equality check.
instanceOf(): Check if an object is an instance of a given/expected object.
notNullValue(): Check if the passed value is not null
sameInstance(): Tests if the given object is the exact same instance as another.
CoreLogicalObject
Java Unit Test - JUnit
• If you have several test classes, you can combine them
into a test suite.
• Running a test suite executes all test classes in that
suite in the specified order.
• A test suite can also contain other test suites.
Java Unit Test - JUnit
• You can add behavior to each tests in a test class.
• This adds more flexibility to your tests.
• for example, specify which exception message you expect during the execution of your test code.
• For example, the TemporaryFolder class allows to setup files and folders which are automatically removed
after each test run.
https://github.com/junit-team/junit4/wiki/Rules
Assert.assertEquals == assertEquals
Java Unit Test - JUnit
You don't write many unit tests for each
method and cover all code paths, also you
can't test all possible inputs.
But instead will want to test a variety of types
of inputs such as negative, positive, large and
small values, object's size and so on
There are quite a few ways of tackling tests for units
dealing with databases. Some of which are frowned
upon, though, such as pointing directly to the any
database.
Java Unit Test - JUnit
• For example, when testing service layer, we should don't care about the data flow in unit testing.
• Or when testing controller, we should don't care about how integrate with service layer in unit testing.
A mock object is a dummy implementation for an interface or a class in which you define the output of
certain method calls. Mock objects are configured to perform a certain behavior during a test. They
typically record the interaction with the system and tests can validate that.
UserController --> UserService --> UserDAO
Mockito is a test framework with mock, stub and spy features.
• Use annotation to minimize repetitive mock/spy creation code.
• Use annotation to make the test more readable.
Java Unit Test - JUnit
This is an object that has no implementation
which is used purely to populate arguments of
method calls which are irrelevant to your test.
For example, the code below uses a lot of code to
create the customer which is not important to
the test.
The test couldn't care less which customer is
added, as long as the customer count comes back
as one.
The role of the test stub is to return controlled values to the object being tested.
These are described as indirect inputs to the test.
A saboteur is used to test exceptional behaviour.
Mock objects are used to verify object behaviour during a test.
This is very different to the supporting role of a stub which is used to provide results to whatever you are testing.
In a stub we use the pattern of defining a return value for a method.
In a mock we check the behaviour of the object using the following form.
Java Unit Test - JUnit
MVC & Code Coverage Example

More Related Content

PPT
New Features Of Test Unit 2.x
djberg96
 
PDF
All about unit testing using (power) mock
Pranalee Rokde
 
PDF
Workshop unit test
Francesco Garavaglia
 
PPTX
Introduction to JUnit
Devvrat Shukla
 
PPTX
Unit testing
Pooya Sagharchiha
 
PDF
Unit testing in xcode 8 with swift
allanh0526
 
PPTX
Tdd & unit test
GomathiNayagam S
 
New Features Of Test Unit 2.x
djberg96
 
All about unit testing using (power) mock
Pranalee Rokde
 
Workshop unit test
Francesco Garavaglia
 
Introduction to JUnit
Devvrat Shukla
 
Unit testing
Pooya Sagharchiha
 
Unit testing in xcode 8 with swift
allanh0526
 
Tdd & unit test
GomathiNayagam S
 

What's hot (20)

PPTX
Mocking with Moq
Mohamed Elkhodary
 
PDF
Writing good unit test
Lucy Lu
 
PDF
Unit testing with JUnit
Thomas Zimmermann
 
PPTX
Power mock
Piyush Mittal
 
PPTX
Best practices unit testing
Tricode (part of Dept)
 
PPT
Unit testing
jeslie
 
PDF
Unit test documentation
Anjan Debnath
 
PPTX
Java Unit Testing
Nayanda Haberty
 
PDF
JUnit & Mockito, first steps
Renato Primavera
 
PPTX
Junit 4.0
pallavikhandekar212
 
DOCX
Comp 220 ilab 5 of 7
ashhadiqbal
 
PPTX
Presentation
Igor Vlahek
 
PDF
Unit test-using-spock in Grails
NexThoughts Technologies
 
PPT
Simple Unit Testing With Netbeans 6.1
Kiki Ahmadi
 
PPTX
Grails Spock Testing
TO THE NEW | Technology
 
PPTX
.Net Unit Testing with Visual Studio 2010
kgayda
 
PDF
Unit Testing Fundamentals
Richard Paul
 
PPT
testng
harithakannan
 
PPT
05 junit
mha4
 
PDF
Unit testing best practices
nickokiss
 
Mocking with Moq
Mohamed Elkhodary
 
Writing good unit test
Lucy Lu
 
Unit testing with JUnit
Thomas Zimmermann
 
Power mock
Piyush Mittal
 
Best practices unit testing
Tricode (part of Dept)
 
Unit testing
jeslie
 
Unit test documentation
Anjan Debnath
 
Java Unit Testing
Nayanda Haberty
 
JUnit & Mockito, first steps
Renato Primavera
 
Comp 220 ilab 5 of 7
ashhadiqbal
 
Presentation
Igor Vlahek
 
Unit test-using-spock in Grails
NexThoughts Technologies
 
Simple Unit Testing With Netbeans 6.1
Kiki Ahmadi
 
Grails Spock Testing
TO THE NEW | Technology
 
.Net Unit Testing with Visual Studio 2010
kgayda
 
Unit Testing Fundamentals
Richard Paul
 
05 junit
mha4
 
Unit testing best practices
nickokiss
 
Ad

Similar to Java Unit Test - JUnit (20)

PPTX
Unit Testing in Java
Ahmed M. Gomaa
 
PPTX
Testing And Mxunit In ColdFusion
Denard Springle IV
 
PPT
Chapter 3 SOFTWARE TESTING PROCESS
st. michael
 
PDF
Unit testing basic
Yuri Anischenko
 
PPTX
Angular Unit Testing
Alessandro Giorgetti
 
PPTX
unit 1 (1).pptx
SumitKumar918321
 
PDF
Effective Unit Testing
Narendra Pathai
 
PPTX
Object Oriented Testing Strategy.pptx
ZakriyaMalik2
 
PPTX
Mocking with Mockito
Paul Churchward
 
PPTX
Intro To Unit and integration Testing
Paul Churchward
 
PDF
Software Testing
AdroitLogic
 
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
PPT
Md04 flow control
Rakesh Madugula
 
PPTX
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
PDF
Unit Testing & TDD Training for Mobile Apps
Marcelo Busico
 
PPT
Assessing Unit Test Quality
guest268ee8
 
PDF
Effective Unit Test Style Guide
Jacky Lai
 
PPT
Software Testing
Kiran Kumar
 
PPT
Qtp Training
mehramit
 
Unit Testing in Java
Ahmed M. Gomaa
 
Testing And Mxunit In ColdFusion
Denard Springle IV
 
Chapter 3 SOFTWARE TESTING PROCESS
st. michael
 
Unit testing basic
Yuri Anischenko
 
Angular Unit Testing
Alessandro Giorgetti
 
unit 1 (1).pptx
SumitKumar918321
 
Effective Unit Testing
Narendra Pathai
 
Object Oriented Testing Strategy.pptx
ZakriyaMalik2
 
Mocking with Mockito
Paul Churchward
 
Intro To Unit and integration Testing
Paul Churchward
 
Software Testing
AdroitLogic
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Md04 flow control
Rakesh Madugula
 
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
Unit Testing & TDD Training for Mobile Apps
Marcelo Busico
 
Assessing Unit Test Quality
guest268ee8
 
Effective Unit Test Style Guide
Jacky Lai
 
Software Testing
Kiran Kumar
 
Qtp Training
mehramit
 
Ad

Recently uploaded (20)

PDF
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PDF
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Salesforce Implementation Services Provider.pdf
VALiNTRY360
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Presentation about variables and constant.pptx
kr2589474
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
10 posting ideas for community engagement with AI prompts
Pankaj Taneja
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 

Java Unit Test - JUnit

  • 1. Unit tests: testing individual methods (low-level) Integration tests: interaction with the database or making sure that microservices work together as expected Functional tests: only verify the output of an action and do not check the intermediate states End-to-end tests: more complex scenarios verifying email notifications, online payments (high-level) Acceptance testing: replicating user behaviors (entire application) Performance testing: behaviors of the system when it is under significant load Smoke testing: after a deployment to make sure that they application is running properly ... ... ...
  • 2. TestNG: Unit testing Cucumber: Integration testing Robot Framework: Acceptance testing Mockito: PowerMock/JMock ... Selenium: Acceptance testing
  • 3. "Test" suffix at the end of test classes names. a test name should explain what the test does Given[ExplainYourInput]When[WhatIsDone]Then[ExpectedResult] You should use the "Test" suffix for test classes. The Maven automatically includes such classes in its test scope
  • 4. JUnit assumes that all test methods can be executed in an arbitrary order. - test code should not assume any order, - tests should not depend on other tests. annotation.
  • 5. @Test : Declares a test method @Test(timeout=2000) @BeforeClass - @BeforeAll : method will be executed before all test methods @AfterClass - @AfterAll : method will be executed after all test methods @Before - @BeforeEach : method will be executed before each test method @After- @AfterEach : method will be executed after each test method @Ignore- @Disable : Disable a test method or a test class @Category- @Tag : Declare tags for filtering tests
  • 6. fail : Let the method fail. assertTrue : (message , condition) Checks that the boolean condition is true. assertFalse : (message , condition) Checks that the boolean condition is false. assertEquals : (message , expected, actual) Tests that two values are the same. assertEquals : (message , expected, actual , tolerance) float or double values match assertNull : (message , object) Checks that the object is null. assertNotNull assertSame : (message , expected, actual) Checks that both variables refer to the same object.assertNotSame : assertThat : (actual, matcher) Checks that with CoreMatchers. *****
  • 7. any(): Matches any object passed to it. is(): A matcher that checks if the given objects are equal. describeAs(): adds a description to the matcher allOf(): Takes an array of matchers and must all match the expected object. anyOf(): Takes an array of matcher and must match at least one of the matchers must report that it matches the target object. not(): Check if the object negates what was passed. equalTo(): Equality check. instanceOf(): Check if an object is an instance of a given/expected object. notNullValue(): Check if the passed value is not null sameInstance(): Tests if the given object is the exact same instance as another. CoreLogicalObject
  • 9. • If you have several test classes, you can combine them into a test suite. • Running a test suite executes all test classes in that suite in the specified order. • A test suite can also contain other test suites.
  • 11. • You can add behavior to each tests in a test class. • This adds more flexibility to your tests. • for example, specify which exception message you expect during the execution of your test code. • For example, the TemporaryFolder class allows to setup files and folders which are automatically removed after each test run. https://github.com/junit-team/junit4/wiki/Rules
  • 14. You don't write many unit tests for each method and cover all code paths, also you can't test all possible inputs. But instead will want to test a variety of types of inputs such as negative, positive, large and small values, object's size and so on
  • 15. There are quite a few ways of tackling tests for units dealing with databases. Some of which are frowned upon, though, such as pointing directly to the any database.
  • 17. • For example, when testing service layer, we should don't care about the data flow in unit testing. • Or when testing controller, we should don't care about how integrate with service layer in unit testing. A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls. Mock objects are configured to perform a certain behavior during a test. They typically record the interaction with the system and tests can validate that. UserController --> UserService --> UserDAO Mockito is a test framework with mock, stub and spy features.
  • 18. • Use annotation to minimize repetitive mock/spy creation code. • Use annotation to make the test more readable.
  • 20. This is an object that has no implementation which is used purely to populate arguments of method calls which are irrelevant to your test. For example, the code below uses a lot of code to create the customer which is not important to the test. The test couldn't care less which customer is added, as long as the customer count comes back as one.
  • 21. The role of the test stub is to return controlled values to the object being tested. These are described as indirect inputs to the test.
  • 22. A saboteur is used to test exceptional behaviour.
  • 23. Mock objects are used to verify object behaviour during a test. This is very different to the supporting role of a stub which is used to provide results to whatever you are testing. In a stub we use the pattern of defining a return value for a method. In a mock we check the behaviour of the object using the following form.
  • 25. MVC & Code Coverage Example

Editor's Notes

  • #3: Unit testin faydaları: Yazılan kodun her satırının başka bir kod (test kodu) tarafından otomatik olarak test edilmesini sağlar. Kodun anlaşılmasını kolaylaştırır. Daha hızlı yazılım geliştirmeyi sağlar.(Proje başlangıcında projeyi yavaşlatır gibi görünmekte fakat projenin ileri dönemlerinde ciddi bir zaman kazanımı sağlamaktadır) Koddaki hata oranını azaltır. Kodların kalitesinin artmasını sağlar. Hataların çabuk tespit edilip düzenlenmesini sağlar.
  • #7: Assert.assertTrue(EqualsBuilder.reflectionEquals(expected,actual)); [Commons Lang3] assertThat(actual).isEqualToComparingFieldByField(expected); [hamcrest]
  • #14: https://dzone.com/articles/unit-testing-patterns-common-patterns-to-follow-fo
  • #17: http://www.baeldung.com/mockito-mock-methods
  • #20: https://www.javaworld.com/article/2074508/core-java/mocks-and-stubs---understanding-test-doubles-with-mockito.html Fake Object = in-memory database or fake service layer.
  • #24: https://www.javaworld.com/article/2074508/core-java/mocks-and-stubs---understanding-test-doubles-with-mockito.html http://www.baeldung.com/mockito-verify