SlideShare a Scribd company logo
COMP23420 Sem 2 week 7
                          Unit testing and JUnit
                                                     John Sargeant
                                                  johns@cs.man.ac.uk


                         REMINDER: PLEASE ENSURE YOUR PHONE IS
                              SWITCHED OFF DURING LECTURES

C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Overview

•       Introduction
•       Java features for Junit 4
•       JUnit 4
•       Example unit tests




C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Introduction
• Reminder: unit testing is testing one unit (class) at a
        time – although most classes depend on other
        classes
• Can be black-box (based on the javadoc) or white
        box (based on the code).
• In most cases black-box is better.
• JUnit is a Java framework for unit testing
• JUnit 4 is a big improvement on previous versions,
        but requires some Java features you may not know.


C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Static import
Added in Java 1.5. Reminder: a normal import, e.g.
import java.util.Calendar;
Allows us to refer just to Calendar rather than having to
   say java.util.Calendar; every time.


Similarly a static import.e.g.
import static java.util.Calendar;
Allows us to refer to all the static features of the
   Calendar class by their short names, e.g.
   DAY_OF_WEEK rather than Calendar.DAY_OF_WEEK
C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Annotations
• Also added in Java 1.5. Ignored by the compiler, but
        intended to be used by other tools.
• E.g. suppose you have a tool which reminds you of
        programming tasks you need to do:

@Remind(period=weekly)
public Driver pickOptimumDriver() {
       return null; // Not yet implemented
}
Annotation applies to the immediately following class or
  method.
C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Reflection
• The ability to represent programming language
        constructs such as classes and methods within the
        language itself.
• “Not a first year topic” – JTL.
• Instances of the class called Class represent classes.
• Can be obtained with .class, e.g. Calendar.class
        gives an object representing the Calendar class.
• Can get mind-bending, e.g. Class.class is an
        instance of class Class which represents the class
        Class.

C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Example code to test
public class Sorter {
    private int[] _numbers;

               public Sorter(int[] numbers) {
                   _numbers = numbers;
               }

               public int[] getNumbers() {
                   return _numbers;
               }

               public void sort() {
                 // Not implemented yet
               }
}om VictoriathUenive rs ity os fof U M ISeTs te r
C
Th e
     b ining     s tre ngth
                                 M anch
                                              and
Test class (1)
import org.junit.*;
import static org.junit.Assert.*;

public class TestSorter {
   private static Sorter _sorter;
   private static boolean isSorted(int[] array) { …. }

      @Before
      public void setUp() {
         _sorter = new Sorter(new int[] { 3, 7, 1, 4, 6 })
      }



C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Test class (2)
          @Test
          public void testUnsorted() {
                     assertFalse(isSorted(_sorter.getNumbers()));
          }


              @Test
              public void testSorted() {
                     _sorter.sort();
                     assertTrue(isSorted(_sorter.getNumbers()));
              }
}

C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
What happens
The first test succeeds, the second fails, giving an
  AssertionError.
Now if we actually implement sorting:

public void sort() {
        Arrays.sort(_numbers);
}


Both tests should succeed.


C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
@Before and @BeforeClass
• Code run before or after a test to set things up to tidy
        up afterwards is called a Fixture.
• @Before indicates a fixture to be run before every
  test. The setup method which follows must not be
  static.
• @BeforeClass indicates a fixture to be run just once.
  The setup method must be static.
• @After and @AfterClass are the same for code run
  afterwards.


C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Running tests
The test class has no main() so how do we run it?


Either from the command line, with the JUnit Jar file on
    the CLASSPATH:
java org.junit.runner.JUnitCore TestClass


Or from within an IDE, e.g. in Netbeans, right click on
   the Java file, select Tools -> JUnit (make sure you
   select JUnit 4).

C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Test suites
• Often we want to run a bunch of tests together – a
        test suite. This is done with the @RunWith annotation
        and the test classes to use listed using reflection:

@Runwith(Suite.class)
@SuiteClasses(DepartureTimesTest.class,
  RosterOrderingTest.class,
  DriverAllocationTest.class)
public class RosterTest() {
}


C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Other things you can do
JUnit 4 allows you to other good things such as:


• Parameterise tests so you can run the same test
        many times with different parameters
• Test the exception handling behaviour of your code.

More information at JUnit,org and there are many
  tutorials on the web (make sure it’s JUnit 4, not 3).


C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Black box vs. White Box
• JUnit test classes are separate from the classes they
        are testing, so can only use the public interface
• If you have access to the private stuff, you could
        make use of that knowledge..
• E.g. an amount of Money represented as an int –
        won’t work for large numbers
• But generally Black Box testing is preferable – also
        helps to clarify requirements.
• E.g. testing for large amounts is an obvious thing to
        do anyway.
C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
General testing hints
• Real-world data (e.g. 358 timetable) is messy – check
        that you’ve covered all the cases.
• Test small parts before assembling them into bigger
        parts – make sure the easy tests get done.
• Make sure known bugs and things not yet
        implemented are documented using e.g. Bugzilla.
• When doing system testing, use a variety of real
        users – people will use it in ways you don’t expect.
• Don’t assume – check!

C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r
Weeks 8-11 (Provisional)


• Weeks 8 - 10 Software Architecture design (LZ)
• Week 11 review of second semester (JS/LZ)
• ~ 1 week before the exam: exam revision session
        (JS/LZ). Mock online exam will also be available.




C om b ining th e s tre ngth s of U M IS T and
Th e Victoria U nive rs ity o f M anch e s te r

More Related Content

What's hot

Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
Mavoori Soshmitha
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
rajkamaltibacademy
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
PyCon Italia
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
tarun308
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
Danairat Thanabodithammachari
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
study of java
study of java study of java
study of java
Prashant Mishra
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10Terry Yoast
 
Junit Recipes - Elementary tests (1/2)
Junit Recipes  - Elementary tests (1/2)Junit Recipes  - Elementary tests (1/2)
Junit Recipes - Elementary tests (1/2)Will Shen
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Mutable and immutable classes
Mutable and  immutable classesMutable and  immutable classes
Mutable and immutable classesTech_MX
 

What's hot (20)

Ppt on java basics1
Ppt on java basics1Ppt on java basics1
Ppt on java basics1
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
 
Control statements
Control statementsControl statements
Control statements
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
study of java
study of java study of java
study of java
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Java
JavaJava
Java
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Junit Recipes - Elementary tests (1/2)
Junit Recipes  - Elementary tests (1/2)Junit Recipes  - Elementary tests (1/2)
Junit Recipes - Elementary tests (1/2)
 
3.C#
3.C#3.C#
3.C#
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Mutable and immutable classes
Mutable and  immutable classesMutable and  immutable classes
Mutable and immutable classes
 

Similar to Week7 unit-testing

Junit 4.0
Junit 4.0Junit 4.0
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
Amila Paranawithana
 
Junit
JunitJunit
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
Jacky Lai
 
Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
Erkin Ünlü
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
Valerio Maggio
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
Devvrat Shukla
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
Sanjib Dhar
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
Büşra İçöz
 
Esem2014 presentation
Esem2014 presentationEsem2014 presentation
Esem2014 presentation
Tanja Vos
 
Junit
JunitJunit
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
Sónia
 
Unit testing
Unit testingUnit testing
Unit testing
Pooya Sagharchiha
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Advance unittest
Advance unittestAdvance unittest
Advance unittestReza Arbabi
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 

Similar to Week7 unit-testing (20)

Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
Junit
JunitJunit
Junit
 
Effective Unit Test Style Guide
Effective Unit Test Style GuideEffective Unit Test Style Guide
Effective Unit Test Style Guide
 
Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Junit
JunitJunit
Junit
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
Esem2014 presentation
Esem2014 presentationEsem2014 presentation
Esem2014 presentation
 
Junit
JunitJunit
Junit
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Advance unittest
Advance unittestAdvance unittest
Advance unittest
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Test ng
Test ngTest ng
Test ng
 

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 

Week7 unit-testing

  • 1. COMP23420 Sem 2 week 7 Unit testing and JUnit John Sargeant johns@cs.man.ac.uk REMINDER: PLEASE ENSURE YOUR PHONE IS SWITCHED OFF DURING LECTURES C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 2. Overview • Introduction • Java features for Junit 4 • JUnit 4 • Example unit tests C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 3. Introduction • Reminder: unit testing is testing one unit (class) at a time – although most classes depend on other classes • Can be black-box (based on the javadoc) or white box (based on the code). • In most cases black-box is better. • JUnit is a Java framework for unit testing • JUnit 4 is a big improvement on previous versions, but requires some Java features you may not know. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 4. Static import Added in Java 1.5. Reminder: a normal import, e.g. import java.util.Calendar; Allows us to refer just to Calendar rather than having to say java.util.Calendar; every time. Similarly a static import.e.g. import static java.util.Calendar; Allows us to refer to all the static features of the Calendar class by their short names, e.g. DAY_OF_WEEK rather than Calendar.DAY_OF_WEEK C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 5. Annotations • Also added in Java 1.5. Ignored by the compiler, but intended to be used by other tools. • E.g. suppose you have a tool which reminds you of programming tasks you need to do: @Remind(period=weekly) public Driver pickOptimumDriver() { return null; // Not yet implemented } Annotation applies to the immediately following class or method. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 6. Reflection • The ability to represent programming language constructs such as classes and methods within the language itself. • “Not a first year topic” – JTL. • Instances of the class called Class represent classes. • Can be obtained with .class, e.g. Calendar.class gives an object representing the Calendar class. • Can get mind-bending, e.g. Class.class is an instance of class Class which represents the class Class. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 7. Example code to test public class Sorter { private int[] _numbers; public Sorter(int[] numbers) { _numbers = numbers; } public int[] getNumbers() { return _numbers; } public void sort() { // Not implemented yet } }om VictoriathUenive rs ity os fof U M ISeTs te r C Th e b ining s tre ngth M anch and
  • 8. Test class (1) import org.junit.*; import static org.junit.Assert.*; public class TestSorter { private static Sorter _sorter; private static boolean isSorted(int[] array) { …. } @Before public void setUp() { _sorter = new Sorter(new int[] { 3, 7, 1, 4, 6 }) } C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 9. Test class (2) @Test public void testUnsorted() { assertFalse(isSorted(_sorter.getNumbers())); } @Test public void testSorted() { _sorter.sort(); assertTrue(isSorted(_sorter.getNumbers())); } } C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 10. What happens The first test succeeds, the second fails, giving an AssertionError. Now if we actually implement sorting: public void sort() { Arrays.sort(_numbers); } Both tests should succeed. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 11. @Before and @BeforeClass • Code run before or after a test to set things up to tidy up afterwards is called a Fixture. • @Before indicates a fixture to be run before every test. The setup method which follows must not be static. • @BeforeClass indicates a fixture to be run just once. The setup method must be static. • @After and @AfterClass are the same for code run afterwards. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 12. Running tests The test class has no main() so how do we run it? Either from the command line, with the JUnit Jar file on the CLASSPATH: java org.junit.runner.JUnitCore TestClass Or from within an IDE, e.g. in Netbeans, right click on the Java file, select Tools -> JUnit (make sure you select JUnit 4). C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 13. Test suites • Often we want to run a bunch of tests together – a test suite. This is done with the @RunWith annotation and the test classes to use listed using reflection: @Runwith(Suite.class) @SuiteClasses(DepartureTimesTest.class, RosterOrderingTest.class, DriverAllocationTest.class) public class RosterTest() { } C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 14. Other things you can do JUnit 4 allows you to other good things such as: • Parameterise tests so you can run the same test many times with different parameters • Test the exception handling behaviour of your code. More information at JUnit,org and there are many tutorials on the web (make sure it’s JUnit 4, not 3). C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 15. Black box vs. White Box • JUnit test classes are separate from the classes they are testing, so can only use the public interface • If you have access to the private stuff, you could make use of that knowledge.. • E.g. an amount of Money represented as an int – won’t work for large numbers • But generally Black Box testing is preferable – also helps to clarify requirements. • E.g. testing for large amounts is an obvious thing to do anyway. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 16. General testing hints • Real-world data (e.g. 358 timetable) is messy – check that you’ve covered all the cases. • Test small parts before assembling them into bigger parts – make sure the easy tests get done. • Make sure known bugs and things not yet implemented are documented using e.g. Bugzilla. • When doing system testing, use a variety of real users – people will use it in ways you don’t expect. • Don’t assume – check! C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r
  • 17. Weeks 8-11 (Provisional) • Weeks 8 - 10 Software Architecture design (LZ) • Week 11 review of second semester (JS/LZ) • ~ 1 week before the exam: exam revision session (JS/LZ). Mock online exam will also be available. C om b ining th e s tre ngth s of U M IS T and Th e Victoria U nive rs ity o f M anch e s te r