The document discusses JUnit, a unit testing framework for Java. It provides an example of using JUnit to test a class called StaticCalculation that performs basic math operations like addition and multiplication. The tests check that the operations return the expected values. It also discusses how to create JUnit tests in Eclipse and integrate test cases into source code files.
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
A presentation on JUnit Pioneer given at Fortitude Technologies on Mar. 4, 2021. JUnit Pioneer is an extension library for JUnit 5 (Jupiter).
Sample code on GitHub at:
https://github.com/sleberknight/junit-pioneering-presentation-code
JUnit Pioneer home page:
https://junit-pioneer.org
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
A presentation on JUnit Pioneer given at Fortitude Technologies on Mar. 4, 2021. JUnit Pioneer is an extension library for JUnit 5 (Jupiter).
Sample code on GitHub at:
https://github.com/sleberknight/junit-pioneering-presentation-code
JUnit Pioneer home page:
https://junit-pioneer.org
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.
For informative discussions on software testing please see. http://forum.360logica.com/
Please see description below
360logica is an independent software and application testing services company which provides wide range of testing solutions to our partners based on domain, technology and business solutions including software product testing, quality assurance of software, automation in testing, finance testing, mobile software and applications testing. 360logica offers full range of software testing which include Software Product Testing, Test Automation, Performance Test Engineering, Finance Application Testing, Healthcare App Testing and SaaS Product Testing. We work closely with our partners to tailor a program of support which meets their needs and ensures our systems achieve the quality levels demanded by our partners, especially in financial testing.
Sample Chapter of Practical Unit Testing with TestNG and MockitoTomek Kaczanowski
This is Chapter 10 of "Practical Unit Testing with TestNG and Mockito" book.
This is one of the last chapters which explains how to make your unit tests manageable, so they do not become a burden as the project develops and changes are introduced.
You can learn more about the book on http://practicalunittesting.com.
Slides from my Confitura 2012 presentation. The issues discussed during the talk will be described in my new (free!) ebook - see https://github.com/tomekkaczanowski/bad-tests-good-tests
IT Talk in Odessa for QA Automation/SDET engineers on 26/12/2016:
https://dou.ua/calendar/13626/
https://dataart.ru/events/odessa/it-talk-odessa-testng-vs-junit/
JUnit 4 code on github: https://github.com/a-oleynik/junit-workshop/tree/junit-4.13.2
TestNG code on github: https://github.com/a-oleynik/testng-workshop
Webinar on youtube (it was the next version but only a few slides and details were added): https://www.youtube.com/watch?v=3C-Nu5mkyOQ&t=3189
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
This document provides an over view of spring IOC and it's advantages. It also gives basic idea on the spring core container. At the last it describes how develop a simple spring application
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.
For informative discussions on software testing please see. http://forum.360logica.com/
Please see description below
360logica is an independent software and application testing services company which provides wide range of testing solutions to our partners based on domain, technology and business solutions including software product testing, quality assurance of software, automation in testing, finance testing, mobile software and applications testing. 360logica offers full range of software testing which include Software Product Testing, Test Automation, Performance Test Engineering, Finance Application Testing, Healthcare App Testing and SaaS Product Testing. We work closely with our partners to tailor a program of support which meets their needs and ensures our systems achieve the quality levels demanded by our partners, especially in financial testing.
Sample Chapter of Practical Unit Testing with TestNG and MockitoTomek Kaczanowski
This is Chapter 10 of "Practical Unit Testing with TestNG and Mockito" book.
This is one of the last chapters which explains how to make your unit tests manageable, so they do not become a burden as the project develops and changes are introduced.
You can learn more about the book on http://practicalunittesting.com.
Slides from my Confitura 2012 presentation. The issues discussed during the talk will be described in my new (free!) ebook - see https://github.com/tomekkaczanowski/bad-tests-good-tests
IT Talk in Odessa for QA Automation/SDET engineers on 26/12/2016:
https://dou.ua/calendar/13626/
https://dataart.ru/events/odessa/it-talk-odessa-testng-vs-junit/
JUnit 4 code on github: https://github.com/a-oleynik/junit-workshop/tree/junit-4.13.2
TestNG code on github: https://github.com/a-oleynik/testng-workshop
Webinar on youtube (it was the next version but only a few slides and details were added): https://www.youtube.com/watch?v=3C-Nu5mkyOQ&t=3189
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
Spring IOC advantages and developing spring application sample Sunil kumar Mohanty
This document provides an over view of spring IOC and it's advantages. It also gives basic idea on the spring core container. At the last it describes how develop a simple spring application
This session describes the overview on different types of spring containers. Here we can also find simple examples showing the demo to instantiate the containers.
A Brief presentation on Containerisationsubhash_ae
A brief presentation on Containerisation , the advent of Containerisation , use of marine containers to carry cargo across the oceans , description and types of marine containers , technical details of the marine containers etc. etc.
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
This presentation describes the some of the major functionality of JUnit4 and TestNG .Each topic contains example so that a viewer can understand the usage and apply them in their code.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
How world-class product teams are winning in the AI era by CEO and Founder, P...
Junit With Eclipse
1. JUnit
Use of JUnit for Java Unit Testing in Eclipse
Introduction to Unit Testing
Unit Testing is concerned about testing individual programs to ascertain that each program runs as per specification.
Prior to systematic unit testing framework, programmers tends to write test expressions which print to the console
or a trace file (the amount of output is sometimes controlled by a trace-level or debug-level flag). This approach is
not satisfactory because it requires human judgment to analyze the results produced. Too many print statements
cause the headache
JDK 1.4 provides an assertion feature (read Assertion), which enables you to test your assumptions about your
program logic (such as pre-conditions, post-conditions, and invariants). Nonetheless, assertion is primitive compared
with the unit testing framework.
With a proper Unit Testing framework, you can automate the entire unit testing process. Your job becomes
designing proper test cases to excite the program. Furthermore, the unit testing process can be integrated into the
build process. In this case, the build process not only checks for syntax errors, but semantic errors as well.
Extreme programming (www.xprogramming.com) advocates "write test first, before writing codes".
JUnit
JUnit is a Java Unit Testing Framework. It is the default standard for Java Unit Testing. JUnit is an open-source
project @ http://www.junit.org. JUnit is not included in JDK, but included in most of the IDEs such as Eclipse and
NetBeans.
Installing JUnit: Goto www.junit.org ⇒ "Download JUnit" ⇒ "junit4.x.x.zip" (which includes executable jar
files, source, and documentation), or "junit4.x.x.jar" (if you only want the executable) ⇒ Unzip.
Using JUnit: To use the JUnit, include JUnit jar-file "junit4.x.x.zip" in your CLASSPATH.
// set CLASSPATH for this command session only (set permanently via control
panel) prompt> set CLASSPATH=.;$JUNIT_HOMEjunit4.x.x.jar
// You can also compile/run with classpath option
prompt> javac -classpath .;$JUNIT_HOMEjunit4.x.x.jar test.java
prompt> java -classpath .;$JUNIT_HOMEjunit4.x.x.jar test
Read: Read "Getting Started" at www.junit.org. The JUnit's "doc" directory contains the documentation, and "junit"
contains samples.
JUnit 4
There are two versions of JUnit, version 3 and version 4, which are radically different. JUnit 4 uses the annotation
feature (since JDK 1.5) to streamline the process and drop the strict naming conventions.
Let's Get Started with an Example
The following program uses staticmethods to operate on two numbers.
public class StaticCalculation {
public static int add(int number1, int number2)
{
return number1 + number2;
2. }
public static int sub(int number1, int number2)
{ return number1 - number2;
}
public static int mul(int number1, int number2)
{ return number1 * number2;
}
public static int div(int number1, int number2)
{ return number1 / number2;
}
}
Use JUnit to write test cases to test all the methods.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StaticCalculationTest {
@Test
public void addSubTest() {
// assertEquals(String message, long expected, long actual)
assertEquals("Error in add()!", 3, StaticCalculation.add(1, 2));
assertEquals("Error in sub()!", 1, StaticCalculation.sub(2, 1));
}
@Test
public void mulDivTest() {
assertEquals("Error in mul()!", 6, StaticCalculation.mul(2, 3));
// assertEquals(String message, double expected, double actual, double delta)
assertEquals("Error in div()!", 0.5, StaticCalculation.div(1, 2), 1e-8);
}
}
Methods marked by annotation @org.junit.Test are JUnit's test cases. Inside the test cases, we could use
assertEquals(), assertTrue(), assertFalse(), assertNull(), assertNotNull(), assertSame(),
assertNotSame(), assertThat()to compare the actual result of an operation under test with an expected result.
They are all static methods in org.junit.Assertclass.
Take note that we separate 4 assertions in two test cases (for illustration). For the last assertion for div(), we
mistakenly assume that 1/2 = 0.5.
JUnit provides a console-version of test-runner org.junit.runner.JUnitCorefor you to run the tests under
command shell, with the following syntax:
prompt> java org.junit.runner.JUnitCore TestClass1 [TestClass2 ...]
You can also run the test from you Java program, using this statement:
org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);
For example, to run our test program:
// Set CLASSPATH to include JUnit
prompt> set classpath=.;D:xxxxxxjunit-4.8.2.jar
// Run test cases, using the JUnit console run-runner JUnitCore
prompt> java org.junit.runner.JUnitCore StaticCalculationTest
JUnit version 4.8.2
..E
Time: 0.008
There was 1 failure:
1) mulDivTest(StaticCalculationTest)
java.lang.AssertionError: Error in div()! expected:<0.5> but was:<0.0>
......
FAILURES!!!
Tests run: 2, Failures: 1
Observe that the unit test caught the error 1/2 = 0.5. In this case, it could be an error in the test case, or an
3. incorrect assumption in the program under test.
JUnit under Eclipse
To create a test case under Eclipse: "File" ⇒ "New" ⇒ "JUnit Test Case" ⇒ the "New JUnit Test Case" dialog appears.
Select "New JUnit 4 Test", and enter the class name StaticCalculationTest.
To run the test: Right-click ⇒ "Run As" ⇒ "JUnit Test". The results are shown in the JUnit console.
Integrating Test Cases into Source Code
Instead of writing a separate class for test cases, we can integrated them into the source code (not sure whether
recommended, as you might not want to include the test cases in production). For example,
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StaticCalculation {
public static int add(int number1, int number2)
{ return number1 + number2;
}
public static int sub(int number1, int number2)
{ return number1 - number2;
}
public static int mul(int number1, int number2)
{ return number1 * number2;
}
public static int div(int number1, int number2)
{ return number1 / number2;
}
public static void main(String[] args) {
System.out.println("1/2 is " + div(1, 2) + ", and is not 0.5");
}
// Integrate test case inside the source
@Test
public void unitTest() {
// assertEquals(String message, long expected, long actual)
assertEquals("Error in add()!", 3, StaticCalculation.add(1, 2));
assertEquals("Error in sub()!", 1, StaticCalculation.sub(2, 1));
assertEquals("Error in mul()!", 6, StaticCalculation.mul(2, 3));
// assertEquals(String message, double expected, double actual, double delta)
assertEquals("Error in div()!", 0.5, StaticCalcul ation.div(1, 2), 1e-8);
}
}
You can run the above program normally, starting at main(); or use test-runner to run the test cases.
Test Methods and Test Fixtures
Test Methods: A test methods is annotated with @Test. Inside a test method, you can use a variation of the
static assert method from org.junit.Assert(e.g., assertTrue(), assertFalse(), assertEquals() to
compare the expected and actual results.
Test Fixture: The set of objects that a test method operates on. You declare these objects as private variables.
You could initialize them via a public method annotated with @Before, and perform clean-up with a public
method annotated with @After. Each test method runs on its own set of text fixtures. This ensures isolation
between the test methods. Two other method annotations, @BeforeClassand @AfterClass, are available,
which run the annotated method once before the class and after the class.
Let's rewrite our earlier example in object instead of static methods, to illustrate the test fixture.
public class MyNumber {
4. private int number;
public MyNumber(int number) { // Constructor
this.number = number;
}
public int getNumber()
{ return number;
}
public MyNumber add(MyNumber another) {
return new MyNumber(this.number + another.number);
}
public MyNumber sub(MyNumber another) {
return new MyNumber(this.number - another.number);
}
}
The JUnit test program is as follows:
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class MyNumberTest {
private MyNumber number1, number2; // Test fixtures
// Initialize the test fixtures for EACH test
@Before
public void setup() { number1
= new MyNumber(2); number2
= new MyNumber(1);
}
@Test
public void addTest() {
assertEquals("Error in add()!", 3, number1.add(number2).getNumber());
}
@Test
public void subTest() {
assertEquals("Error in sub()!", 1, number1.sub(number2).getNumber());
}
}
Again, you could use the JUnit console test-runner or Eclipse to run the tests.
Another Example:
import org.junit.*;
import java.util.ArrayList;
import org.junit.runner.Result;
public class ArrayListTest {
private ArrayList<String> lst; // Test fixtures
// Initialize test fixtures before each test
method @Before
public void init() throws Exception
{ lst = new ArrayList<String>();
lst.add("alpha"); // at index 0
lst.add("beta"); // at index 1
}
// Test method to test the insert
operation @Test
public void insertTest() {
// assertEquals(String message, long expected, long
actual) Assert.assertEquals("wrong size", 2, lst.size());
lst.add(1, "charlie");
5. Assert.assertEquals("wrong size", 3, lst.size());
// assertEquals(String message, Object expected, Object actual)
// Use String.equals() for comparison
Assert.assertEquals("wrong element", "alpha", lst.get(0));
Assert.assertEquals("wrong element", "charlie", lst.get(1));
Assert.assertEquals("wrong element", "beta", lst.get(2));
}
// Test method to test the replace
operation @Test
public void replaceTest() {
Assert.assertEquals("wrong size", 2, lst.size());
lst.set(1, "charlie"); Assert.assertEquals("wrong
size", 2, lst.size());
Assert.assertEquals("wrong element", "alpha", lst.get(0));
Assert.assertEquals("wrong element", "charlie", lst.get(1));
}
public static void main(String[] args) {
Result r = org.junit.runner.JUnitCore.runClasses(ArrayListTest.class);
System.out.println(r.wasSuccessful());
}
}
To run the test, you can either include a main()method as above, or use the command-line.
JUnit Package org.junit
The core package for JUnit 4 is org.unit, which is simple and elegantly designed.
Assertclass: contains staticmethods assertEquals(), assertTrue(), assertFalse(), assertNull(),
assertNotNull(), assertSame(), assertNotSame(), assertThat(), assertArrayEquals().
Assume class: contains static methods assumeTrue(), assumeNotNull(), assumeThat(),
assumeNoException().
@Test: mark the method as a test method.
@Test(expected=IOException.class): The test is expected to trigger this exception.
@Test(timeout=1000): Treat the test as fail, if it exceeds the specified milliseconds.
@Beforeand @After: mark the method as to be run before and after EACH test method, for initializing and
cleaning-up test fixtures.
@BeforeClassand @AfterClass: mark the method as to be run before and after ONCE for the class.
@Ignore: ignore this test method (annotated with @Test). For example,
@Ignore("Under
Construction") @Test
public void someTest() {
......
}
@Rule:
Writing Generic Tests with Parameters
Writing Test Cases
How to test a program to ensure correctly? There are two techniques: white-box testing and black-box testing.
White-box testing inspect the program codes and test the program logic. Black-box testing does not inspect the
program codes, but looking at the input-output, treating the program as a black box.
For black-box testing, the most common approach is to partition the inputs, and design test cases for each input
partition. The test cases could test on a typical input value as well as the boundaries.
For example, the following program converts a given mark (0-100) to a letter grade ('A' to 'F'). There is a logical error
6. import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StaticGrade {
// Convert given mark into letter grade
// Assume that mark is between 0 and 100 (inclusive)
public static char getLetterGrade(int mark) {
// Assert is disabled by default,
// To enable, run with option –enableassertions (or –ea)
assert (mark >= 0 && mark <= 100) : "mark is out-of-range: " + mark;
if (mark >= 75) {
return 'A';
} else if (mark >= 60) {
return 'B';
} else if (mark > 50) { // an logical error here
return 'C';
} else {
return 'F';
}
}
// Test a typical value in each partition
@Test
public void testTypical() {
assertEquals("wrong grade", 'A', StaticGrade.getLetterGrade(95));
assertEquals("wrong grade", 'B', StaticGrade.getLetterGrade(72));
assertEquals("wrong grade", 'C', StaticGrade.getLetterGrade(55));
assertEquals("wrong grade", 'F', StaticGrade.getLetterGrade(30));
}
// Test the boundaries of the each partition
@Test
public void testBoundaries() {
assertEquals("wrong grade", 'A', StaticGrade.getLetterGrade(75));
assertEquals("wrong grade", 'A', StaticGrade.getLetterGrade(100));
assertEquals("wrong grade", 'B', StaticGrade.getLetterGrade(60));
assertEquals("wrong grade", 'B', StaticGrade.getLetterGrade(74));
assertEquals("wrong grade", 'C', StaticGrade.getLetterGrade(50));
assertEquals("wrong grade", 'C', StaticGrade.getLetterGrade(59));
assertEquals("wrong grade", 'F', StaticGrade.getLetterGrade(0));
assertEquals("wrong grade", 'F', StaticGrade.getLetterGrade(49));
}
}
Try to run the above tests to find the logical error. Take note that assertEquals()does not accept char as arguments,
but upcast to long. That is, the output show the char's numeric code.
JUnit 3.8
JUnit 3.8, which uses strict naming convention to denote various entities, is probably outdated. I suggest that you
move to JUnit 4, which is more intuitive by using annotation.
Let's begin with an Example
Below is a Java program to be tested. Note that there is a logical error in the program.
1 public class Grade {
2 public static char getLetterGrade(int mark) {
3 // assume that mark is between 0 and 100 (inclusive)
4 assert (mark >= 0 && mark <= 100) : "mark is out -of-range: " + mark;
5 if (mark >= 75) {
6 return 'A';
7 } else if (mark >= 60) {
8 return 'B';
9 } else if (mark > 50) {// an logical error here
7. 10 return 'C';
11 } else {
12 return 'F';
13 }
14 }
15 }
The unit-test program (using JUnit framework) is as follows. Black-box test cases are set up to test typical values as
well as boundary values.
1 import junit.framework.Test;
2 import junit.framework.TestCase;
3 import junit.framework.TestSuite;
4
5 public class GradeUnitTest extends TestCase {
6
7 public GradeUnitTest(String name) { super(name); }
8 protected void setUp() throws Exception { super.setUp(); }
9 protected void tearDown() throws Exception { super.tearDown(); }
10
11 public void testTypical() { // test a typical value in partitions
12 assertEquals("wrong grade", 'A', Grade.getLetterGrade(95));
13 assertEquals("wrong grade", 'B', Grade.getLetterGrade(72));
14 assertEquals("wrong grade", 'C', Grade.getLetterGrade(55));
15 assertEquals("wrong grade", 'F', Grade.getLetterGrade(30));
16 }
17
18 public void testBoundaries() { // test the boundaries of the partitions
19 assertEquals("wrong grade", 'A', Grade.getLetterGrade(75));
20 assertEquals("wrong grade", 'A', Grade.getLetterGrade(100));
21 assertEquals("wrong grade", 'B', Grade.getLetterGrade(60));
22 assertEquals("wrong grade", 'B', Grade.getLetterGrade(74));
23 assertEquals("wrong grade", 'C', Grade.getLetterGrade(50));
24 assertEquals("wrong grade", 'C', Grade.getLetterGrade(59));
25 assertEquals("wrong grade", 'F', Grade.getLetterGrade(0));
26 assertEquals("wrong grade", 'F', Grade.getLetterGrade(49));
27 }
28
29 public static Test suite() { // For putting into a TestSuite.
30
return new TestSuite(GradeUnitTest.class);
31 }
32
33 public static void main(String[] args) {
34 junit.textui.TestRunner.run(GradeUnitTest.class);
35 }
36 }
Compile and execute the program (with JUnit JAR file included in the CLASSPATH) as follows. Note that one of
the unit-test cases catches the logical error.
> javac -cp .;c:junitjunit-3.8.2.jar GradeUnitTest.java
> java -cp .;c:junitjunit-3.8.2.jar GradeUnitTest
..F
Time: 0.006
There was 1 failure:
1) testBoundaries(GradeUnitTest)junit.framework.AssertionFailedError: wrong grade expected:<C>
but was:<F> at GradeUnitTest.testBoundaries(GradeUnitTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at GradeUnitTest.main(GradeUnitTest.java:34)
FAILURES!!!
Tests run: 2, Failures: 1, Errors: 0
JUnit Terminology
Class TestCase: A class that contains test methods should derive from this superclass. Each TestCase can
include many test methods.
8. Test Methods: A test methods must be named testXxx(). This is because JUnit uses the reflection
mechanism to find and run these methods. Inside a test method, you can use a variation of the
assert()method (e.g., assertTrue(), assertFalse(), assertEquals() to compare the expected
and actual results.
Test Fixture: The set of objects that a test method operates on. You declare these objects as a private
variable, and initialize them by overriding the setUp()or via the constructor. You can perform clean-up
operations by overriding tearDown(). Each test method runs on its own TestCaseinstance with its own
set of text fixtures. This ensures isolation between the test methods.
Class TestSuite: You can combine many TestCases(e.g., written by different person) into a test suite,
and run them at once.
Class TestRunner: for running the TestCaseor TestSuite.
Writing Tests
Step 1: Extend a subclass of junit.framework.TestCase:
import junit.framework.*;
public class JUnit38DemoArrayList extends TestCase {
public JUnit38DemoArrayList(String name) { super(name); } // constructor
}
Step 2: If two or more test methods use a common set of test objects (called test fixtures), declare the test
fixtures as instance variables. For example, suppose we are testing the class ArrayList.
private ArrayList<String> lst; // declare test fixture instance.
Step 3: Initialize the text fixture. You can override setUp()or use the constructor. Each test method runs on
its own TestCase instance. This provides isolation between test methods. Each test method invoke the
constructor to construct an instance of the TestCase, followed by setUp(), run the steps coded inside the
test method, and the tearDown() before exiting. The test methods may run concurrently. For example, let's
initialize our test fixture ArrayListwith two Stringelements.
// Initialize the test fixture used by all the test
methods protected void setUp() throws Exception {
lst = new ArrayList<String>();
lst.add("alpha"); // at index 0
lst.add("beta"); // at index 1
}
protected void tearDown() throws Exception { super.tearDown(); } // for clean-up operation
Step 4: Write the test methods for this TestCase. All the test methods must be named testXxx(), as JUnit uses
reflection to find these test methods. For example,
// test method to test the insert
operation public void testInsert() {
assertEquals("wrong size", 2, lst.size()); // error message, expected,
actual lst.add(1, "charlie");
assertEquals("wrong size", 3, lst.size());
assertEquals("wrong element", "alpha", lst.get(0));
assertEquals("wrong element", "charlie", lst.get(1));
assertEquals("wrong element", "beta", lst.get(2));
}
// test method to test the replace
operation public void testReplace() {
assertEquals("wrong size", 2, lst.size());
lst.set(1, "charlie"); assertEquals("wrong
size", 2, lst.size());
assertEquals("wrong element", "alpha", lst.get(0));
assertEquals("wrong element", "charlie", lst.get(1));
}
Step 5: You can now run the TestCase, using JUnit-provided TestRunner. There are two versions of TestRunner:
text-based junit.textui.TestRunner, and GUI-based junit.swingui.TestRunner. To use the text-based
TestRunner, you could include a main()method as follows:
public static void main(String[] args) {
junit.textui.TestRunner.run(JUnit38DemoArrayList.class);
}
9. The expected outputs are:
..
Time: 0.001
OK (2 tests)
You can also invoke the TestRunnerfrom command-line:
> java junit.textui.TestRunner JUnit38DemoArrayList
You can invoke the GUI-based TestRunnerfrom command-line:
> java junit.swingui.TestRunner JUnit38DemoArrayList
Step 6: If there are many TestCases (could be written by different people), you can put them together into a
TestSuite and run all the TestCases at once. To do so, in each of the TestCases, create a static method
suite()to extract all the test methods as follows:
// In JUnit38DemoArrayList Class - do the same for other TestCase
classes public static Test suite() {
return new TestSuite(JUnit38DemoArrayList.class);
}
Next, write a class to include all the TestCases into a TestSuite.
import
java.framework.*;
public class AllTests {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() { TestSuite
suite = new TestSuite();
suite.addTest(JUnit38DemoArrayList.suite());
// other TestCase classes
//suite.addTest(OtherTestCase1.suite());
//suite.addTest(OtherTestCase2.suite());
return suite;
}
}
REFERENCES & RESOURCES
JUnit mother site @ www.junit.org.
JUnit API documentation @ http://junit.sourceforge.net/javadoc_40.
Kent Beck and Erich Gamma, "JUnit Cookbook" @ http://junit.sourceforge.net/doc/cookbook/cookbook.htm.
JUnit A Cook's Tour (for JUnit 3.8) @ http://junit.sourceforge.net/doc/cookstour/cookstour.htm.