21 Oct 2008Presentation to PJUG2 Unit Testing Java Code with Howard Abrams m.

Slides:



Advertisements
Similar presentations
Christian Hujer What is AceUnit? How does AceUnit work? How do I use AceUnit? © 2007 Christian Hujer.
Advertisements

1 JavaCUP JavaCUP (Construct Useful Parser) is a parser generator Produce a parser written in java, itself is also written in Java; There are many parser.
Squirrel Programming Language By Nandini Bhatta CS537 Summer 2008.
Unit Testing Java using Groovy and Mock Objects Walker Hale Human Genome Sequencing Center Baylor College of Medicine.
Session 4 Command-Line Arguments, Strings, and Files.
Programmer Testing Testing all things Java using JUnit and extensions.
Using Ant to build J2EE Applications Kumar
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
Computer Science and Engineering College of Engineering The Ohio State University JUnit The credit for these slides goes to Professor Paul Sivilotti at.
8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign them –Your PATH variable Introduction to shell programming.
Groovy in 15 minutes… Johannes Carlén Callista Enterprise AB
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
1 Groovy for Java developers and testers How Java developers and testers could use Groovy to increase their efficiency AUGUST 6, 2015.
Introduction Use of makefiles to manage the build process Declarative, imperative and relational rules Environment variables, phony targets, automatic.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
H3D API Training  Part 3.1: Python – Quick overview.
Using CookCC.  Use *.l and *.y files.  Proprietary file format  Poor IDE support  Do not work well for some languages.
1162 JDK 5.0 Features Christian Kemper Principal Architect Borland.
Junit At the forefront of Test Driven Development.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Ant Presentation by: Bart Taylor. What is Ant? The simple definition: A Java-based build tool The Official Definition: “Apache Ant is a Java-based build.
Fall 2004CSI University of Ottawa Introduction to PHP Basic principles and syntax.
Introduction to JUnit 3.8 SEG 3203 Winter ‘07 Prepared By Samia Niamatullah.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
Enterprise Java v090125Dev Env Overview1 Enterprise Java ( ) Development Environment Overview.
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Interfaces and Polymorphism CS 162 (Summer 2009).
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Unit, Regression, and Behavioral Testing Based On: Unit Testing with JUnit and CUnit by Beth Kirby Dec 13, 2002 Jules.
Build Systems Presentation December 14, 2015 Noon-1pm Kathy Lee Simunich Bldg. 203/ D120 Brought to you by: Argonne Java.
Fall 2004CSI University of Ottawa Introduction to PHP Basic principles and syntax.
THE PREPROCESSOR
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
1 Example Uses of Java Reflection Explained Simply.
Lambda Functions & Closures A Sydney PHP Group Presentation 2 nd October 2008 By Timothy Chandler.
One Year of Groovy Lessons Learned Aaron Digulla SSC - SharedServiceCenter 4163.
CSE 143 Lecture 14: testing.
Heath Carroll Bill Hanczaryk Rich Porter.  A Theory of Type Polymorphism in Programming ◦ Robin Milner (1977)  Milner credited with introducing the.
The need for Programming Languages
Software Construction Lab 10 Unit Testing with JUnit
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
CS 3304 Comparative Languages
Ch 10- Advanced Object-Oriented Programming Features
Java Programming Language
PHP (PHP: Hypertext Preprocessor)
Going from C++ to Java Jayden Navarro.
מבוא ל Groovy אליהו חלסצ'י תכנות מתקדם תרגול מספר 12
Statements, Comments & Simple Arithmetic
Exercise on Java Basics
Starting JavaProgramming
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Lecture 16 - Interfaces Professor Adams.
CSE 341 Section 7 Winter 2018 Adapted from slides by Eric Mullen, Nicholas Shahan, Dan Grossman, and Tam Dang.
Object Oriented Programming in java
Functional interface.
EEC-492/693/793 iPhone Application Development
CS5220 Advanced Topics in Web Programming Angular – TypeScript
Creating and Modifying Text part 3
Groovy.
CS5220 Advanced Topics in Web Programming Angular – TypeScript
SPL – PS1 Introduction to C++.
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Plug-In Architecture Pattern
Presentation transcript:

21 Oct 2008Presentation to PJUG2 Unit Testing Java Code with Howard Abrams m

21 Oct 2008Presentation to PJUG3 Why use Groovy for Unit Testing? ● Scripting language advantages ● Quick development (RAD)... inclined to write tests ● Higher-level programming... easier to maintain ● More features than Java ● Groovy integrates seamlessly with Java ● Extends JUnit, but still works like JUnit ● Good integration with Mocking Libraries ● Integrates with Ant and Maven

21 Oct 2008Presentation to PJUG4 Groovy Goodies ● Syntactic Sugar Coating ● Lists and Maps are first-class types ● Closures ● Builders and other helpers like XmlSlurper ● Object runtime alteration ● Mocks ● Dynamic Code — Evaluating expressions ● Write code to generate script code

21 Oct 2008Presentation to PJUG5 Java to Groovy Conversion public class Foobar { int prop = 5; List l = new ArrayList(); Foobar() { l.add ( 6 ); l.add (10); l.add (12.5); } Object doSomething() { System.out.println ("Working with " + prop+" property."); if ( prop < 5 ) return prop * 1.5; else return prop * 100; } public int getProp() { return prop; } public void setProp (int prop) { this.prop = prop; } public class Foobar { int prop = 5; List l = new ArrayList() Foobar() { l.add 6 l.add 10 l.add 12.5 } Object doSomething() { System.out.println ("Working with " + prop+" property.") if ( prop < 5 ) return prop * 1.5 else return prop * 100 } public int getProp() { return prop } public void setProp (int prop) { this.prop = prop } public class Foobar { int prop = 5; List l = new ArrayList() Foobar() { l.add 6 l.add 10 l.add 12.5 } Object doSomething() { println "Working with "+prop+" property." if ( prop < 5 ) return prop * 1.5 else return prop * 100 } public int getProp() { return prop } public void setProp (int prop) { this.prop = prop } public class Foobar { int prop = 5; List l = new ArrayList() Foobar() { l.add 6 l.add 10 l.add 12.5 } Object doSomething() { println "Working with "+prop+" property." if ( prop < 5 ) return prop * 1.5 else return prop * 100 } public class Foobar { int prop = 5; List l = [ 6, 10, 12.5 ] Foobar() { } Object doSomething() { println "Working with "+prop+" property." if ( prop < 5 ) return prop * 1.5 else return prop * 100 } public class Foobar { int prop = 5; List l = [ 6, 10, 12.5 ] Foobar() { } Object doSomething() { println "Working with ${prop} property." if ( prop < 5 ) return prop * 1.5 else return prop * 100 } public class Foobar { def prop = 5; def l = [ 6, 10, 12.5 ] def doSomething() { println "Working with ${prop} property." if ( prop < 5 ) return prop * 1.5 else return prop * 100 }

21 Oct 2008Presentation to PJUG6 Integrates Seamlessly with Java ● Java code is Groovy code ● Don't know how to write Groovy, write it in Java first. ● Groovy code compiles to Java class files ● Depends on groovy.jar ● The groovyc compiler can compile Java files ● Groovy classes extend Java classes

21 Oct 2008Presentation to PJUG7 Extends JUnit ● GroovyTestCase extends junit.framework.TestCase ● IDEs treat a Groovy test like JUnit ● Additional asserts: ● assertArrayEquals ( array1, array2 ) ● assertLength ( value, array ) ● assertContains ( object, array ) ● shouldFail {... }

21 Oct 2008Presentation to PJUG8 Square Class public class Square { int x; int y; int height; int width; /** * Returns the area associated with this square. The area == width * height IllegalStateException If the properties are not set. */ public int area() throws IllegalStateException { if ( width < 0 || height < 0 ) throw new IllegalStateException("Not properly set up."); return width * height; } // What follows is the getters/setters, etc...

21 Oct 2008Presentation to PJUG9 Square Tests public class SquareTests extends GroovyTestCase void testArea() { def sq = new Square ( width:4, height:3 ) assert 12 == sq.area() void testBadArea() { def sq = new Square ( width: -1, height: 4 ) shouldFail ( IllegalStateException ) { sq.area() } ● Instantiate objects and set properties at one time ● Normally we use assert instead of assertTrue ● Catch exceptions with shouldFail closure

21 Oct 2008Presentation to PJUG10 assertArrayEquals() /** * Like the string's String#split(String)} method, but returns the * delimiter... oh, and it doesn't take a regular expression. * original The string to parse delimiter The character(s) to use as splitting tokens An array of the strings split. */ public static String[] split ( String original, String delimiter void testSplit() { def original = "foo:and:bar" def delimiter = ':' def expected = [ 'foo', ':', 'and', ':', 'bar' ] assertArrayEquals ( expected, Utilities.split(original, delimiter) ) } Java Code to test... (Interface) Groovy Test Case...

21 Oct 2008Presentation to PJUG11 Groovy Test Suites import junit.framework.* static Test suite() { def suite = new TestSuite() def gsuite = new GroovyTestSuite() suite.addTestSuite( gsuite.compile( "SquareTests.groovy" )) suite.addTestSuite( gsuite.compile( "UtilitiesTests.groovy")) //... return suite } junit.textui.TestRunner.run(suite()) ● Create a standard JUnit test suite ● Use the GroovyTestSuite class to compile Groovy code

21 Oct 2008Presentation to PJUG12 AllTestSuite ● The AllTestSuite helper builds JUnit test suites. ● Takes a collection of Groovy files. ● First argument is a directory ● Second is a filename pattern ● Returns a JUnit TestSuite def suite = AllTestSuite.suite(".", "*Tests.groovy") junit.textui.TestRunner.run(suite)

21 Oct 2008Presentation to PJUG13 Collaborators ● Code depends on a component (poss. w/Interface) ● Component can be replaced (with a method call) /** * The Collaborator Interface */ public interface Bar { /** * Returns the random value. Returns something. */ public String something(); } public class Foo { Bar bar; // Setter for the "bar" property. public void setBar (Bar bar) { this.bar = bar; } /** * Returns a random value times 100. A random value. */ public String getValue() { if ( bar == null ) throw new IllegalStateException("'bar' property not set."); return bar.something() + "..."; }

21 Oct 2008Presentation to PJUG14 Testing Collaborators ● Goal: Test a single class (CUT) in isolation ● Minimize issues introduced by dependent code ● The domain of creating Mock classes class FooTests extends GroovyTestCase { void testGetValue() { def barMock = new BarMock ( value:'Hello' ) Foo foo = new Foo ( bar:barMock ) assert 'Hello...' == foo.value } class BarMock implements Bar { String value String something() { return value }

21 Oct 2008Presentation to PJUG15 Using Mock Libraries ● Mock Libraries are often helpful ● Popular library: EasyMockEasyMock ● I like jMock... with a bit of an extension:jMock /** * Taken from the Codehaus Groovy site. Sure hope they don't mind. JMock */ public class JUnit4GroovyMockery extends JUnit4Mockery { class ClosureExpectations extends org.jmock.Expectations { void closureInit(Closure cl, Object delegate) { cl.setDelegate(delegate); cl.call(); } public void checking(Closure c) { ClosureExpectations expectations = new ClosureExpectations(); expectations.closureInit(c, expectations); super.checking(expectations); }

21 Oct 2008Presentation to PJUG16 Testing with jMock final Mockery context = new void testGetValue() { mockBar = context.mock ( Bar.class ) context.checking { // How shall Mock act? one(mockBar).something(); will(returnValue("Hello")) one(mockBar).something(); will(returnValue("Good-bye")) } foo = new Foo( bar:mockBar ) assert foo.value == "Hello..." assert foo.value == "Good-bye..." }

21 Oct 2008Presentation to PJUG17 Ant Integration <taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" classpath="/usr/java/groovy/embedded/groovy-all jar"/> <groovyc srcdir ="${testSourceDirectory}" destdir="${testClassesDirectory}"> ● Add groovy-all-VERSION.jar to my.classpath: ● Joint compilation of both Java and Groovy:

21 Oct 2008Presentation to PJUG18 Using the JUnit Task ● JUnit task typically specifies *.java... not classes ● Must be careful to not specify internal classes:

21 Oct 2008Presentation to PJUG19 Groovy in Ant ● Add the Groovy Task: ● Add scripting to your build process: <taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpath="/usr/java/groovy/embedded/groovy-all jar"/> xmlfiles = new File(".").listFiles().findAll{ it =~ "\.xml$" } xmlfiles.sort().each { println it.toString() }

21 Oct 2008Presentation to PJUG20 Gant – Groovy Build Process ● Specify a build process using Groovy syntax: ● Includes closures and scripting capabilities ● Excludes closing tags. includeTargets << gant.targets.Clean cleanPattern << [ '**/*~', '**/*.bak' ] cleanDirectory << 'build' ant.taskdef ( name:'groovyc', classname:'org.codehaus.groovy.ant.Groovyc') target ( stuff : 'A target to do some stuff.' ) { println ( 'Stuff' ) depends ( clean ) echo ( message : 'A default message from Ant.' ) otherStuff ( ) } target ( otherStuff : 'A target to do some other stuff' ) { println ( 'OtherStuff' ) echo ( message : 'Another message from Ant.' ) clean ( ) } setDefaultTarget ( stuff )

21 Oct 2008Presentation to PJUG21 Gant Features ● Targets can be build programmatically: ● Compiling Example: aTargetName = 'something' target ( ( aTargetName ) : 'A target called' + aTargetName + '.' ) { println ( 'Executing ' + aTargetName ) } ant.taskdef ( name : 'groovyc', classname : 'org.codehaus.groovy.ant.Groovyc' ) target ( compile : 'Compile source to build directory.' ) { javac ( srcdir : sourceDirectory, destdir : buildDirectory, debug : 'on' ) groovyc ( srcdir : sourceDirectory, destdir : buildDirectory ) }