SlideShare a Scribd company logo
1 of 12
Unit Testing Coursesites
Context PublicHomePageRedirector public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //on request to the site / or index.html redirect to the servlet //we only want to hit on / HttpServletRequesthttpRequest = (HttpServletRequest)request; HttpServletResponsehttpResponse = (HttpServletResponse)response; String serverName = httpRequest.getHeader("Host"); intfirstperiodIndex = serverName.indexOf('.'); intlastperiodIndex = serverName.lastIndexOf('.'); /*   * so for wayank12teacher2.coursesites-stage.com   * hostHeader will be wayank12teacher2 setting the stage to check whether   * to forward to homepage.jsp or redirects to pages/index.html as in the past  */ String hostHeader = serverName.substring(0, firstperiodIndex).toLowerCase();
“No class is an island …” PublicHomePageRedirectorcollaborates with (depends on) ServletRequest ServletResponse FilterChain
Context..(2) /* taking care of missing www in the request   * aka coursesites-stage.com, coursesites.com   * making sure that redirects from OpenID login through Facebook or Twitter   * happen flawlessly  * */ if (!serverName.startsWith("www") && (firstperiodIndex == lastperiodIndex)) { String responseUrlPath = "https://" + "www." + serverName + "/webapps/Bb-sites-course-creation-BBLEARN/pages/index.html"; httpResponse.sendRedirect(responseUrlPath); return; }
Context…(3) else if (serverName.equalsIgnoreCase("coursesites.blackboard.com")){ serverName = "coursesites.com"; String responseUrlPath = "https://" + "www." + serverName + "/webapps/Bb-sites-course-creation-BBLEARN/pages/index.html"; httpResponse.sendRedirect(responseUrlPath); return; }
Scenario(s) Request with missing www (1) Request from coursesites.blackboard.com (2)
Unit Test Junit (command line through Ant) Mock (for collaborators  ServletRequest, ServletResponse, Chain)
TestCase(s) public class CourseSitesFilterTest { 	@Test	public void testMissingWWW() throws Exception{ … } 	@Test	public void testBlackBoardDomain() throws Exception{ …}
Scenario 1 public void testMissingWWW() throws Exception{			MockHttpServletRequest request = new MockHttpServletRequest();        		MockHttpServletResponse response = new MockHttpServletResponse();				//request.setMethod("GET"); request.addHeader("Host","coursesites.com");	 			//MockHttpServletRequest request = new 				FilterChain chain = Mockito.mock(FilterChain.class);				CourseSitesFilter filter = new CourseSitesFilter();		filter.doFilter(request, response, chain);				//System.out.println(request.getAttribute("hello"));		//System.out.println(request.getRequestURI());				//System.out.println(response.getForwardedUrl());		System.out.println("Output: " + response.getRedirectedUrl());	 assertTrue("Redirects to index.html", response.getRedirectedUrl().contains("index.html"));			 }
Scenario 2 	public void testBlackBoardDomain() throws Exception{			MockHttpServletRequest request = new MockHttpServletRequest();        		 MockHttpServletResponse response = new MockHttpServletResponse();			//request.setMethod("GET");		request.addHeader("Host","coursesites.blackboard.com");				//MockHttpServletRequest request = new MockHttpServletRequest("GET", "/invoiceView.app");				FilterChain chain = Mockito.mock(FilterChain.class);				CourseSitesFilter filter = new CourseSitesFilter();		filter.doFilter(request, response, chain);					//System.out.println(request.getRequestURI());			//System.out.println(response.getForwardedUrl());		System.out.println("Output: " + response.getRedirectedUrl());				assertTrue("Redirects to index.html", response.getRedirectedUrl().contains("index.html"));	}
Junit/Ant  <target name="junit" depends="compile">        <mkdir dir="${report.dir}"/>        <junitprintsummary="yes" haltonfailure="yes" showoutput="yes">            <classpath>                <path refid="classpath"/>                <path location="${build.dest}"/>				<path location="${build.test.dest}"/>            </classpath>            <formatter type="xml"/>            <batchtest fork="yes">                <fileset dir="${test.dir}" includes="**/*Test.java"/>            </batchtest>        </junit>    </target>
Results

More Related Content

What's hot

What's hot (20)

Reactive Programming no Android
Reactive Programming no AndroidReactive Programming no Android
Reactive Programming no Android
 
Reactive Programming on Android
Reactive Programming on AndroidReactive Programming on Android
Reactive Programming on Android
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
NestJS
NestJSNestJS
NestJS
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
Anay - Fluent interfaces in testing
Anay - Fluent interfaces in testingAnay - Fluent interfaces in testing
Anay - Fluent interfaces in testing
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Agile Android
Agile AndroidAgile Android
Agile Android
 
Agile Swift
Agile SwiftAgile Swift
Agile Swift
 
Laporan tugas network programming
Laporan tugas network programmingLaporan tugas network programming
Laporan tugas network programming
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
Testing JavaScript Applications
Testing JavaScript ApplicationsTesting JavaScript Applications
Testing JavaScript Applications
 
Code Reactions - An Introduction to Reactive Extensions
Code Reactions - An Introduction to Reactive ExtensionsCode Reactions - An Introduction to Reactive Extensions
Code Reactions - An Introduction to Reactive Extensions
 
Taking a Test Drive
Taking a Test DriveTaking a Test Drive
Taking a Test Drive
 
Como NÃO testar o seu projeto de Software. DevDay 2014
Como NÃO testar o seu projeto de Software. DevDay 2014Como NÃO testar o seu projeto de Software. DevDay 2014
Como NÃO testar o seu projeto de Software. DevDay 2014
 
Reactor Design Pattern
Reactor Design PatternReactor Design Pattern
Reactor Design Pattern
 
Programming JVM Bytecode with Jitescript
Programming JVM Bytecode with JitescriptProgramming JVM Bytecode with Jitescript
Programming JVM Bytecode with Jitescript
 
ES3-2020-06 Test Driven Development (TDD)
ES3-2020-06 Test Driven Development (TDD)ES3-2020-06 Test Driven Development (TDD)
ES3-2020-06 Test Driven Development (TDD)
 
Reliability and Reslience
Reliability and ReslienceReliability and Reslience
Reliability and Reslience
 

Viewers also liked

CourseSites jQuery plug-in
CourseSites jQuery plug-inCourseSites jQuery plug-in
CourseSites jQuery plug-in
Wayan Wira
 

Viewers also liked (8)

CourseSites jQuery plug-in
CourseSites jQuery plug-inCourseSites jQuery plug-in
CourseSites jQuery plug-in
 
Course sites new user profile pages
Course sites new user profile pagesCourse sites new user profile pages
Course sites new user profile pages
 
Spring batch
Spring batchSpring batch
Spring batch
 
Brasil Império: Primeiro Reinado (1822-1831)
Brasil Império:   Primeiro Reinado (1822-1831)Brasil Império:   Primeiro Reinado (1822-1831)
Brasil Império: Primeiro Reinado (1822-1831)
 
The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...The impact of innovation on travel and tourism industries (World Travel Marke...
The impact of innovation on travel and tourism industries (World Travel Marke...
 
Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)Reuters: Pictures of the Year 2016 (Part 2)
Reuters: Pictures of the Year 2016 (Part 2)
 
The Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post FormatsThe Six Highest Performing B2B Blog Post Formats
The Six Highest Performing B2B Blog Post Formats
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Similar to Unit testing CourseSites Apache Filter

Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
celenarouzie
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
knight1128
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
Martijn Dashorst
 

Similar to Unit testing CourseSites Apache Filter (20)

13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
servlets
servletsservlets
servlets
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Asynchronen Code testen
Asynchronen Code testenAsynchronen Code testen
Asynchronen Code testen
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 
Keep your Wicket application in production
Keep your Wicket application in productionKeep your Wicket application in production
Keep your Wicket application in production
 
Retrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saberRetrofit 2 - O que devemos saber
Retrofit 2 - O que devemos saber
 
Google guava
Google guavaGoogle guava
Google guava
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Salesforce Integration using REST SOAP and HTTP callouts
Salesforce Integration using REST SOAP and HTTP calloutsSalesforce Integration using REST SOAP and HTTP callouts
Salesforce Integration using REST SOAP and HTTP callouts
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 

Unit testing CourseSites Apache Filter

  • 2. Context PublicHomePageRedirector public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //on request to the site / or index.html redirect to the servlet //we only want to hit on / HttpServletRequesthttpRequest = (HttpServletRequest)request; HttpServletResponsehttpResponse = (HttpServletResponse)response; String serverName = httpRequest.getHeader("Host"); intfirstperiodIndex = serverName.indexOf('.'); intlastperiodIndex = serverName.lastIndexOf('.'); /* * so for wayank12teacher2.coursesites-stage.com * hostHeader will be wayank12teacher2 setting the stage to check whether * to forward to homepage.jsp or redirects to pages/index.html as in the past */ String hostHeader = serverName.substring(0, firstperiodIndex).toLowerCase();
  • 3. “No class is an island …” PublicHomePageRedirectorcollaborates with (depends on) ServletRequest ServletResponse FilterChain
  • 4. Context..(2) /* taking care of missing www in the request * aka coursesites-stage.com, coursesites.com * making sure that redirects from OpenID login through Facebook or Twitter * happen flawlessly * */ if (!serverName.startsWith("www") && (firstperiodIndex == lastperiodIndex)) { String responseUrlPath = "https://" + "www." + serverName + "/webapps/Bb-sites-course-creation-BBLEARN/pages/index.html"; httpResponse.sendRedirect(responseUrlPath); return; }
  • 5. Context…(3) else if (serverName.equalsIgnoreCase("coursesites.blackboard.com")){ serverName = "coursesites.com"; String responseUrlPath = "https://" + "www." + serverName + "/webapps/Bb-sites-course-creation-BBLEARN/pages/index.html"; httpResponse.sendRedirect(responseUrlPath); return; }
  • 6. Scenario(s) Request with missing www (1) Request from coursesites.blackboard.com (2)
  • 7. Unit Test Junit (command line through Ant) Mock (for collaborators  ServletRequest, ServletResponse, Chain)
  • 8. TestCase(s) public class CourseSitesFilterTest { @Test public void testMissingWWW() throws Exception{ … } @Test public void testBlackBoardDomain() throws Exception{ …}
  • 9. Scenario 1 public void testMissingWWW() throws Exception{ MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); //request.setMethod("GET"); request.addHeader("Host","coursesites.com"); //MockHttpServletRequest request = new FilterChain chain = Mockito.mock(FilterChain.class); CourseSitesFilter filter = new CourseSitesFilter(); filter.doFilter(request, response, chain); //System.out.println(request.getAttribute("hello")); //System.out.println(request.getRequestURI()); //System.out.println(response.getForwardedUrl()); System.out.println("Output: " + response.getRedirectedUrl()); assertTrue("Redirects to index.html", response.getRedirectedUrl().contains("index.html")); }
  • 10. Scenario 2 public void testBlackBoardDomain() throws Exception{ MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); //request.setMethod("GET"); request.addHeader("Host","coursesites.blackboard.com"); //MockHttpServletRequest request = new MockHttpServletRequest("GET", "/invoiceView.app"); FilterChain chain = Mockito.mock(FilterChain.class); CourseSitesFilter filter = new CourseSitesFilter(); filter.doFilter(request, response, chain); //System.out.println(request.getRequestURI()); //System.out.println(response.getForwardedUrl()); System.out.println("Output: " + response.getRedirectedUrl()); assertTrue("Redirects to index.html", response.getRedirectedUrl().contains("index.html")); }
  • 11. Junit/Ant <target name="junit" depends="compile"> <mkdir dir="${report.dir}"/> <junitprintsummary="yes" haltonfailure="yes" showoutput="yes"> <classpath> <path refid="classpath"/> <path location="${build.dest}"/> <path location="${build.test.dest}"/> </classpath> <formatter type="xml"/> <batchtest fork="yes"> <fileset dir="${test.dir}" includes="**/*Test.java"/> </batchtest> </junit> </target>