SlideShare a Scribd company logo
1 of 9
JUnit Testing Frameworks
for Developers
Srini Seetharaman
srini@sdnhub.org
March 2015
Goals
► OpenDaylight’s Integration project looks at the overall system
test, in some ways treating the controller like a blackbox
► Developers write white-box test cases that enable different
types of test and verification that will tie up with Jenkins
2
JUnit
► JUnit is the most common testing framework used
► Can cover logic within a single bundle, or multiple bundles
 Integrated with Maven through multiple plugins
 Other mock framework (e.g., Mockito and EasyMock) make testing even
easier with creating mock objects pre-programmed with expectation
3
JUnit Basic Annotations
Annotation Description
@Test
public void method()
The @Test annotation identifies a method as a test method.
@Test (expected = Exception.class) Fails if the method does not throw the named exception.
@Test(timeout=100) Fails if the method takes longer than 100 milliseconds.
@Before
public void method()
This method is executed before each test. It is used to prepare the test
environment (e.g., read input data, initialize the class).
@After
public void method()
This method is executed after each test. It is used to cleanup the test
environment (e.g., delete temporary data, restore defaults).
@BeforeClass
public static void method()
This static method is executed once, before the start of all tests. It is used to
perform time intensive activities, for example, to connect to a database.
@AfterClass
public static void method()
This static method is executed once, after all tests have been finished. It is used
to perform clean-up activities, for example, to disconnect from a database.
@Ignore Ignores the test method. This is useful when the underlying code has been
changed and the test case has not yet been adapted. Or if the execution time of
this test is too long to be included.
4
Three Maven Testing Plugins
1. Unit tests with SureFire plugin
 To verify if a certain feature is available
 If test fails, build breaks right away
 One maven goal:
► surefire:test
2. Integration tests with Fail-safe plugin
 Test multiple components
 Includes files with name IT*.java, *IT.java, *ITCase.java
 If test fails, cleans up state in a post-integration-test phase, but does not fail the build
 Two maven goals
► failsafe:integration-test runs the integration tests of an application
► failsafe:verify verifies that the integration tests of an application passed.
3. Integration tests with Pax-Exam plugin
 Tests cross-bundle interfaces and integrates with OSGi
 Can be used for spinning up virtual bundle container
5
JUnit Extended with Pax-Exam
► Spins up a test container with all dependencies injected
► Pax Exam JUnit test requires a method annotated with @Configuration
6
@RunWith(PaxExam.class)
public class SampleTest {
@Inject
private HelloService helloService;
@Configuration
public Option[] config() {
return options(
mavenBundle("com.example.myproject", "myproject-api", "1.0.0-SNAPSHOT"),
bundle("http://www.example.com/repository/foo-1.2.3.jar"),
junitBundles()
);
}
@Test
public void getHelloService() {
assertNotNull(helloService);
assertEquals("Hello Pax!", helloService.getMessage());
}
}
JUnit with Mockito
► In some cases, you don’t need to create a real object to test code.
► Using Mock objects Minimizes number of moving pieces tested
7
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
// assume there is a class MyDatabase
@Mock
MyDatabase databaseMock;
@Test
public void testQuery() {
// assume there is a class called ClassToTest
// which could be tested
ClassToTest t = new ClassToTest(databaseMock);
// call a method
boolean check = t.query("* from t");
// test the return type
assertTrue(check);
// test that the query() method on the
// mock object was called
Mockito.verify(databaseMock).query("* from t");
}
}
A more Concrete ODL example:
controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandlerTest
8
public class TopologyLinkDataChangeHandlerTest {
NetworkGraphService networkGraphService;
DataBrokerService dataBrokerService;
DataChangeEvent dataChangeEvent;
Topology topology;
Link link;
@Before
public void init() {
networkGraphService = mock(NetworkGraphService.class);
dataBrokerService = mock(DataBrokerService.class);
dataChangeEvent = mock(DataChangeEvent.class);
link = mock(Link.class);
topology = mock(Topology.class);
}
@Test
public void testOnDataChange() throws Exception {
TopologyLinkDataChangeHandler topologyLinkDataChangeHandler = new
TopologyLinkDataChangeHandler(dataBrokerService, networkGraphService, 2);
Map<InstanceIdentifier<?>, DataObject> original = new HashMap<InstanceIdentifier<?>, DataObject>();
when(dataChangeEvent.getOriginalOperationalData()).thenReturn(original);
InstanceIdentifier<?> instanceIdentifier = InstanceIdentifierUtils.generateTopologyInstanceIdentifier("flow:1");
Map<InstanceIdentifier<?>, DataObject> updated = new HashMap<InstanceIdentifier<?>, DataObject>();
DataObject dataObject = mock(DataObject.class);
updated.put(instanceIdentifier, dataObject);
when(dataChangeEvent.getUpdatedOperationalData()).thenReturn(updated);
when(dataBrokerService.readOperationalData(instanceIdentifier)).thenReturn(topology);
List<Link> links = new ArrayList<>();
links.add(link);
when(topology.getLink()).thenReturn(links);
topologyLinkDataChangeHandler.onDataChanged(dataChangeEvent);
Thread.sleep(2100);
verify(networkGraphService, times(1)).addLinks(links);
}
Setup data
Setup mock objects
Exercise
Verify
Sonar Code Coverage
► Sonar picks up testing results by using the JaCoCo plugin
► http://sonar.opendaylight.org/dashboard/index/45745?metric=it_coverage
9

More Related Content

What's hot

JUnit 5 - The Next Generation
JUnit 5 - The Next GenerationJUnit 5 - The Next Generation
JUnit 5 - The Next GenerationKostadin Golev
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introductionDenis Bazhin
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warOleksiy Rezchykov
 
X unit testing framework with c# and vs code
X unit testing framework with c# and vs codeX unit testing framework with c# and vs code
X unit testing framework with c# and vs codeShashank Tiwari
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management toolRenato Primavera
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG Greg.Helton
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleNoam Kfir
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Thomas Weller
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features PresentationShir Brass
 
Applying TDD to Legacy Code
Applying TDD to Legacy CodeApplying TDD to Legacy Code
Applying TDD to Legacy CodeAlexander Goida
 

What's hot (20)

Test ng
Test ngTest ng
Test ng
 
JUnit 5 - The Next Generation
JUnit 5 - The Next GenerationJUnit 5 - The Next Generation
JUnit 5 - The Next Generation
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
TestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the warTestNG vs JUnit: cease fire or the end of the war
TestNG vs JUnit: cease fire or the end of the war
 
TestNG with selenium
TestNG with seleniumTestNG with selenium
TestNG with selenium
 
Bug zillatestopiajenkins
Bug zillatestopiajenkinsBug zillatestopiajenkins
Bug zillatestopiajenkins
 
X unit testing framework with c# and vs code
X unit testing framework with c# and vs codeX unit testing framework with c# and vs code
X unit testing framework with c# and vs code
 
Test NG Framework Complete Walk Through
Test NG Framework Complete Walk ThroughTest NG Framework Complete Walk Through
Test NG Framework Complete Walk Through
 
Apache maven, a software project management tool
Apache maven, a software project management toolApache maven, a software project management tool
Apache maven, a software project management tool
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
NUnit Features Presentation
NUnit Features PresentationNUnit Features Presentation
NUnit Features Presentation
 
Applying TDD to Legacy Code
Applying TDD to Legacy CodeApplying TDD to Legacy Code
Applying TDD to Legacy Code
 

Similar to Introduction to JUnit testing in OpenDaylight (20)

Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
3 j unit
3 j unit3 j unit
3 j unit
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
L08 Unit Testing
L08 Unit TestingL08 Unit Testing
L08 Unit Testing
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
TestNG
TestNGTestNG
TestNG
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
JMockit
JMockitJMockit
JMockit
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit test
Unit testUnit test
Unit test
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 

More from OpenDaylight

OpenDaylight OpenFlow clustering
OpenDaylight OpenFlow clusteringOpenDaylight OpenFlow clustering
OpenDaylight OpenFlow clusteringOpenDaylight
 
Network Intent Composition in OpenDaylight
Network Intent Composition in OpenDaylightNetwork Intent Composition in OpenDaylight
Network Intent Composition in OpenDaylightOpenDaylight
 
OpenDaylight MD-SAL Clustering Explained
OpenDaylight MD-SAL Clustering ExplainedOpenDaylight MD-SAL Clustering Explained
OpenDaylight MD-SAL Clustering ExplainedOpenDaylight
 
ONOS Platform Architecture
ONOS Platform ArchitectureONOS Platform Architecture
ONOS Platform ArchitectureOpenDaylight
 
Security of OpenDaylight platform
Security of OpenDaylight platformSecurity of OpenDaylight platform
Security of OpenDaylight platformOpenDaylight
 
Using OVSDB and OpenFlow southbound plugins
Using OVSDB and OpenFlow southbound pluginsUsing OVSDB and OpenFlow southbound plugins
Using OVSDB and OpenFlow southbound pluginsOpenDaylight
 
Yang in ODL by Jan Medved
Yang in ODL by Jan MedvedYang in ODL by Jan Medved
Yang in ODL by Jan MedvedOpenDaylight
 

More from OpenDaylight (7)

OpenDaylight OpenFlow clustering
OpenDaylight OpenFlow clusteringOpenDaylight OpenFlow clustering
OpenDaylight OpenFlow clustering
 
Network Intent Composition in OpenDaylight
Network Intent Composition in OpenDaylightNetwork Intent Composition in OpenDaylight
Network Intent Composition in OpenDaylight
 
OpenDaylight MD-SAL Clustering Explained
OpenDaylight MD-SAL Clustering ExplainedOpenDaylight MD-SAL Clustering Explained
OpenDaylight MD-SAL Clustering Explained
 
ONOS Platform Architecture
ONOS Platform ArchitectureONOS Platform Architecture
ONOS Platform Architecture
 
Security of OpenDaylight platform
Security of OpenDaylight platformSecurity of OpenDaylight platform
Security of OpenDaylight platform
 
Using OVSDB and OpenFlow southbound plugins
Using OVSDB and OpenFlow southbound pluginsUsing OVSDB and OpenFlow southbound plugins
Using OVSDB and OpenFlow southbound plugins
 
Yang in ODL by Jan Medved
Yang in ODL by Jan MedvedYang in ODL by Jan Medved
Yang in ODL by Jan Medved
 

Recently uploaded

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Introduction to JUnit testing in OpenDaylight

  • 1. JUnit Testing Frameworks for Developers Srini Seetharaman srini@sdnhub.org March 2015
  • 2. Goals ► OpenDaylight’s Integration project looks at the overall system test, in some ways treating the controller like a blackbox ► Developers write white-box test cases that enable different types of test and verification that will tie up with Jenkins 2
  • 3. JUnit ► JUnit is the most common testing framework used ► Can cover logic within a single bundle, or multiple bundles  Integrated with Maven through multiple plugins  Other mock framework (e.g., Mockito and EasyMock) make testing even easier with creating mock objects pre-programmed with expectation 3
  • 4. JUnit Basic Annotations Annotation Description @Test public void method() The @Test annotation identifies a method as a test method. @Test (expected = Exception.class) Fails if the method does not throw the named exception. @Test(timeout=100) Fails if the method takes longer than 100 milliseconds. @Before public void method() This method is executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class). @After public void method() This method is executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults). @BeforeClass public static void method() This static method is executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. @AfterClass public static void method() This static method is executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. @Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included. 4
  • 5. Three Maven Testing Plugins 1. Unit tests with SureFire plugin  To verify if a certain feature is available  If test fails, build breaks right away  One maven goal: ► surefire:test 2. Integration tests with Fail-safe plugin  Test multiple components  Includes files with name IT*.java, *IT.java, *ITCase.java  If test fails, cleans up state in a post-integration-test phase, but does not fail the build  Two maven goals ► failsafe:integration-test runs the integration tests of an application ► failsafe:verify verifies that the integration tests of an application passed. 3. Integration tests with Pax-Exam plugin  Tests cross-bundle interfaces and integrates with OSGi  Can be used for spinning up virtual bundle container 5
  • 6. JUnit Extended with Pax-Exam ► Spins up a test container with all dependencies injected ► Pax Exam JUnit test requires a method annotated with @Configuration 6 @RunWith(PaxExam.class) public class SampleTest { @Inject private HelloService helloService; @Configuration public Option[] config() { return options( mavenBundle("com.example.myproject", "myproject-api", "1.0.0-SNAPSHOT"), bundle("http://www.example.com/repository/foo-1.2.3.jar"), junitBundles() ); } @Test public void getHelloService() { assertNotNull(helloService); assertEquals("Hello Pax!", helloService.getMessage()); } }
  • 7. JUnit with Mockito ► In some cases, you don’t need to create a real object to test code. ► Using Mock objects Minimizes number of moving pieces tested 7 @RunWith(MockitoJUnitRunner.class) public class MockitoTest { // assume there is a class MyDatabase @Mock MyDatabase databaseMock; @Test public void testQuery() { // assume there is a class called ClassToTest // which could be tested ClassToTest t = new ClassToTest(databaseMock); // call a method boolean check = t.query("* from t"); // test the return type assertTrue(check); // test that the query() method on the // mock object was called Mockito.verify(databaseMock).query("* from t"); } }
  • 8. A more Concrete ODL example: controller/sample/l2switch/md/topology/TopologyLinkDataChangeHandlerTest 8 public class TopologyLinkDataChangeHandlerTest { NetworkGraphService networkGraphService; DataBrokerService dataBrokerService; DataChangeEvent dataChangeEvent; Topology topology; Link link; @Before public void init() { networkGraphService = mock(NetworkGraphService.class); dataBrokerService = mock(DataBrokerService.class); dataChangeEvent = mock(DataChangeEvent.class); link = mock(Link.class); topology = mock(Topology.class); } @Test public void testOnDataChange() throws Exception { TopologyLinkDataChangeHandler topologyLinkDataChangeHandler = new TopologyLinkDataChangeHandler(dataBrokerService, networkGraphService, 2); Map<InstanceIdentifier<?>, DataObject> original = new HashMap<InstanceIdentifier<?>, DataObject>(); when(dataChangeEvent.getOriginalOperationalData()).thenReturn(original); InstanceIdentifier<?> instanceIdentifier = InstanceIdentifierUtils.generateTopologyInstanceIdentifier("flow:1"); Map<InstanceIdentifier<?>, DataObject> updated = new HashMap<InstanceIdentifier<?>, DataObject>(); DataObject dataObject = mock(DataObject.class); updated.put(instanceIdentifier, dataObject); when(dataChangeEvent.getUpdatedOperationalData()).thenReturn(updated); when(dataBrokerService.readOperationalData(instanceIdentifier)).thenReturn(topology); List<Link> links = new ArrayList<>(); links.add(link); when(topology.getLink()).thenReturn(links); topologyLinkDataChangeHandler.onDataChanged(dataChangeEvent); Thread.sleep(2100); verify(networkGraphService, times(1)).addLinks(links); } Setup data Setup mock objects Exercise Verify
  • 9. Sonar Code Coverage ► Sonar picks up testing results by using the JaCoCo plugin ► http://sonar.opendaylight.org/dashboard/index/45745?metric=it_coverage 9