mockobjects-0.09/0000755000175000017500000000000010117310270015365 5ustar craftermcrafterm00000000000000mockobjects-0.09/build.properties.sample0000644000175000017500000000073007371354535022106 0ustar craftermcrafterm00000000000000# Properties related to the user's environment. This file should be provided # for building mockobjects or the properties need to be specified on the command # line when starting Ant with the -D switch or from a higher level build file # Distribution directory (if none is specified here, it will default to # 'dist' #dist.dir = e:/tmp/mockobjects-dist # You can also change your libraries directory. If none is specified here, it # will default to 'lib' #lib.dir = lib mockobjects-0.09/build.xml0000644000175000017500000003514307662777354017253 0ustar craftermcrafterm00000000000000 mockobjects-0.09/conf/0000755000175000017500000000000010117310266016317 5ustar craftermcrafterm00000000000000mockobjects-0.09/conf/.Refactory/0000755000175000017500000000000010117310266020333 5ustar craftermcrafterm00000000000000mockobjects-0.09/conf/.Refactory/pretty.settings0000644000175000017500000003727407340234365023472 0ustar craftermcrafterm00000000000000# Pretty.settings version=1.0 # This is the number of spaces to indent for each block. # Twice this number is the amount of space used for # unexpected carrage returns. indent=4 indent.char=space # Style for { and } # C style means that { is at the end of the line # and } is on a line by itself. For example, # if (myTest) { # // This is c style # } # # PASCAL style means both { and } are on lines # by themselves. For example, # if (myTest) # { # // This is PASCAL style # } block.style=C # The following parameter should be changed to true if you # like your parens to have a space before and after them # if ( x == y ) //expr.space=true # if (x == y) //expr.space=false expr.space=false # The following parameter is the minimum number of blank lines # between methods, nested classes, and nested interfaces. # It is also the number of lines before and after # field declarations, though field declarations will have # what ever spacing you used. # # Note that this is a minimum. If your code already # has more space between methods, then it won't shrink # the number of blank lines. lines.between=1 # # Default Javadoc comments # # The following items are used by the mechanism that # automatically inserts javadoc comments. Other than # author (which I recommend that you change), these # values are probably sufficient. However, if you # want to make it easer to search your files to find # where the values are missing, you can change these # to something more unique. # # Author - the default author author=Vincent Massol # Default description of the class class.descr=Description of the Class # Default description of the interface interface.descr=Description of the Interface # Default description of the constructor {0} stands for the name # of the constructor constructor.descr=Constructor for the {0} object # Default description of the method method.descr=Description of the Method # Default description of the parameter param.descr=Description of Parameter # Default description of the return value return.descr=Description of the Returned Value # Default description of the exception exception.descr=Description of Exception # Pretty.settings version=1.1 # Default description of the getter. {0} is the name of the # attribute, {1} is the name of the class, {2} is 'class' # or 'object' depending on whether it is static or not getter.descr=Gets the {0} attribute of the {1} {2} # Default description of the setter. {0} is the name of the # attribute, {1} is the name of the class, {2} is 'class' # or 'object' depending on whether it is static or not setter.descr=Sets the {0} attribute of the {1} {2} # Parameter description for setters. {0} is the name of the attribute setter.param.descr=The new {0} value # Return description for getters. {0} is the name of the attribute getter.return.descr=The {0} value # # Sort order # # To change the relative priorities of the sort, adjust the number after # the dot. For instance, if you want all the instance parts first then # static parts second, and within these you want the field, constructor etc # to be sorted next, switch the number of sort.1 and sort.2. # Check the type first # This places the fields first, and initializers last. Note that to keep # things compiling initializers must be after the fields. sort.1=Type(Field,Initializer,Constructor,Method,NestedClass,NestedInterface) # Check the class/instance next # To place the static methods and variables first, switch the order # of instance and static. sort.2=Class(Instance,Static) # Check the protection next # To sort with public methods/variables use Protection(public) # To sort with private methods/variables use Protection(private) sort.3=Protection(public) # Group setters and getters last # Setters are methods that start with the word 'set' # Getters are methods that start with the word 'get' or 'is' sort.4=Method(setter,getter,other) # Pretty.settings version=1.2 # Limits the level that javadoc comments are forced # into the document. The following are valid # levels: # * all - all items must have javadoc # * private - same as all # * package - all items except private items must have javadoc # * default - same as package # * protected - protected and public items must have javadoc # * public - only public items must have javadoc # * none - nothing is required to have javadoc # # method.minimum applies to constructors and methods method.minimum=none # field.minimum applies to fields field.minimum=none # Default field description field.descr=Description of the Field # Default description of the run method. {0} is the name of the # attribute, {1} is the name of the class, {2} is 'class' # or 'object' depending on whether it is static or not run.descr=Main processing method for the {1} {2} # Default description of the run method. {0} is the name of the # attribute, {1} is the name of the class, {2} is 'class' # or 'object' depending on whether it is static or not main.descr=The main program for the {1} {2} # Description of the main arguments main.param.descr=The command line arguments # Is the date a required field of the class or interface date.required=false # Pretty.settings version=1.3 # Default description of the add method. {0} is the name of the # attribute, {1} is the name of the class, {2} is 'class' # or 'object' depending on whether it is static or not adder.descr=Adds a feature to the {0} attribute of the {1} {2} # Description of the add argument adder.param.descr=The feature to be added to the {0} attribute # Pretty Printer Version version=1.4 # JUnit has a particular format for the names of methods. # These setup for the unit tests are done in a method named # setUp, the cleanup afterwards is done in tearDown, and # the unit tests all start with the word test. The following # are the default descriptions of these methods. junit.setUp.descr=The JUnit setup method junit.test.descr=A unit test for JUnit junit.tearDown.descr=The teardown method for JUnit junit.suite.descr=A suite of unit tests for JUnit junit.suite.return.descr=The test suite # class.minimum applies to classes and interfaces class.minimum=none # Pretty Printer Version version=1.5 # Is there a space after the cast cast.space=false # Star count for javadoc javadoc.star=2 # Wordwrap length for javadoc. You must have at least # javadoc.wordwrap.min characters in the comment and you # must be passing javadoc.wordwrapp.max for the indenting # plus the comment javadoc.wordwrap.max=78 javadoc.wordwrap.min=40 # Pretty Printer Version version=1.6 # # Header: # Uncomment these lines if you would like # a standard header at the beginning of each file. # You are allowed an unlimited number of lines here, # just number them sequentially. # header.1=/* header.2= * The Apache Software License, Version 1.1 header.3= * header.4= * Copyright (c) 1999 The Apache Software Foundation. All rights header.5= * reserved. header.6= * header.7= * Redistribution and use in source and binary forms, with or without header.8= * modification, are permitted provided that the following conditions header.9= * are met: header.10= * header.11= * 1. Redistributions of source code must retain the above copyright header.12= * notice, this list of conditions and the following disclaimer. header.13= * header.14= * 2. Redistributions in binary form must reproduce the above copyright header.15= * notice, this list of conditions and the following disclaimer in header.16= * the documentation and/or other materials provided with the header.17= * distribution. header.18= * header.19= * 3. The end-user documentation included with the redistribution, if header.20= * any, must include the following acknowlegement: header.21= * "This product includes software developed by the header.22= * Apache Software Foundation (http://www.apache.org/)." header.23= * Alternately, this acknowlegement may appear in the software itself, header.24= * if and wherever such third-party acknowlegements normally appear. header.25= * header.26= * 4. The names "The Jakarta Project", "Ant", and "Apache Software header.27= * Foundation" must not be used to endorse or promote products derived header.28= * from this software without prior written permission. For written header.29= * permission, please contact apache@apache.org. header.30= * header.31= * 5. Products derived from this software may not be called "Apache" header.32= * nor may "Apache" appear in their names without prior written header.33= * permission of the Apache Group. header.34= * header.35= * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED header.36= * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES header.37= * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE header.38= * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR header.39= * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, header.40= * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT header.41= * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF header.42= * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND header.43= * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, header.44= * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT header.45= * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF header.46= * SUCH DAMAGE. header.47= * ==================================================================== header.48= * header.49= * This software consists of voluntary contributions made by many header.50= * individuals on behalf of the Apache Software Foundation. For more header.51= * information on the Apache Software Foundation, please see header.52= * . header.53= */ # Pretty Printer Version version=1.7 # The following allow you to require and order # tags for the classes, methods, and fields. To # require the tag, add the name of the tag here # and then add a TAGNAME.descr field. To only # specify the order, just include the tag here. # Here is the order for tags for classes and interfaces class.tags=author # Here is the order for tags for methods and constructors method.tags=param,return,exception,since # Here is the order for tags for fields field.tags=since # In all tags that are required, there are some parameters # that are available. These are: # {0} refers to the current user # {1} refers to the current user # {2} refers to the name of the current object # Now we are ready to specify the author author.descr=Vincent Massol # Now we are ready to specify the created tag created.descr={1} # Pretty Printer Version version=2.2 # Whether we put a space before the @ space.before.javadoc=true # Should we sort the types and imports? sort.top=false # Should catch statements look like # (true) is: # try { # // Something here # } # catch (IOException ioe) { # // Something here # } # (false) is: # try { # // Something here # } catch (IOException ioe) { # // Something here # } # This value is also used for else statements catch.start.line=false # This determines if there should be a space after keywords # When this value is true, you get: # if (true) { # // Do something # } # When this value is false, you get: # if(true) { # // Do something # } keyword.space=true # # Do you want to lineup the names and descriptions # in javadoc comments? # javadoc.id.lineup=true # # How many spaces should javadoc comments be indented? # javadoc.indent=1 # # What do you do when a newline is unexpectedly encountered? # The valid values are double and param. Double means that # you should indent twice. Param means try to line up the # the parameters. # surprise.return=double # # To handle sun's coding standard, you want the method to begin # with a PASCAL coding style and the {} beneath that to be C style. # This parameter allows you to set the method style different # from the rest. # method.block.style=PASCAL # # Should throws part of a method/constructor declaration always be # on it's own line? # throws.newline=false # Pretty Printer Version version=3.0 # # Wordwrap the javadoc comments # reformat.comments=true # # Single line comment type # # # Should each single line comment be indented a certain number of spaces # from the margin? For this to work right be sure to indent each line with # spaces. # singleline.comment.ownline=true # # Indent the name of the field to this column (-1 for just one space) # field.name.indent=-1 # # Include javadoc comments where ever they appear # keep.all.javadoc=false # # End of line character(s) - either CR, CRNL, or NL # CR means carriage return, NL means newline # end.line=CRNL # # Absolute indent before a single line comment. # singleline.comment.absoluteindent=0 # # Space used before the start of a single line # from the end of the code # singleline.comment.incrementalindent=0 # # This feature describes how the pretty printer should # indent single line comments (//) that share the line # with source code. The two choices are incremental and absolute. # incremental - use an incremental indent # absolute - use the absolute indent level # singleline.comment.indentstyle.shared=incremental # # This feature describes how the pretty printer should # indent single line comments (//) that are on their # own line. The two choices are code and absolute. # code - use the same indent as the current code # absolute - use the absolute indent level # singleline.comment.indentstyle.ownline=code # # This feature describes what type of characters are used for # the java files. # 1 - ASCII (1 byte characters) # 2 - Unicode (2 byte characters - far east) # char.stream.type=1 # # This features sprecifies how to space out a field or a local # variable declaration. # single - a space between the modifiers, the type, the name # and the initializer # dynamic - determine the spacing between the modifiers, type, # name, and initializers so everything lines up # variable.spacing=single # Pretty Printer Version version=3.1 # # When a dynamic field spacing is used, this value specifies # the number of additional spaces to add between the modifiers, # type, name, and initializer. # dynamic.variable.spacing=1 # Pretty Printer Version version=3.2 # # How to format C Style comments. Valid values are: # leave - leave alone # align.star - place a row of stars to the right and align on those # align.blank - just align the comments to the right (no star) # c.style.format=align.star # # For one of the methods above that use the align type, this is # the number of spaces to include after the * or blank # c.style.indent=2 # Pretty Printer Version version=3.3 # # Empty methods and constructors remain on a single line # empty.block.single.line=false # Pretty Printer Version version=3.4 # # Do we force a space after a cast? # cast.force.nospace=false # Pretty Printer Version version=3.5 # # What tag name should be used for exceptions # exception.tag.name=@exception # Pretty Printer Version version=3.6 # # Should inner classes be documented # document.nested.classes=true # # Should the document have a footer. Include it here. # To include more lines, just add more values # #footer.1= #footer.2=// This is the end of the file #footer.3= # Pretty Printer Version version=3.7 # # Should the local variables be aligned with the { and } # or should they be indented to align with the other code? # false means align with the code, true means align # with the { } # variable.align.with.block=false mockobjects-0.09/conf/manifest0000644000175000017500000000041007331064400020043 0ustar craftermcrafterm00000000000000Manifest-Version: 1.0 Created-By: Ant Name: mockobjects/ Specification-Title: Mock Objects Specification-Vendor: Mock Objects Implementation-Vendor: Mock Objects Specification-Version: @version@ Implementation-Version: @version@ Implementation-Title: mockobjects mockobjects-0.09/.cvsignore0000644000175000017500000000006207613265331017401 0ustar craftermcrafterm00000000000000out build.properties bin dist .classpath .project mockobjects-0.09/doc/0000755000175000017500000000000010117310266016137 5ustar craftermcrafterm00000000000000mockobjects-0.09/doc/README0000644000175000017500000000015107661012520017016 0ustar craftermcrafterm00000000000000All documentation has been moved to the MockObjects wiki: http://wiki.truemesh.com/mockobjects/FrontPage mockobjects-0.09/env.txt0000644000175000017500000000021407635626433016741 0ustar craftermcrafterm00000000000000clean-compiled jar:/opt/IBMJava2-131: clean-compiled jar:/usr/java/j2sdk1.4.1: clean-compiled jar:/opt/IBMJava2-131:-Dj2ee.lib=lib/j2ee.jar mockobjects-0.09/lib/0000755000175000017500000000000010117310266016140 5ustar craftermcrafterm00000000000000mockobjects-0.09/lib/.cvsignore0000644000175000017500000000000607613265265020153 0ustar craftermcrafterm00000000000000*.jar mockobjects-0.09/lib/.keepit0000644000175000017500000000036307336502371017435 0ustar craftermcrafterm00000000000000This file is only there so that CVS clients will not prune this directory. Why ? Because Ant will look for user jars in this diretory and if the directory does not exist Ant will exit with an error (something "directory lib does not exist" !).mockobjects-0.09/make_mocks.py0000755000175000017500000000146507553016707020103 0ustar craftermcrafterm00000000000000#!/usr/bin/python2 import os, shutil libdir = 'lib' junitlib = libdir+'/junit.jar' antcmd = 'ant' if os.environ.has_key('ANT_HOME'): anthome=os.environ('ANT_HOME') else: anthome='/opt/ant' def ante(target, javahome, options): ENV={ 'PATH': javahome + '/bin:' + anthome + '/bin:' + os.environ['PATH'], 'JAVA_HOME': javahome } target = antcmd+options+' ' + target print '###############################################' print ENV print '###############################################' os.spawnvpe(os.P_WAIT, antcmd, target.split(), ENV) print '###############################################' def ant(target): ante(target, os.environ['JAVA_HOME'], '') def build(env): args = env.strip().split(':') ante(args[0], args[1], args[2]) ant('clean') for env in file('env.txt').readlines(): build(env) mockobjects-0.09/make_mocks.sh0000644000175000017500000000213607552647342020062 0ustar craftermcrafterm00000000000000#!/usr/bin/bash # helper script for building all the combinations # copy it somewhere it won't be overwritten and set the paths # to those on your machine # This version setup for cygwin on my machine # - smgf export ANT_HOME="D:\java\ant" cd mockobjects-java rm -f lib/junit.jar cp /cygdrive/d/java/junit/3.7/junit.jar lib export PATH=$ANT_HOME/bin:$PATH ant.bat clean ( export JAVA_HOME="D:\java\jdk\1.3.1_05" export PATH=$JAVA_HOME/bin:$PATH echo "+++++++++ JAVA 1.3 +++++++++++++" echo " +++++ JDK 1.2 +++++" rm -f lib/j2ee.jar cp /cygdrive/d/java/j2sdkee1.2.1//lib/j2ee.jar lib ant.bat clean-compiled jar echo " +++++ JDK 1.3 +++++" rm -f lib/j2ee.jar cp /cygdrive/d/java/j2sdkee1.3.1/lib/j2ee.jar lib ant.bat clean-compiled jar ) ( export JAVA_HOME="D:\java\jdk\1.4.1" export PATH=$JAVA_HOME/bin:$PATH echo "+++++++++ JAVA 1.4 +++++++++++++" echo " +++++ JDK 1.2 +++++" rm -f lib/j2ee.jar cp /cygdrive/d/java/j2sdkee1.2.1//lib/j2ee.jar lib ant.bat clean-compiled jar echo " +++++ JDK 1.3 +++++" rm -f lib/j2ee.jar cp /cygdrive/d/java/j2sdkee1.3.1/lib/j2ee.jar lib ant.bat clean-compiled jar ) mockobjects-0.09/src/0000755000175000017500000000000010117310266016161 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/0000755000175000017500000000000010117310266017111 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/com/0000755000175000017500000000000010117310266017667 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/com/mockobjects/0000755000175000017500000000000010117310266022172 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/com/mockobjects/AbstractExpectation.java0000644000175000017500000000344107331064400027006 0ustar craftermcrafterm00000000000000package com.mockobjects; abstract public class AbstractExpectation implements Verifiable, Expectation { protected boolean myFailureModeIsImmediate = true; protected String myName; private boolean myHasExpectations = false; public AbstractExpectation(String name) { myName = name; } protected void assertEquals( String msg, int expectedValue, int actualValue) { assertEquals(msg, new Integer(expectedValue), new Integer(actualValue)); } /** * Due to junit Assert being a Singleton implemented with static methods, and java's * unfortunate implementation of class methods (e.g. no late binding) it is * necessary to re-implement this method here instead of over-riding failNotEquals */ protected void assertEquals( String msg, Object expectedValue, Object actualValue) { if (!myHasExpectations) return; if (expectedValue == null && actualValue == null) return; if (expectedValue != null && expectedValue.equals(actualValue)) return; junit.framework.Assert.fail( myName + " " + msg + "\nExpected: " + expectedValue + "\nReceived: " + actualValue); } abstract public void clearActual(); public boolean hasExpectations() { return myHasExpectations; } public void setFailOnVerify() { myFailureModeIsImmediate = false; } protected void setHasExpectations() { clearActual(); myHasExpectations = true; } protected boolean shouldCheckImmediately() { return myFailureModeIsImmediate && myHasExpectations; } public abstract void verify(); } mockobjects-0.09/src/core/com/mockobjects/AbstractExpectationCollection.java0000644000175000017500000000511007661772070031034 0ustar craftermcrafterm00000000000000package com.mockobjects; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.HashSet; abstract public class AbstractExpectationCollection extends AbstractExpectation implements ExpectationCollection { public AbstractExpectationCollection(String name) { super(name); } public void addActual(Object actualItem) { getActualCollection().add(actualItem); if (shouldCheckImmediately()) { checkImmediateValues(actualItem); } } public void addActual(int actualItem) { addActual(new Integer(actualItem)); } public void addActualMany(Object[] items) { if(items == null) return; for (int i = 0; i < items.length; ++i) { addActual(items[i]); } } public void addActualMany(Enumeration items) { while (items.hasMoreElements()) { addActual(items.nextElement()); } } public void addActualMany(Iterator items) { while (items.hasNext()) { addActual(items.next()); } } public void addExpected(int expectedItem) { addExpected(new Integer(expectedItem)); } public void addExpected(Object expectedItem) { getExpectedCollection().add(expectedItem); setHasExpectations(); } public void addExpectedMany(Object[] expectedItems) { for (int i = 0; i < expectedItems.length; ++i) { addExpected(expectedItems[i]); } setHasExpectations(); } public void addExpectedMany(Enumeration expectedItems) { while (expectedItems.hasMoreElements()) { addExpected(expectedItems.nextElement()); } setHasExpectations(); } public void addExpectedMany(Iterator expectedItems) { while (expectedItems.hasNext()) { addExpected(expectedItems.next()); } setHasExpectations(); } abstract protected void checkImmediateValues(Object actualItem); public void clearActual() { getActualCollection().clear(); } protected void clearExpectation() { getExpectedCollection().clear(); } abstract protected Collection getActualCollection(); abstract protected Collection getExpectedCollection(); public void setExpectNothing() { clearExpectation(); setHasExpectations(); } public void verify() { assertEquals( "did not receive the expected collection items.", new HashSet(getExpectedCollection()), new HashSet(getActualCollection())); } } mockobjects-0.09/src/core/com/mockobjects/ExceptionalReturnValue.java0000644000175000017500000000104407661772070027523 0ustar craftermcrafterm00000000000000package com.mockobjects; /** * Sequence of exception values as required by MockMaker * This is a generic class that should have been introduced to the mockobjects code stream instead of * being separately included in org.mockobjects. * It is possibly similar to a ReturnObjectList? */ public class ExceptionalReturnValue { private Throwable exception; public ExceptionalReturnValue( Throwable exception ) { this.exception = exception; } public Throwable getException() { return exception; } } mockobjects-0.09/src/core/com/mockobjects/Expectation.java0000644000175000017500000000224007342317367025335 0ustar craftermcrafterm00000000000000package com.mockobjects; /** * An Expectation is an object that we set up at the beginning of a unit test to * expect certain things to happen to it. If it is possible to tell, the Expectation will * fail as soon as an incorrect value has been set. * * Call verify() at the end of a unit test to check for missing or incomplete values. * * If no expectations have been set on the object, then no checking will be done and * verify() will do nothing. */ public interface Expectation extends Verifiable { /** * Return true if any expectations have been set on this object. */ public boolean hasExpectations(); /** * Tell the object to expect nothing to happen to it, perhaps because the test is exercising * the handling of an error. The Expectation will fail if any actual values are set. * * Note that this is not the same as not setting any expectations, in which case verify() * will do nothing. */ void setExpectNothing(); /** * If an incorrect actual value is set, defer reporting this as a failure until verify() * is called on this object. */ public void setFailOnVerify(); } mockobjects-0.09/src/core/com/mockobjects/ExpectationCollection.java0000644000175000017500000000155307342317367027357 0ustar craftermcrafterm00000000000000package com.mockobjects; import java.util.*; /** * An ExpectationCollection is an expectation that supports multiple values, such as lists * and sets. * * The addition methods distinguish between adding a single value and unpacking the contents of * a collection. We have to make this distinction so that it is possible to add an array, enumeration, * or iterator as a single expected object, rather than adding its contents. */ public interface ExpectationCollection extends Expectation { void addActual(Object actual); void addActualMany(Object[] actuals); void addActualMany(Enumeration actuals); void addActualMany(Iterator actuals); void addExpected(Object expected); void addExpectedMany(Object[] expectedItems); void addExpectedMany(Enumeration expectedItems); void addExpectedMany(Iterator expectedItems); } mockobjects-0.09/src/core/com/mockobjects/ExpectationCounter.java0000644000175000017500000000175507331064400026670 0ustar craftermcrafterm00000000000000package com.mockobjects; import junit.framework.Assert; public class ExpectationCounter extends AbstractExpectation { private int myExpectedCalls = 0; private int myActualCalls = 0; public ExpectationCounter(String name) { super(name); } public void clearActual() { myActualCalls = 0; } public void inc() { myActualCalls++; if (shouldCheckImmediately()) { Assert.assertTrue( myName + " should not be called more than " + myExpectedCalls + " times", myActualCalls <= myExpectedCalls); } } public void setExpected(int expectedCalls) { myExpectedCalls = expectedCalls; setHasExpectations(); } public void setExpectNothing() { myExpectedCalls = 0; setHasExpectations(); } public void verify() { assertEquals( "did not receive the expected Count.", myExpectedCalls, myActualCalls); } } mockobjects-0.09/src/core/com/mockobjects/ExpectationDoubleValue.java0000644000175000017500000000322507570131754027466 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.AssertMo; public class ExpectationDoubleValue extends AbstractExpectation { private Double expectedValue = null; private double expectedError = 0.0; private boolean expectNothing = false; private Double actualValue = null; public ExpectationDoubleValue(String name) { super(name); clearActual(); } public void clearActual() { actualValue = null; } public void setActual( double value ) { actualValue = new Double(value); if (shouldCheckImmediately()) { verify(); } } public void setExpected( double value, double error ) { expectedValue = new Double(value); expectedError = Math.abs(error); setHasExpectations(); } public void setExpectNothing() { expectNothing = true; clearActual(); setHasExpectations(); } public void verify() { if( expectNothing ) { AssertMo.assertNull( myName + " expected no value", actualValue ); } else if( expectedValue != null ) { AssertMo.assertNotNull( myName + " expected a value", actualValue ); double actualError = Math.abs( actualValue.doubleValue() - expectedValue.doubleValue() ); AssertMo.assertTrue( myName + " expected a value within " + expectedError + " of " + expectedValue + ", was " + actualValue, actualError <= expectedError ); } } } mockobjects-0.09/src/core/com/mockobjects/ExpectationList.java0000644000175000017500000000206307531223605026163 0ustar craftermcrafterm00000000000000package com.mockobjects; import java.util.*; import junit.framework.Assert; public class ExpectationList extends AbstractExpectationCollection { protected ArrayList myExpectedItems = new ArrayList(); protected ArrayList myActualItems = new ArrayList(); public ExpectationList(String name) { super(name); } protected void checkImmediateValues(Object actualItem) { int size = myActualItems.size(); Assert.assertTrue( myName + " had different sizes\nExpected Size:" + myExpectedItems.size() + "\nReceived size: " + size + " when adding:" + actualItem, myExpectedItems.size() >= size); assertEquals( myName + " added item does not match", myExpectedItems.get(size - 1), actualItem); } protected Collection getActualCollection() { return myActualItems; } protected Collection getExpectedCollection() { return myExpectedItems; } } mockobjects-0.09/src/core/com/mockobjects/ExpectationMap.java0000644000175000017500000000166407660454726026010 0ustar craftermcrafterm00000000000000package com.mockobjects; import java.util.*; public class ExpectationMap implements Expectation, Verifiable { private HashMap myEntries; private ExpectationSet myKeys; public ExpectationMap(String name) { myEntries = new HashMap(); myKeys = new ExpectationSet(name + " keys"); } public void addExpected(Object key, Object value) { myKeys.addExpected(key); myEntries.put(key, value); } public void addExpectedMissing(Object key) { myKeys.addExpected(key); } public Object get(Object key) { myKeys.addActual(key); return myEntries.get(key); } public boolean hasExpectations() { return myKeys.hasExpectations(); } public void setExpectNothing() { myKeys.setExpectNothing(); } public void setFailOnVerify() { myKeys.setFailOnVerify(); } public void verify() { myKeys.verify(); } } mockobjects-0.09/src/core/com/mockobjects/ExpectationSegment.java0000644000175000017500000000216507331064400026647 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.*; public class ExpectationSegment extends AbstractExpectation { private String myExpectedSegment; private String myActualString; public ExpectationSegment(String name) { super(name); clearActual(); } public void clearActual() { myActualString = null; } public void setActual(String aString) { myActualString = aString; if (shouldCheckImmediately()) { verify(); } } public void setExpected(String segment) { myExpectedSegment = segment; setHasExpectations(); } public void setExpectNothing() { myActualString = null; setExpected(null); } public void verify() { if (hasExpectations()) { if (null == myExpectedSegment) { AssertMo.assertNull("Expecting nothing", myActualString); } else { AssertMo.assertIncludes( "Should include string segment", myExpectedSegment, myActualString); } } } } mockobjects-0.09/src/core/com/mockobjects/ExpectationSet.java0000644000175000017500000000142107660454726026015 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.AssertMo; import java.util.Collection; import java.util.HashSet; public class ExpectationSet extends AbstractExpectationCollection { private HashSet myExpectedItems = new HashSet(); private HashSet myActualItems = new HashSet(); public ExpectationSet(String name) { super(name); } protected void checkImmediateValues(Object actualItem) { AssertMo.assertTrue( myName + " did not receive an expected item\nUnexpected:" + actualItem, new HashSet(myExpectedItems).contains(actualItem)); } protected Collection getActualCollection() { return myActualItems; } protected Collection getExpectedCollection() { return myExpectedItems; } } mockobjects-0.09/src/core/com/mockobjects/ExpectationValue.java0000644000175000017500000000316407570131754026335 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.Null; public class ExpectationValue extends AbstractExpectation { private Object myExpectedValue; private Object myActualValue; public ExpectationValue(String name) { super(name); clearActual(); } public void clearActual() { myActualValue = new Null("Nothing"); } public void setActual(int aValue) { setActual(new Integer(aValue)); } public void setActual(long aValue) { setActual(new Long(aValue)); } public void setActual(double aValue) { setActual(new Double(aValue)); } public void setActual(Object aValue) { myActualValue = aValue; if (shouldCheckImmediately()) { verify(); } } public void setActual(boolean aValue) { setActual(new Boolean(aValue)); } public void setExpected(int aValue) { setExpected(new Integer(aValue)); } public void setExpected(long aValue) { setExpected(new Long(aValue)); } public void setExpected(double aValue) { setExpected(new Double(aValue)); } public void setExpected(Object aValue) { myExpectedValue = aValue; setHasExpectations(); } public void setExpected(boolean aValue) { setExpected(new Boolean(aValue)); } public void setExpectNothing() { setExpected(new Null("Nothing")); myActualValue = myExpectedValue; } public void verify() { assertEquals( "did not receive the expected Value.", myExpectedValue, myActualValue); } } mockobjects-0.09/src/core/com/mockobjects/MapEntry.java0000644000175000017500000000531507660454726024623 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.Null; import java.lang.reflect.Array; import java.util.Map; /** * A public MapEntry data type that can be used where the Map.Entry interface is required * (needed because the Sun implementation is package protected) */ public class MapEntry implements Map.Entry { private Object myKey; private Object myValue; public MapEntry(Object aKey, Object aValue) { myKey = (aKey == null ? new Null() : aKey); myValue = (aValue == null ? new Null() : aValue); } public boolean equals(Object o) { if (!(o instanceof MapEntry)) { return false; } MapEntry other = (MapEntry) o; if (myValue.getClass().isArray() && other.getValue().getClass().isArray()) { return arrayEquals(other.getValue()); } else { return myKey.equals(other.getKey()) && myValue.equals(other.getValue()); } } private final boolean arrayEquals(Object anArray) { int i = 0; boolean endOfThisArray = false; boolean endOfAnotherArray = false; while (true) { Object valueOfThis = null; Object valueOfAnother = null; try { valueOfThis = Array.get(myValue, i); } catch (ArrayIndexOutOfBoundsException e) { endOfThisArray = true; } try { valueOfAnother = Array.get(anArray, i); } catch (ArrayIndexOutOfBoundsException e) { endOfAnotherArray = true; } if (endOfThisArray && endOfAnotherArray) { return true; } if (valueOfThis != null || valueOfAnother != null) { if (valueOfThis == null || !valueOfThis.equals(valueOfAnother)) { return false; } } i++; } } public Object getKey() { return myKey; } public Object getValue() { return myValue; } public int hashCode() { int hash = myKey.hashCode(); if (myValue.getClass().isArray()) { int i = 0; try { while (true) { hash = hash ^ Array.get(myValue, i++).hashCode(); } } catch (ArrayIndexOutOfBoundsException e) { } } else { hash = hash ^ myValue.hashCode(); } return hash; } public Object setValue(Object aValue) { Object oldValue = myValue; myValue = (null == aValue ? new Null() : aValue); return oldValue; } public String toString() { return myKey.toString() + "=" + myValue.toString(); } } mockobjects-0.09/src/core/com/mockobjects/MockObject.java0000644000175000017500000000205507570131754025073 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.AssertMo; import com.mockobjects.util.Verifier; public abstract class MockObject implements Verifiable { protected void assertEquals(String message, int o1, int o2) { AssertMo.assertEquals(message, o1, o2); } protected void assertEquals(String message, Object o1, Object o2) { AssertMo.assertEquals(message, o1, o2); } protected void assertTrue(String message, boolean condition) { AssertMo.assertTrue(message, condition); } protected void fail(String message) { AssertMo.fail(message); } public void notImplemented() { AssertMo.notImplemented(this.getClass().getName()); } /** * @deprecated */ protected void notYetImplemented() { notYetImplemented(this.getClass().getName()); } /** * @deprecated */ public static void notYetImplemented(String mockName) { AssertMo.notImplemented(mockName); } public void verify() { Verifier.verifyObject(this); } } mockobjects-0.09/src/core/com/mockobjects/ReturnObjectBag.java0000644000175000017500000001201707651477216026100 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.ReturnObjectList; import com.mockobjects.Verifiable; import com.mockobjects.util.AssertMo; import com.mockobjects.util.Null; import java.util.*; /** * The ReturnObjectBag is a map containing instances of ReturnObjectList. * A single instance is held for each mapkey. Every time a call to putObjectToReturn or * getNextReturnObject is made an object is added or removed from the ReturnObjectList for * the given key. * This allows the ReturnObjectBag to be used to return an ordered list of objects for each key * regardless of the order in which the key requests are made. * @see ReturnObjectList * @author Jeff Martin * @version $Revision: 1.4 $ */ public class ReturnObjectBag implements Verifiable { private final Hashtable returnObjectLists = new Hashtable(); private final String name; /** * @param name Name used to describe an instance of ReturnObjectBag in error messages */ public ReturnObjectBag(String name) { this.name = name; } /** * Places an object into the list of return objects for a particular key * @param key the key against which the object will be stored * @param value the value to be added to the list for that key * @see ReturnObjectList#addObjectToReturn */ public void putObjectToReturn(Object key, Object value) { if (key == null) { key = Null.NULL; } ReturnObjectList returnObjectList = (ReturnObjectList) returnObjectLists.get(key); if (returnObjectList == null) { returnObjectList = new ReturnObjectList(name + "." + key.toString()); returnObjectLists.put(key, returnObjectList); } returnObjectList.addObjectToReturn(value); } /** * Places an object into the list of return objects for a particular int key * @param key the key against which the object will be stored * @param value the value to be added to the list for that key * @see ReturnObjectList#addObjectToReturn */ public void putObjectToReturn(int key, Object value) { putObjectToReturn(new Integer(key), value); } /** * Places an int into the list of return objects for a particular key. The value can be retrieved * using the getNextReturnInt method * @param key the key against which the object will be stored * @param value the value to be added to the list for that key * @see ReturnObjectList#addObjectToReturn * @see #getNextReturnInt */ public void putObjectToReturn(Object key, int value) { putObjectToReturn(key, new Integer(value)); } /** * Places an boolean into the list of return objects for a particular key. The value can be retrieved * using the getNextReturnBoolean method * @param key the key against which the object will be stored * @param value the value to be added to the list for that key * @see ReturnObjectList#addObjectToReturn * @see #getNextReturnBoolean */ public void putObjectToReturn(Object key, boolean value) { putObjectToReturn(key, new Boolean(value)); } /** * Checks each the list for each key to verify that all no objects remain * in the list for that key. * @see ReturnObjectList#verify */ public void verify() { for (Iterator it = returnObjectLists.values().iterator(); it.hasNext();) { ((ReturnObjectList) it.next()).verify(); } } /** * Returns the next object in the ReturnObjectList for a given key. * The call will throw an AssertFailError if the requested key is * not present within this ReturnObjectBag. * @param key The key for which the next object should be returned. * @return The next object from the ReturnObjectList stored against the given key. * @see ReturnObjectList#nextReturnObject */ public Object getNextReturnObject(Object key) { if (key == null) { key = Null.NULL; } ReturnObjectList returnObjectList = (ReturnObjectList) returnObjectLists.get(key); AssertMo.assertNotNull(name + " does not contain " + key.toString(), returnObjectList); return returnObjectList.nextReturnObject(); } /** * Returns the next object in the ReturnObjectList for a given int key. * The call will throw an AssertFailError if the requested key is * not present within this ReturnObjectBag. * @param key The key for which the next object should be returned. * @return The next object from the ReturnObjectList stored against the given key. * @see ReturnObjectList#nextReturnObject */ public Object getNextReturnObject(int key) { return getNextReturnObject(new Integer(key)); } public Hashtable getHashTable(){ return returnObjectLists; } public int getNextReturnInt(Object key) { return ((Integer)getNextReturnObject(key)).intValue(); } public boolean getNextReturnBoolean(Object key) { return ((Boolean)getNextReturnObject(key)).booleanValue(); } } mockobjects-0.09/src/core/com/mockobjects/ReturnObjectList.java0000644000175000017500000000426507651477216026330 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.AssertMo; import java.util.Vector; /** *

This class allows a list of objects to be setup which can be used whilst.The * list is check to make sure that all the object in it are used and that none * are left over at the end of a test.

* *

For ever sucessive call to nextReturnObject the next object in the list will * returned.

* *

If the nextReturnObject method is called and there are no objects in the list * an assertion error will be thrown. If the verify method is called and there * are objects still in the list an assertion error will also be thrown.

*/ public class ReturnObjectList implements Verifiable { private final Vector myObjects = new Vector(); private final String myName; /** * Construct a new empty list * @param aName Label used to identify list */ public ReturnObjectList(String aName) { this.myName = aName; } /** * Add a next object to the end of the list. * @param anObjectToReturn object to be added to the list */ public void addObjectToReturn(Object anObjectToReturn){ myObjects.add(anObjectToReturn); } /** * Add a next boolean to the end of the list. * @param aBooleanToReturn boolean to be added to the list */ public void addObjectToReturn(boolean aBooleanToReturn){ myObjects.add(new Boolean(aBooleanToReturn)); } /** * Add a next integer to the end of the list. * @param anIntegerToReturn integer to be added to the list */ public void addObjectToReturn(int anIntegerToReturn){ myObjects.add(new Integer(anIntegerToReturn)); } /** * Returns the next object from the list. Each object it returned in the * order in which they where added. */ public Object nextReturnObject(){ AssertMo.assertTrue(myName + " has run out of objects.", myObjects.size() > 0); return myObjects.remove(0); } /** * Verify that there are no objects left within the list. */ public void verify() { AssertMo.assertEquals(myName + " has un-used objects.", 0, myObjects.size()); } } mockobjects-0.09/src/core/com/mockobjects/ReturnValue.java0000644000175000017500000000620107635626401025324 0ustar craftermcrafterm00000000000000package com.mockobjects; import com.mockobjects.util.AssertMo; import com.mockobjects.util.Null; /** *

The ReturnValue class allows a value to be setup which will then be returned upon a specific * method call. If value.getValue() is called before value.setValue(value) * the ReturnValue will raise an error warning that this value has not been set. If the required * return value is null the return value can be set like this * value.setValue(null) in this case calling value.getValue() * will return null.

* *

The advantage of this is provide better information to the user of a mock when * interacting with third party code which may expect certain values to have been set.

* * e.g. *
 * private final ReturnValue value = new ReturnValue("value");
 *
 * public void setupValue(Integer value){
 *    value.setValue(value);
 * }
 *
 * public Integer getValue(){
 *     return (Integer)value.getValue();
 * }
 * 
* @version $Revision: 1.4 $ */ public class ReturnValue { private final String name; private Object value; /** * @param name the name used to identify the ReturnValue when an error is raised */ public ReturnValue(String name) { this.name = name; } /** * @return the value set using setValue * @exception junit.framework.AssertionFailedError throw if setValue has not been called */ public Object getValue() { AssertMo.assertNotNull("The return value \"" + name + "\" has not been set.", value); if(value instanceof Null){ return null; } return value; } /** * @param value value to be returned by getValue. null can be use to force getValue to return null. */ public void setValue(Object value) { if(value==null){ this.value = Null.NULL; }else{ this.value = value; } } /** * @param value value to be returned by getBooleanValue. Calling getValue after this method will return * a Boolean wrapper around the value. */ public void setValue(boolean value){ setValue(new Boolean(value)); } /** * @return the current value converted to a boolean */ public boolean getBooleanValue() { return ((Boolean)getValue()).booleanValue(); } /** * @return the current value converted to an int */ public int getIntValue() { return ((Number)getValue()).intValue(); } /** * @param value value to be returned by getIntValue. Calling getValue after this method will return * a Integer wrapper around the value. */ public void setValue(int value) { setValue(new Integer(value)); } /** * @param value value to be returned by getLongValue. Calling getValue after this method will return * a Long wrapper around the value. */ public void setValue(long value) { setValue(new Long(value)); } /** * @return the current value converted to an long */ public long getLongValue() { return ((Number)getValue()).longValue(); } }mockobjects-0.09/src/core/com/mockobjects/ReturnValues.java0000644000175000017500000000266307661772070025522 0ustar craftermcrafterm00000000000000package com.mockobjects; import junit.framework.*; import java.util.*; /** * Sequence values as required by MockMaker * This is a generic class that should have been introduced to the mockobjects code stream instead of * being separately included in org.mockobjects. * It is possibly similar to a ReturnObjectList? */ public class ReturnValues { private String myName; protected Vector myContents = new Vector(); private boolean myKeepUsingLastReturnValue = false; public ReturnValues() { this("Generate me with a useful name!",true); } public ReturnValues(String name, boolean keepUsingLastReturnValue) { myName = name; myKeepUsingLastReturnValue = keepUsingLastReturnValue; } public ReturnValues(boolean keepUsingLastReturnValue) { this("Generate me with a useful name!", keepUsingLastReturnValue); } public void add(Object element){ myContents.addElement(element); } public void addAll(Collection returnValues){ myContents.addAll(returnValues); } public Object getNext() { if (myContents.isEmpty()) { throw new AssertionFailedError(getClass().getName() + "[" + myName + "] was not setup with enough values"); } return pop(); } public boolean isEmpty() { return myContents.size() == 0; } protected Object pop() { Object result = myContents.firstElement(); boolean shouldNotRemoveElement = myContents.size() == 1 && myKeepUsingLastReturnValue; if (!shouldNotRemoveElement) { myContents.removeElementAt(0); } return result; } } mockobjects-0.09/src/core/com/mockobjects/Verifiable.java0000644000175000017500000000064007450657026025123 0ustar craftermcrafterm00000000000000package com.mockobjects; /** * A Verifiable is an object that can confirm at the end of a unit test that * the correct behvaiour has occurred. * * @see com.mockobjects.util.Verifier Verifier to check all the Verifiables in an object. */ public interface Verifiable { /** * Throw an AssertionFailedException if any expectations have not been met. */ public abstract void verify(); } mockobjects-0.09/src/core/com/mockobjects/VoidReturnValues.java0000644000175000017500000000123707661772070026340 0ustar craftermcrafterm00000000000000package com.mockobjects; /** * Sequence of void values as required by MockMaker * This is a generic class that should have been introduced to the mockobjects code stream instead of * being separately included in org.mockobjects. * It is possibly similar to a ReturnObjectList? */ public class VoidReturnValues extends ReturnValues { public VoidReturnValues() { } public VoidReturnValues(String name, boolean keepUsingLastReturnValue) { super(name, keepUsingLastReturnValue); } public VoidReturnValues(boolean keepUsingLastReturnValue) { super(keepUsingLastReturnValue); } public Object getNext() { return myContents.isEmpty() ? null : pop(); } } mockobjects-0.09/src/core/com/mockobjects/constraint/0000755000175000017500000000000010117310266024356 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/com/mockobjects/constraint/And.java0000644000175000017500000000125607570132763025744 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 B13media Ltd. All rights reserved. * * Created on February 10, 2002, 11:49 PM */ package com.mockobjects.constraint; /** Calculates the logical conjunction of two constraints. * Evaluation is shortcut, so that the second constraint is not * called if the first constraint returns false. */ public class And implements Constraint { Constraint _p1, _p2; public And(Constraint p1, Constraint p2) { _p1 = p1; _p2 = p2; } public boolean eval( Object o ) { return _p1.eval(o) && _p2.eval(o); } public String toString() { return "(" + _p1 + " and " + _p2 + ")"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/Constraint.java0000644000175000017500000000071307564236615027367 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:21 PM */ package com.mockobjects.constraint; /** A constraint over acceptable values. */ public interface Constraint { /** Evaluates the constraint for argument o. * * @return * true if o meets the constraint, * false if it does not. */ boolean eval( Object o ); } mockobjects-0.09/src/core/com/mockobjects/constraint/IsAnything.java0000644000175000017500000000065207564236616027323 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:33 PM */ package com.mockobjects.constraint; /** A constraint that always returns true. */ public class IsAnything implements Constraint { public IsAnything() { } public boolean eval(Object o) { return true; } public String toString() { return "any value"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsCloseTo.java0000644000175000017500000000133007564236615027103 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; /** Is the value a number equal to a value within some range of * acceptable error? */ public class IsCloseTo implements Constraint { private double _error; private double _value; public IsCloseTo( double value, double error ) { _error = error; _value = value; } public boolean eval( Object arg ) { double arg_value = ((Number)arg).doubleValue(); return Math.abs( (arg_value - _value) ) <= _error; } public String toString() { return "a numeric value within " + _error + " of " + _value; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsEqual.java0000644000175000017500000000166307661772074026615 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; import java.util.Arrays; import com.mockobjects.dynamic.DynamicUtil; /** Is the value equal to another value, as tested by the * {@link java.lang.Object#equals} method? */ public class IsEqual implements Constraint { private Object _object; public IsEqual( Object equalArg) { if(equalArg instanceof Object[]) { _object = Arrays.asList((Object[])equalArg); } else { _object = equalArg; } } public boolean eval( Object arg ) { if(arg instanceof Object[]) { arg = Arrays.asList((Object[])arg); } return arg.equals(_object); } public String toString() { return " = " + DynamicUtil.proxyToString(_object); } public boolean equals(Object anObject) { return eval(anObject); } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsEventFrom.java0000644000175000017500000000245507570132763027445 0ustar craftermcrafterm00000000000000/** Created on Jun 28, 2002 by npryce * Copyright (c) B13media Ltd. */ package com.mockobjects.constraint; import java.util.EventObject; /** Tests if the value is an event announced by a specific object. */ public class IsEventFrom implements Constraint { private Class _event_class; private Object _source; /** Constructs an IsEventFrom predicate that returns true for any object * derived from {@link java.util.EventObject} announced by * source. */ public IsEventFrom( Object source ) { this( EventObject.class, source ); } /** Constructs an IsEventFrom predicate that returns true for any object * derived from event_class announced by * source. */ public IsEventFrom( Class event_class, Object source ) { _event_class = event_class; _source = source; } public boolean eval( Object o ) { if( o instanceof EventObject ) { EventObject ev = (EventObject)o; return _event_class.isInstance(o) && ev.getSource() == _source; } else { return false; } } public String toString() { return "an event of type " + _event_class.getName() + " from " + _source; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsGreaterThan.java0000644000175000017500000000110407661772074027740 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; /** * Is the value greater than another {@link java.lang.Comparable} value? */ public class IsGreaterThan implements Constraint { private Comparable _object; public IsGreaterThan( Comparable o ) { _object = o; } public boolean eval( Object arg ) { return _object.compareTo(arg) < 0; } public String toString() { return "a value greater than <" + _object + ">"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsInstanceOf.java0000644000175000017500000000136407564236616027574 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; /** Tests whether the value is an instance of a class. */ public class IsInstanceOf implements Constraint { private Class _class; /** Creates a new instance of IsInstanceOf * * @param theclass * The predicate evaluates to true for instances of this class * or one of its subclasses. */ public IsInstanceOf( Class theclass ) { _class = theclass; } public boolean eval( Object arg ) { return _class.isInstance( arg ); } public String toString() { return "an instance of <" + _class.getName() + ">"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsLessThan.java0000644000175000017500000000106207661772074027260 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; /** Is the value less than another {@link java.lang.Comparable} value? */ public class IsLessThan implements Constraint { private Comparable _object; public IsLessThan(Comparable o) { _object = o; } public boolean eval( Object arg ) { return _object.compareTo(arg) > 0; } public String toString() { return "a value less than <" + _object + ">"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsNot.java0000644000175000017500000000100707570132763026270 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; /** Calculates the logical negation of a constraint. */ public class IsNot implements Constraint { private Constraint _predicate; public IsNot( Constraint p ) { _predicate = p; } public boolean eval( Object arg ) { return !_predicate.eval(arg); } public String toString() { return "not " + _predicate; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsNull.java0000644000175000017500000000060107564236615026445 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:33 PM */ package com.mockobjects.constraint; /** Is the value null? */ public class IsNull implements Constraint { public IsNull() { } public boolean eval(Object o) { return o == null; } public String toString() { return "null"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/IsSame.java0000644000175000017500000000125507570132763026422 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; /** Is the value the same object as another value? */ public class IsSame implements Constraint { private Object _object; /** Creates a new instance of IsSame * * @param o * The predicate evaluates to true only when the argument is * this object. */ public IsSame(Object o) { _object = o; } public boolean eval( Object arg ) { return arg == _object; } public String toString() { return "the same object as <" + _object + ">"; } } mockobjects-0.09/src/core/com/mockobjects/constraint/Or.java0000644000175000017500000000125407570132763025620 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 B13media Ltd. All rights reserved. * * Created on February 10, 2002, 11:49 PM */ package com.mockobjects.constraint; /** Calculates the logical disjunction of two constraints. * Evaluation is shortcut, so that the second constraint is not * called if the first constraint returns true. */ public class Or implements Constraint { Constraint _p1, _p2; public Or( Constraint p1, Constraint p2 ) { _p1 = p1; _p2 = p2; } public boolean eval( Object o ) { return _p1.eval(o) || _p2.eval(o); } public String toString() { return "(" + _p1 + " or " + _p2 + ")"; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/0000755000175000017500000000000010117310266023616 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/com/mockobjects/dynamic/AnyConstraintMatcher.java0000644000175000017500000000041107661772067030602 0ustar craftermcrafterm00000000000000/* * Created on 20-Apr-03 */ package com.mockobjects.dynamic; public class AnyConstraintMatcher implements ConstraintMatcher { public boolean matches(Object[] args) { return true; } public Object[] getConstraints() { return new String[] {"ANY"}; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/C.java0000644000175000017500000000723607661772067024700 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 14, 2002, 4:02 PM */ package com.mockobjects.dynamic; import com.mockobjects.constraint.*; /** Convenient factory functions and constants for building predicates. */ public abstract class C { public static final IsAnything IS_ANYTHING = new IsAnything(); public static final IsNull IS_NULL = new IsNull(); public static final Constraint IS_NOT_NULL = not(IS_NULL); public static final Constraint IS_TRUE = eq(new Boolean(true)); public static final Constraint IS_FALSE = eq(new Boolean(false)); public static final Constraint IS_ZERO = eq(new Integer(0)); public static final Constraint IS_NOT_ZERO = not(IS_ZERO); public static final ConstraintMatcher NO_ARGS = new FullConstraintMatcher(new Constraint[0]); public static final ConstraintMatcher ANY_ARGS = new AnyConstraintMatcher(); public static Constraint same( Object o ) { return new IsSame(o); } public static Constraint eq( Object o ) { return new IsEqual(o); } public static ConstraintMatcher eq( Object arg0, Object arg1 ) { return args(eq(arg0), eq(arg1)); } public static ConstraintMatcher eq( Object arg0, Object arg1, Object arg2 ) { return args(eq(arg0), eq(arg1), eq(arg2)); } public static Constraint eq( int n ) { return new IsEqual( new Integer(n) ); } public static Constraint eq( long l ) { return new IsEqual( new Long(l) ); } public static Constraint eq( double d ) { return new IsEqual( new Double(d) ); } public static Constraint gt( int n ) { return new IsGreaterThan( new Integer(n) ); } public static Constraint gt( long l ) { return new IsGreaterThan( new Long(l) ); } public static Constraint gt( double d ) { return new IsGreaterThan( new Double(d) ); } public static Constraint gt( char c ) { return new IsGreaterThan( new Character(c) ); } public static Constraint lt( int n ) { return new IsLessThan( new Integer(n) ); } public static Constraint lt( long l ) { return new IsLessThan( new Long(l) ); } public static Constraint lt( double d ) { return new IsLessThan( new Double(d) ); } public static Constraint lt( char c ) { return new IsLessThan( new Character(c) ); } public static Constraint not( Constraint p ) { return new IsNot(p); } public static Constraint and( Constraint p1, Constraint p2 ) { return new And(p1,p2); } public static Constraint or( Constraint p1, Constraint p2 ) { return new Or(p1,p2); } public static Constraint isA( Class c ) { return new IsInstanceOf(c); } /* Helper methods for succinctly constructing Constraint arrays */ public static ConstraintMatcher args() { return NO_ARGS; } public static ConstraintMatcher args(Constraint p) { return new FullConstraintMatcher(new Constraint[]{p}); } public static ConstraintMatcher args(Constraint p1, Constraint p2) { return new FullConstraintMatcher(new Constraint[]{p1, p2}); } public static ConstraintMatcher args(Constraint p1, Constraint p2, Constraint p3) { return new FullConstraintMatcher(new Constraint[]{p1, p2, p3}); } public static ConstraintMatcher anyArgs( int argCount) { Constraint[] constraints = new Constraint[argCount]; for (int i = 0; i < constraints.length; i++) { constraints[i] = new IsAnything(); } return new FullConstraintMatcher(constraints); } } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallBag.java0000644000175000017500000000366207661772067026002 0ustar craftermcrafterm00000000000000/* * Created on 04-Apr-2003 */ package com.mockobjects.dynamic; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class CallBag extends CallCollection implements Callable, CallableAddable { private List expectedCalls = new ArrayList(); private List expectedMatches = new ArrayList(); public CallBag() { } public void reset() { this.expectedCalls.clear(); this.expectedMatches.clear(); } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { Callable matchingCall = findMatchingCall(methodName, args, this.expectedCalls); if(matchingCall == null) { matchingCall = findMatchingCall(methodName, args, this.expectedMatches); } if(matchingCall == null) { throw createUnexpectedCallError(methodName, args); } return matchingCall.call(mock, methodName, args); } private Callable findMatchingCall(String methodName, Object[] args, List callList) { for (Iterator call = callList.iterator(); call.hasNext();) { Callable element = (Callable) call.next(); if (element.matches(methodName, args)) { return element; } } return null; } public String getDescription() { if (this.expectedCalls.isEmpty()) { return "no methods"; } else { StringBuffer buf = new StringBuffer(); buf.append("one of:\n"); for (Iterator i = this.expectedCalls.iterator(); i.hasNext();) { buf.append(((Callable) i.next()).getDescription()); buf.append("\n"); } return buf.toString(); } } public boolean matches(String methodName, Object[] args) { throw new Error("not implemented"); } public void verify() { for (Iterator call = this.expectedCalls.iterator(); call.hasNext();) { Callable element = (Callable) call.next(); element.verify(); } } public void addExpect(Callable call) { this.expectedCalls.add(call); } public void addMatch(Callable call) { this.expectedMatches.add(call); } } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallCollection.java0000644000175000017500000000114207661772067027373 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; import junit.framework.AssertionFailedError; abstract public class CallCollection extends Object { protected AssertionFailedError createUnexpectedCallError(String methodName, Object[] args) { StringBuffer buf = new StringBuffer(); buf.append("Unexpected call: "); buf.append(DynamicUtil.methodToString(methodName, args)); buf.append("\n"); buf.append("Expected "); buf.append(getDescription()); return new AssertionFailedError(buf.toString()); } abstract protected String getDescription(); } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallFactory.java0000644000175000017500000000052207662267447026712 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; public interface CallFactory { Callable createReturnStub( Object result ); Callable createThrowStub( Throwable throwable ); Callable createVoidStub(); Callable createCallExpectation( Callable call ); Callable createCallSignature( String methodName, ConstraintMatcher constraints, Callable call ); } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallOnceExpectation.java0000644000175000017500000000177107662270504030366 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; import junit.framework.*; public class CallOnceExpectation implements Callable { private Callable delegate; private boolean wasCalled = false; public CallOnceExpectation( Callable delegate ) { this.delegate = delegate; } public String getDescription() { return delegate.getDescription() + " [" + (wasCalled ? "" : "not ") + "called]"; } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { wasCalled = true; return delegate.call( mock, methodName, args ); } public boolean matches(String methodName, Object[] args) { return (!wasCalled) && delegate.matches( methodName, args ); } public void verify() { if( !wasCalled ) { throw new AssertionFailedError( delegate.getDescription() + " was expected but not called" ); } delegate.verify(); } // Implemented to aid visualisation in an IDE debugger public String toString() { return Mock.className(this.getClass()) + "(" + this.getDescription() + ")"; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallSequence.java0000644000175000017500000000427307661772067027060 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; import java.util.ArrayList; import java.util.Iterator; import junit.framework.AssertionFailedError; public class CallSequence extends CallCollection implements Callable, CallableAddable { private ArrayList expectedCalls = new ArrayList(); private CallBag matchedCalls = new CallBag(); int callIndex = 0; public void reset() { this.expectedCalls.clear(); this.matchedCalls.reset(); } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { if (expectedCalls.size() == 0) throw new AssertionFailedError("no methods defined on mock, received: " + DynamicUtil.methodToString(methodName, args)); if (callIndex == expectedCalls.size()) throw new AssertionFailedError("mock called too many times, received: " + DynamicUtil.methodToString(methodName, args)); Callable nextCall = (Callable)expectedCalls.get(callIndex++); if (nextCall.matches(methodName, args)) return nextCall.call(mock, methodName, args); try { return matchedCalls.call(mock, methodName, args); } catch (AssertionFailedError ex) { throw createUnexpectedCallError(methodName, args); } } public String getDescription() { if (expectedCalls.isEmpty()) { return "no methods"; } else { StringBuffer buf = new StringBuffer(); buf.append("in sequence:\n"); int j=0; for (Iterator i = expectedCalls.iterator(); i.hasNext();) { buf.append(((Callable)i.next()).getDescription()); if (j++==(callIndex-1)) buf.append(" <<< Next Expected Call"); buf.append("\n"); } return buf.toString(); } } public boolean matches(String methodName, Object[] args) { throw new AssertionFailedError("matches() operation not supported in CallSequence"); } public void addExpect(Callable call) { expectedCalls.add(call); } public void addMatch(Callable call) { matchedCalls.addMatch(call); } public void verify() { for (Iterator iter = expectedCalls.iterator(); iter.hasNext();) { Callable callable = (Callable) iter.next(); callable.verify(); } } } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallSignature.java0000644000175000017500000000202307662265315027232 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; import junit.framework.Assert; public class CallSignature extends Assert implements Callable { private String methodName; private ConstraintMatcher constraints; private Callable delegate; public CallSignature( String methodName, ConstraintMatcher constraints, Callable delegate ) { this.methodName = methodName; this.constraints = constraints; this.delegate = delegate; } public Object call( Mock mock, String methodName, Object[] args ) throws Throwable { return delegate.call( mock, methodName, args ); } public void verify() { delegate.verify(); } public boolean matches(String methodName, Object[] args) { return this.methodName.equals(methodName) && constraints.matches(args); } public String getDescription() { return DynamicUtil.methodToString(methodName, constraints.getConstraints()); } // Implemented to aid visualisation in an IDE debugger public String toString() { return Mock.className(this.getClass()) + "(" + this.getDescription() + ")"; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallStub.java0000644000175000017500000000037707661772067026226 0ustar craftermcrafterm00000000000000/* * Created on 07-Apr-2003 */ package com.mockobjects.dynamic; /** * @author dev */ public abstract class CallStub implements Callable { public boolean matches(String methodName, Object[] args) { return true; } public void verify() { } } mockobjects-0.09/src/core/com/mockobjects/dynamic/Callable.java0000644000175000017500000000041207661772067026202 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; import com.mockobjects.*; public interface Callable extends Verifiable { String getDescription(); Object call( Mock mock, String methodName, Object[] args ) throws Throwable; boolean matches(String methodName, Object[] args); } mockobjects-0.09/src/core/com/mockobjects/dynamic/CallableAddable.java0000644000175000017500000000036007661772067027441 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; public interface CallableAddable extends Callable { void addExpect(Callable call); void addMatch(Callable call); /** * Resets all expected calls and expected matches. */ void reset(); }mockobjects-0.09/src/core/com/mockobjects/dynamic/ConstraintMatcher.java0000644000175000017500000000024607661772067030140 0ustar craftermcrafterm00000000000000/* * Created on 20-Apr-03 */ package com.mockobjects.dynamic; public interface ConstraintMatcher { boolean matches(Object[] args); Object[] getConstraints(); } mockobjects-0.09/src/core/com/mockobjects/dynamic/DefaultCallFactory.java0000644000175000017500000000114507662270504030205 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; public class DefaultCallFactory implements CallFactory { public Callable createReturnStub(Object result) { return new ReturnStub(result); } public Callable createThrowStub( Throwable exception ) { return new ThrowStub(exception); } public Callable createCallExpectation(Callable call) { return new CallOnceExpectation(call); } public Callable createCallSignature(String methodName, ConstraintMatcher constraints, Callable call) { return new CallSignature( methodName, constraints, call ); } public Callable createVoidStub() { return new VoidStub(); } } mockobjects-0.09/src/core/com/mockobjects/dynamic/DynamicUtil.java0000644000175000017500000000652207661772067026735 0ustar craftermcrafterm00000000000000/* * Created on 16-Apr-2003 */ package com.mockobjects.dynamic; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.*; import java.util.List; public class DynamicUtil { public static Object[] asObjectArray(Object primitiveArray) { if (primitiveArray instanceof Object[]) { return (Object[])primitiveArray; } List result = new ArrayList(); if (primitiveArray instanceof boolean[]) { boolean[] booleanArray = (boolean[]) primitiveArray; for (int i = 0; i < booleanArray.length; i++) { result.add(new Boolean(booleanArray[i])); } } else if (primitiveArray instanceof char[]) { char[] charArray = (char[]) primitiveArray; for (int i = 0; i < charArray.length; i++) { result.add(new Character(charArray[i])); } } else if (primitiveArray instanceof byte[]) { byte[] byteArray = (byte[]) primitiveArray; for (int i = 0; i < byteArray.length; i++) { result.add(new Byte(byteArray[i])); } } else if (primitiveArray instanceof short[]) { short[] shortArray = (short[]) primitiveArray; for (int i = 0; i < shortArray.length; i++) { result.add(new Short(shortArray[i])); } } else if (primitiveArray instanceof int[]) { int[] intArray = (int[]) primitiveArray; for (int i = 0; i < intArray.length; i++) { result.add(new Integer(intArray[i])); } } else if (primitiveArray instanceof long[]) { long[] longArray = (long[]) primitiveArray; for (int i = 0; i < longArray.length; i++) { result.add(new Long(longArray[i])); } } else if (primitiveArray instanceof float[]) { float[] floatArray = (float[]) primitiveArray; for (int i = 0; i < floatArray.length; i++) { result.add(new Float(floatArray[i])); } } else if (primitiveArray instanceof double[]) { double[] doulbeArray = (double[]) primitiveArray; for (int i = 0; i < doulbeArray.length; i++) { result.add(new Float(doulbeArray[i])); } } else { throw new RuntimeException("Unknown primitive data type for Object[] conversion " + primitiveArray.toString()); } return result.toArray(); } public static String proxyToString(Object element) { if (Proxy.isProxyClass(element.getClass())) { try { Method mockNameMethod = Mock.class.getDeclaredMethod("getMockName", new Class[0]); Object debugableResult = Proxy.getInvocationHandler(element).invoke(element, mockNameMethod, new Object[0]); return debugableResult.toString(); } catch (Throwable e) { return element.getClass().getName(); } } if (element.getClass().isArray()) { StringBuffer buf = new StringBuffer(); buf.append("["); join(asObjectArray(element),buf); buf.append("]"); return buf.toString(); } else { return element.toString(); } } public static String methodToString(String name, Object[] args) { StringBuffer buf = new StringBuffer(); buf.append(name); buf.append("("); join(args,buf); buf.append(")"); return buf.toString(); } public static void join(Object[] elements, StringBuffer buf) { for (int i = 0; i < elements.length; i++) { if (i > 0) { buf.append(", "); } Object element = elements[i]; if (element.getClass().isArray()) { buf.append("["); join(asObjectArray(element), buf); buf.append("]"); } else { buf.append("<"); buf.append(proxyToString(element)); buf.append(">"); } } } } mockobjects-0.09/src/core/com/mockobjects/dynamic/FullConstraintMatcher.java0000644000175000017500000000161007661772067030757 0ustar craftermcrafterm00000000000000/* * Created on 20-Apr-03 */ package com.mockobjects.dynamic; import com.mockobjects.constraint.Constraint; public class FullConstraintMatcher implements ConstraintMatcher { private Constraint[] constraints; public FullConstraintMatcher(Constraint[] constraints) { this.constraints = constraints; } public FullConstraintMatcher(Constraint c1) { this(new Constraint[] {c1}); } public FullConstraintMatcher(Constraint c1, Constraint c2) { this(new Constraint[] {c1, c2}); } public FullConstraintMatcher(Constraint c1, Constraint c2, Constraint c3) { this(new Constraint[] {c1, c2, c3}); } public boolean matches(Object[] args) { if( args.length != constraints.length ) return false; for (int i = 0; i < args.length; i++) { if( !constraints[i].eval(args[i]) ) return false; } return true; } public Object[] getConstraints() { return constraints; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/Mock.java0000644000175000017500000002225607662630527025401 0ustar craftermcrafterm00000000000000package com.mockobjects.dynamic; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import junit.framework.AssertionFailedError; import com.mockobjects.Verifiable; import com.mockobjects.constraint.Constraint; public class Mock implements InvocationHandler, Verifiable { private String name; private Object proxy; private CallFactory callFactory; private CallableAddable callSequence; public Mock(CallFactory callFactory, CallableAddable callableAddable, Class mockedClass, String name) { this.name = name; this.callFactory = callFactory; this.callSequence = callableAddable; this.proxy = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { mockedClass }, this); } public Mock(Class mockedClass, String nonDefaultName) { this(new DefaultCallFactory(), new CallBag(), mockedClass, nonDefaultName); } public Mock(Class mockedClass) { this(mockedClass, mockNameFromClass(mockedClass)); } public void reset() { this.callSequence.reset(); } public static String mockNameFromClass(Class c) { return "mock" + className(c); } public static String className(Class c) { String name = c.getName(); int dotIndex = name.lastIndexOf('.'); if (dotIndex >= 0) { return name.substring(dotIndex + 1); } else { return name; } } private ConstraintMatcher createConstraintMatcher(Object constraintArg) { // Can't overload this method as callee had an Object parameter, and java // doesn't do a secondary dispatch on the true underlying type if (constraintArg instanceof Constraint[]) { // to support possible legacy usage of new Contraint[] {...} return new FullConstraintMatcher((Constraint[])constraintArg); } else if (constraintArg instanceof Constraint) { // to support usage of C.lt(5) type constraints return C.args((Constraint)constraintArg); } else { // normal usage of the overloaded expect/match object parameter return C.args(C.eq(constraintArg)); } } public String getMockName() { return this.name; } public String toString() { return this.name; } public Object proxy() { return this.proxy; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (isCheckingEqualityOnProxy(method, args)) { return new Boolean(args[0] == this.proxy); } else if (isMockNameGetter(method, args)) { return this.getMockName(); } else { return callSequence.call(this, method.getName(), (args == null ? new Object[0] : args)); } } catch (AssertionFailedError ex) { throw new AssertionFailedError(name + ": " + ex.getMessage()); } } private boolean isCheckingEqualityOnProxy(Method method, Object[] args) { return (method.getName().equals("equals")) && (args.length == 1) && (Proxy.isProxyClass(args[0].getClass())); } private boolean isMockNameGetter(Method method, Object[] args) { return (method.getName().equals("getMockName")) && (args.length == 0); } public void verify() { try { callSequence.verify(); } catch (AssertionFailedError ex) { throw new AssertionFailedError(name + ": " + ex.getMessage()); } } public void expect(String methodName) { expect(methodName, C.NO_ARGS); } public void expect(String methodName, Object singleEqualArg) { expect(methodName, createConstraintMatcher(singleEqualArg)); } public void expect(String methodName, ConstraintMatcher args) { callSequence.addExpect(callFactory.createCallExpectation(callFactory.createCallSignature(methodName, args, callFactory.createVoidStub()))); } public void expectAndReturn(String methodName, Object result) { this.expectAndReturn(methodName, C.NO_ARGS, result); } public void expectAndReturn(String methodName, boolean result) { this.expectAndReturn(methodName, new Boolean(result)); } public void expectAndReturn(String methodName, int result) { this.expectAndReturn(methodName, new Integer(result)); } public void expectAndReturn(String methodName, Object singleEqualArg, Object result) { this.expectAndReturn(methodName, createConstraintMatcher(singleEqualArg), result); } public void expectAndReturn(String methodName, Object singleEqualArg, boolean result) { this.expectAndReturn(methodName, singleEqualArg, new Boolean(result)); } public void expectAndReturn(String methodName, Object singleEqualArg, int result) { this.expectAndReturn(methodName, singleEqualArg, new Integer(result)); } public void expectAndReturn(String methodName, ConstraintMatcher args, Object result) { callSequence.addExpect(callFactory.createCallExpectation(callFactory.createCallSignature(methodName, args, callFactory.createReturnStub(result)))); } public void expectAndReturn(String methodName, ConstraintMatcher args, boolean result) { this.expectAndReturn(methodName, args, new Boolean(result)); } public void expectAndReturn(String methodName, ConstraintMatcher args, int result) { this.expectAndReturn(methodName, args, new Integer(result)); } public void expectAndThrow(String methodName, Throwable exception) { this.expectAndThrow(methodName, C.NO_ARGS, exception); } public void expectAndThrow(String methodName, Object singleEqualArg, Throwable exception) { this.expectAndThrow(methodName, createConstraintMatcher(singleEqualArg), exception); } public void expectAndThrow(String methodName, ConstraintMatcher args, Throwable exception) { callSequence.addExpect(callFactory.createCallExpectation(callFactory.createCallSignature(methodName, args, callFactory.createThrowStub(exception)))); } public void matchAndReturn(String methodName, Object result) { this.matchAndReturn(methodName, C.NO_ARGS, result); } public void matchAndReturn(String methodName, boolean result) { this.matchAndReturn(methodName, new Boolean(result)); } public void matchAndReturn(String methodName, int result) { this.matchAndReturn(methodName, new Integer(result)); } public void matchAndReturn(String methodName, Object singleEqualArg, Object result) { this.matchAndReturn(methodName, createConstraintMatcher(singleEqualArg), result); } public void matchAndReturn(String methodName, boolean singleEqualArg, Object result) { this.matchAndReturn(methodName, new Boolean(singleEqualArg), result); } public void matchAndReturn(String methodName, int singleEqualArg, Object result) { this.matchAndReturn(methodName, new Integer(singleEqualArg), result); } public void matchAndReturn(String methodName, Object singleEqualArg, boolean result) { this.matchAndReturn(methodName, singleEqualArg, new Boolean(result)); } public void matchAndReturn(String methodName, Object singleEqualArg, int result) { this.matchAndReturn(methodName, singleEqualArg, new Integer(result)); } public void matchAndReturn(String methodName, ConstraintMatcher args, Object result) { callSequence.addMatch(callFactory.createCallSignature(methodName, args, callFactory.createReturnStub(result))); } public void matchAndReturn(String methodName, ConstraintMatcher args, boolean result) { this.matchAndReturn(methodName, args, new Boolean(result)); } public void matchAndReturn(String methodName, ConstraintMatcher args, int result) { this.matchAndReturn(methodName, args, new Integer(result)); } public void matchAndThrow(String methodName, Throwable throwable) { this.matchAndThrow(methodName, C.NO_ARGS, throwable); } public void matchAndThrow(String methodName, Object singleEqualArg, Throwable throwable) { this.matchAndThrow(methodName, createConstraintMatcher(singleEqualArg), throwable); } public void matchAndThrow(String methodName, boolean singleEqualArg, Throwable throwable) { this.matchAndThrow(methodName,new Boolean(singleEqualArg), throwable); } public void matchAndThrow(String methodName, int singleEqualArg, Throwable throwable) { this.matchAndThrow(methodName,new Integer(singleEqualArg), throwable); } public void matchAndThrow(String methodName, ConstraintMatcher args, Throwable throwable) { callSequence.addMatch(callFactory.createCallSignature(methodName, args, callFactory.createThrowStub(throwable))); } /** @deprecated @see OrderedMock */ public void expect(String methodName, CallSequence deprecated) { throw new AssertionFailedError("method is deprecated! Use: new OrderedMock() instead..."); } /** @deprecated @see OrderedMock */ public void expectAndReturn(String methodName, CallSequence deprecated, Object result) { throw new AssertionFailedError("method is deprecated! Use: new OrderedMock() instead..."); } /** @deprecated @see OrderedMock */ public void expectAndThrow(String methodName, CallSequence deprecated, Throwable throwable) { throw new AssertionFailedError("method is deprecated! Use: new OrderedMock() instead..."); } /** @deprecated @see expect */ public void expectVoid(String methodName, ConstraintMatcher args) { this.expect(methodName, args); } /** @deprecated @see expect */ public void expectVoid(String methodName, Object equalArg) { this.expect(methodName,equalArg); } /** @deprecated @see expect */ public void expectVoid(String methodName) { this.expect(methodName); } /** @deprecated Not required, as if methodName is called, you will get a an exception */ public void expectNotCalled(String methodName) { } } mockobjects-0.09/src/core/com/mockobjects/dynamic/OrderedMock.java0000644000175000017500000000056407661772067026711 0ustar craftermcrafterm00000000000000/* * Created on 11-Apr-2003 */ package com.mockobjects.dynamic; /** * @author Administrator */ public class OrderedMock extends Mock { public OrderedMock(Class mockedClass) { this(mockedClass, mockNameFromClass(mockedClass)); } public OrderedMock(Class mockedClass, String name) { super(new DefaultCallFactory(), new CallSequence(),mockedClass, name); } } mockobjects-0.09/src/core/com/mockobjects/dynamic/ReturnStub.java0000644000175000017500000000063207661772067026624 0ustar craftermcrafterm00000000000000/* * Created on 07-Apr-2003 */ package com.mockobjects.dynamic; /** * @author dev */ public class ReturnStub extends CallStub { private Object result; public ReturnStub( Object result ) { this.result = result; } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { return result; } public String getDescription() { return "returns <" + result + ">"; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/ThrowStub.java0000644000175000017500000000065707661772067026457 0ustar craftermcrafterm00000000000000/* * Created on 07-Apr-2003 */ package com.mockobjects.dynamic; /** * @author dev */ public class ThrowStub extends CallStub { private Throwable throwable; public ThrowStub( Throwable throwable ) { this.throwable = throwable; } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { throw throwable; } public String getDescription() { return "throws <" + throwable + ">"; } } mockobjects-0.09/src/core/com/mockobjects/dynamic/VoidStub.java0000644000175000017500000000043107661772067026243 0ustar craftermcrafterm00000000000000/* * Created on 11-Apr-2003 */ package com.mockobjects.dynamic; public class VoidStub extends CallStub { public String getDescription() { return "returns "; } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { return null; } } mockobjects-0.09/src/core/com/mockobjects/util/0000755000175000017500000000000010117310266023147 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/com/mockobjects/util/AssertMo.java0000644000175000017500000000544007661772074025575 0ustar craftermcrafterm00000000000000package com.mockobjects.util; import junit.framework.Assert; import junit.framework.AssertionFailedError; import com.mockobjects.Verifiable; public class AssertMo extends Assert { protected AssertMo() { super(); } public static void assertEquals( String description, Object[] expectedArray, Object[] actualArray) { assertEquals( description + " (different lengths)", expectedArray.length, actualArray.length); for (int i = 0; i < expectedArray.length; i++) { assertEquals( description + " (element " + i + ")", expectedArray[i], actualArray[i]); } } public static void assertExcludes( String description, String excludeString, String targetString) { assertTrue( description + "\nExclude String: " + excludeString + "\n Target String: " + targetString, targetString.indexOf(excludeString) == -1); } public static void assertIncludes( String description, String includeString, String targetString) { assertTrue( description + "\nInclude String: " + includeString + "\n Target String: " + targetString, targetString.indexOf(includeString) != -1); } public static void assertStartsWith( String description, String startString, String targetString) { assertTrue( description + "\n Start String: " + startString + "\nTarget String: " + targetString, targetString.startsWith(startString)); } public static void assertVerifyFails(Verifiable aVerifiable) { boolean threwException = false; try { aVerifiable.verify(); } catch (AssertionFailedError ex) { threwException = true; } assertTrue("Should not have verified", threwException); } static protected void failNotEquals( String message, Object expected, Object actual) { String formatted = ""; if (message != null) formatted = message + " "; fail( formatted + "\nExpected:<" + expected + ">\nReceived:<" + actual + ">"); } public static void notImplemented(String mockName) { throw new NotImplementedException("Not Implemented in " + mockName); } public static void assertFails(String message, Runnable runnable) { try { runnable.run(); } catch (AssertionFailedError expected) { return; } fail(message); } } mockobjects-0.09/src/core/com/mockobjects/util/ErrorLogger.java0000644000175000017500000000036007331064400026242 0ustar craftermcrafterm00000000000000package com.mockobjects.util; public class ErrorLogger { public ErrorLogger() { super(); } public void error(String errorMsg, Exception ex) { System.err.println(errorMsg + " - Exception(" + ex + ")"); } } mockobjects-0.09/src/core/com/mockobjects/util/NotImplementedException.java0000644000175000017500000000072507331064400030621 0ustar craftermcrafterm00000000000000package com.mockobjects.util; import junit.framework.AssertionFailedError; public class NotImplementedException extends AssertionFailedError { /** * NotImplementedException constructor comment. */ public NotImplementedException() { super(); } /** * NotImplementedException constructor comment. * @param message java.lang.String */ public NotImplementedException(String message) { super(message); } } mockobjects-0.09/src/core/com/mockobjects/util/Null.java0000644000175000017500000000701607450657026024746 0ustar craftermcrafterm00000000000000package com.mockobjects.util; /** * A class that represents the null value. * The {@link com.mockobjects.util.Null Null} class is used when an * {@link com.mockobjects.Expectation Expectation} is set to expect nothing. *

* Example usage: *

 * public class MockX {
 *    private Expectation... anExpectation = new Expectation...(...);
 *
 *    public MockX() {
 *       anExpectation.setExpectNothing();
 *    }
 *
 *    public void setAnExpectation(Object value) {
 *       anExpectation.setExpected(value);
 *    }
 *
 *    public void setActual(Object value) {
 *       anExpectation.setActual(value);
 *    }
 * }
 * 
* The act of calling {@link com.mockobjects.Expectation#setExpectNothing() Expectation.setExpectNothing()} * tells the expectation that it should expect no values to change. Since * all {@link com.mockobjects.util.Null Null} objects are equal to themselves, * most expectations set their expected value to an instance of * {@link com.mockobjects.util.Null Null}, and at the same time, set their actual * value to another instance of {@link com.mockobjects.util.Null Null}. * This way, when {@link com.mockobjects.Verifiable#verify() verify()} checks * expectations, they will compare two {@link com.mockobjects.util.Null Null} * objects together, which is guaranteed to succeed. * @author Francois Beausoleil (fbos@users.sourceforge.net) * @version $Id: Null.java,v 1.3 2002/03/28 18:16:54 custommonkey Exp $ */ public class Null { /** * The default description for all {@link com.mockobjects.util.Null Null} * objects. * This String is equal to "Null". */ public static final String DEFAULT_DESCRIPTION = "Null"; /** * A default {@link com.mockobjects.util.Null Null} object. * Instead of always instantiating new {@link com.mockobjects.util.Null Null} * objects, consider using a reference to this object instead. This way, * the virtual machine will not be taking the time required to instantiate * an object everytime it is required. */ public static final Null NULL = new Null(); /** * The description of this {@link com.mockobjects.util.Null Null} object. */ final private String myDescription; /** * Instantiates a new {@link com.mockobjects.util.Null Null} object with * the default description. * @see com.mockobjects.util.Null#DEFAULT_DESCRIPTION */ public Null() { this(DEFAULT_DESCRIPTION); } /** * Instantiates a new {@link com.mockobjects.util.Null Null} object and * sets it's description. * @param description */ public Null(String description) { super(); myDescription = description; } /** * Determines equality between two objects. * {@link com.mockobjects.util.Null Null} objects are only equal to * another instance of themselves. * @param other */ public boolean equals(Object other) { return other instanceof Null; } /** * Returns this {@link com.mockobjects.util.Null Null} object's hashCode. * All {@link com.mockobjects.util.Null Null} return the same * hashCode value. */ public int hashCode() { return 0; } /** * Returns a string representation of this {@link com.mockobjects.util.Null Null} * object. * This merely returns the string passed to the constructor initially. */ public String toString() { return myDescription; } } mockobjects-0.09/src/core/com/mockobjects/util/SuiteBuilder.java0000644000175000017500000000262407331064400026416 0ustar craftermcrafterm00000000000000package com.mockobjects.util; import junit.framework.*; import java.lang.reflect.*; /** * Singleton to fill in a JUnit Test composite for use in a suite method. */ public class SuiteBuilder { public static TestSuite buildTest(Class allTestsClass) { return buildTest(allTestsClass, new ErrorLogger()); } public static TestSuite buildTest( Class allTestsClass, ErrorLogger logger) { TestSuite result = new TestSuite(); Method[] methods = allTestsClass.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; String name = m.getName(); if (isAddMethod(m)) { try { Object[] args = new Object[] { result }; m.invoke(allTestsClass, args); } catch (Exception ex) { logger.error("Error creating Test from " + name, ex); } } } return result; } public static boolean isAddMethod(Method m) { String name = m.getName(); Class[] parameters = m.getParameterTypes(); Class returnType = m.getReturnType(); return parameters.length == 1 && name.startsWith("add") && returnType.equals(Void.TYPE) && Modifier.isPublic(m.getModifiers()) && Modifier.isStatic(m.getModifiers()); } } mockobjects-0.09/src/core/com/mockobjects/util/TestCaseMo.java0000644000175000017500000000131307560517670026037 0ustar craftermcrafterm00000000000000package com.mockobjects.util; import junit.framework.*; import junit.awtui.TestRunner; import com.mockobjects.Verifiable; /** * Provides a level of indirection from TestCase so you can accomodate * JUnit interface changes (like the change from 2.x to 3.1) */ public abstract class TestCaseMo extends TestCase { public TestCaseMo(String name) { super(name); } public void assertVerifyFails(Verifiable aVerifiable) { AssertMo.assertVerifyFails(aVerifiable); } public void assertFails(String message, Runnable runnable) { AssertMo.assertFails(message, runnable); } public static void start(String[] testNames) { TestRunner.main(testNames); } } mockobjects-0.09/src/core/com/mockobjects/util/Verifier.java0000644000175000017500000000605707545626754025624 0ustar craftermcrafterm00000000000000package com.mockobjects.util; import com.mockobjects.Verifiable; import java.lang.reflect.Field; import java.util.Vector; import junit.framework.Assert; /** * Helper class to verify all {@link com.mockobjects.Expectation Expectation}s * of an object. * The {@link com.mockobjects.util.Verifier Verifier} class provides two static * methods to verify objects: * * These two methods can be used to verify any expectation to assert that * they still hold.

* Example usage:

* Verifying all expectations on one object at a time:

*

 * public class MockX implements Verifiable {
 *    private Expectation... anExpectation = new Expectation...(...);
 *    private Expectation... aSecondExpectation = new Expectation...(...);
 *
 *    public void verify() {
 *       Verifier.verifyObject(this);
 *    }
 * }
 * 
* This example shows how most mocks implement * {@link com.mockobjects.Verifiable Verifiable}, i.e.: by delegation. * @see com.mockobjects.Expectation * @see com.mockobjects.Verifiable * @version $Id: Verifier.java,v 1.5 2002/09/29 16:44:28 smgf Exp $ */ public class Verifier { private static Vector myProcessingObjects = new Vector(); /** * Verifies all the fields of type Verifiable in the given object, including * those inherited from superclasses. * @param anObject The object to be verified. */ static synchronized public void verifyObject(Object anObject) { verifyFieldsForClass(anObject, anObject.getClass(), myProcessingObjects); } static private void verifyFieldsForClass(Object anObject, Class aClass, Vector alreadyProcessed) { if (alreadyProcessed.contains(anObject) || isBaseObjectClass(aClass)) { return; } verifyFieldsForClass(anObject, aClass.getSuperclass(), alreadyProcessed); try { alreadyProcessed.addElement(anObject); Field[] fields = aClass.getDeclaredFields(); for (int i = 0; i < fields.length; ++i) { verifyField(fields[i], anObject, alreadyProcessed); } } finally { alreadyProcessed.removeElement(anObject); } } static private void verifyField(Field aField, Object anObject, Vector alreadyProcessed) { try { aField.setAccessible(true); Object fieldObject = aField.get(anObject); if (isVerifiable(fieldObject) && ! alreadyProcessed.contains(fieldObject)) { ((Verifiable)fieldObject).verify(); } } catch (IllegalAccessException e) { Assert.fail("Could not access field " + aField.getName()); } } private static boolean isVerifiable(Object anObject) { return anObject instanceof Verifiable; } private static boolean isBaseObjectClass(Class aClass) { return aClass.equals(Object.class); } } mockobjects-0.09/src/core/com/mockobjects/util/package.html0000644000175000017500000000016207450657026025445 0ustar craftermcrafterm00000000000000 A collection of utilities for the MockObjects framework. mockobjects-0.09/src/core/test/0000755000175000017500000000000010117310266020070 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/test/mockobjects/0000755000175000017500000000000010117310266022373 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/test/mockobjects/constraint/0000755000175000017500000000000010117310266024557 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/test/mockobjects/constraint/ConstraintsTest.java0000644000175000017500000001546107661772074030623 0ustar craftermcrafterm00000000000000/* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:24 PM */ package test.mockobjects.constraint; import com.mockobjects.constraint.*; import com.mockobjects.dynamic.Mock; import com.mockobjects.util.AssertMo; import test.mockobjects.dynamic.DummyInterface; import java.util.EventObject; import junit.framework.*; public class ConstraintsTest extends TestCase { class True implements Constraint { public boolean eval( Object o ) { return true; } } class False implements Constraint { public boolean eval( Object o ) { return false; } } /** Creates a new instance of Test_Predicates */ public ConstraintsTest( String test ) { super(test); } public void testIsNull() { Constraint p = new IsNull(); assertTrue( p.eval(null) ); assertTrue( !p.eval(new Object()) ); } public void testIsSame() { Object o1 = new Object(); Object o2 = new Object(); Constraint p = new IsSame(o1); assertTrue( p.eval(o1) ); assertTrue( !p.eval(o2) ); } public void testIsEqual() { Integer i1 = new Integer(1); Integer i2 = new Integer(2); Constraint p = new IsEqual(i1); assertTrue( p.eval(i1) ); assertTrue( p.eval( new Integer(1) ) ); assertTrue( !p.eval(i2) ); } public void testIsEqualObjectArray() { String[] s1 = new String[] { "a", "b" }; String[] s2 = new String[] { "a", "b" }; String[] s3 = new String[] { "c", "d" }; String[] s4 = new String[] { "a", "b", "c", "d" }; Constraint p = new IsEqual(s1); assertTrue( "Should equal itself", p.eval(s1) ); assertTrue( "Should equal a similar array", p.eval( s2 ) ); assertTrue( "Should not equal a different array", !p.eval(s3) ); assertTrue( "Should not equal a different sized array", !p.eval(s4) ); } public void testIsEqualToStringForNestedConstraint() { assertEquals("Should get an obvious toString to reflect nesting if viewed in a debugger", " = = NestedConstraint", new IsEqual(new IsEqual("NestedConstraint")).toString()); } public void testIsEqualToStringOnProxyArgument() { // Required for error message reporting Mock mockDummyInterface = new Mock(DummyInterface.class, "MockName"); Constraint p = new IsEqual(mockDummyInterface.proxy()); AssertMo.assertIncludes("Should get resolved toString() with no expectation error", "MockName", p.toString()); } public void testIsEqualEquals() throws Exception { assertEquals("Should be equal", new IsEqual("a"), new IsEqual("a")); assertFalse("Should not be equal - same type different values", new IsEqual("a").equals(new IsEqual("b"))); assertFalse("Should not be equal - different type", new IsEqual("a").equals("b")); } public void testIsGreaterThan() { Constraint p = new IsGreaterThan( new Integer(1) ); assertTrue( !p.eval( new Integer(0) ) ); assertTrue( !p.eval( new Integer(1) ) ); assertTrue( p.eval( new Integer(2) ) ); } public void testIsLessThan() { Constraint p = new IsLessThan( new Integer(1) ); assertTrue( p.eval( new Integer(0) ) ); assertTrue( !p.eval( new Integer(1) ) ); assertTrue( !p.eval( new Integer(2) ) ); } public void testIsAnything() { Constraint p = new IsAnything(); assertTrue( p.eval(null) ); assertTrue( p.eval( new Object() ) ); } public void testIsInstanceOf() { Constraint p = new IsInstanceOf( Number.class ); assertTrue( p.eval( new Integer(1) ) ); assertTrue( p.eval( new Double(1.0) ) ); assertTrue( !p.eval("a string") ); assertTrue( !p.eval(null) ); } public void testIsNot() { Constraint p = new IsNot( new True() ); assertTrue( !p.eval(null) ); assertTrue( !p.eval( new Object() ) ); } public void testAnd() { Object o = new Object(); assertTrue( new And( new True(), new True() ).eval(o) ); assertTrue( !new And( new False(), new True() ).eval(o) ); assertTrue( !new And( new True(), new False() ).eval(o) ); assertTrue( !new And( new False(), new False() ).eval(o) ); } public void testOr() { Object o = new Object(); assertTrue( new Or( new True(), new True() ).eval(o) ); assertTrue( new Or( new False(), new True() ).eval(o) ); assertTrue( new Or( new True(), new False() ).eval(o) ); assertTrue( !new Or( new False(), new False() ).eval(o) ); } public void testIsEventFrom() { Object o = new Object(); EventObject ev = new EventObject(o); EventObject ev2 = new EventObject( new Object() ); Constraint p = new IsEventFrom(o); assertTrue( p.eval(ev) ); assertTrue( "p should eval to false for an event not from o", !p.eval(ev2) ); assertTrue( "p should eval to false for objects that are not events", !p.eval(o) ); } private static class DerivedEvent extends EventObject { public DerivedEvent( Object source ) { super(source); } } public void testIsEventSubtypeFrom() { Object o = new Object(); DerivedEvent good_ev = new DerivedEvent(o); DerivedEvent wrong_source = new DerivedEvent(new Object()); EventObject wrong_type = new EventObject(o); EventObject wrong_source_and_type = new EventObject(new Object()); Constraint p = new IsEventFrom( DerivedEvent.class, o ); assertTrue( p.eval(good_ev) ); assertTrue( "p should eval to false for an event not from o", !p.eval(wrong_source) ); assertTrue( "p should eval to false for an event of the wrong type", !p.eval(wrong_type) ); assertTrue( "p should eval to false for an event of the wrong type "+ "and from the wrong source", !p.eval(wrong_source_and_type) ); } public void testIsCloseTo() { Constraint p = new IsCloseTo( 1.0, 0.5 ); assertTrue( p.eval( new Double(1.0) ) ); assertTrue( p.eval( new Double(0.5) ) ); assertTrue( p.eval( new Double(1.5) ) ); assertTrue( p.eval( new Float(1.0) ) ); assertTrue( p.eval( new Integer(1) ) ); assertTrue( "number too large", !p.eval( new Double(2.0) ) ); assertTrue( "number too small", !p.eval( new Double(0.0) ) ); try { p.eval("wrong type"); fail("ClassCastException expected for wrong type of argument"); } catch( ClassCastException ex ) { // expected } } } mockobjects-0.09/src/core/test/mockobjects/AllTests.java0000644000175000017500000000374707555102466025021 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.util.SuiteBuilder; import com.mockobjects.util.TestCaseMo; import junit.framework.Test; import junit.framework.TestSuite; /** * JUnit test case for AllTests */ public class AllTests extends TestCaseMo { private static final Class THIS = AllTests.class; public AllTests(String name) { super(name); } public static void addTestAssertMo(TestSuite suite) { suite.addTest(TestAssertMo.suite()); } public static void addTestExpectationCounter(TestSuite suite) { suite.addTest(TestExpectationCounter.suite()); } public static void addTestExpectationList(TestSuite suite) { suite.addTest(TestExpectationList.suite()); } public static void addTestExpectationMap(TestSuite suite) { suite.addTestSuite(TestExpectationMap.class); } public static void addTestExpectationSegment(TestSuite suite) { suite.addTest(TestExpectationSegment.suite()); } public static void addTestExpectationSet(TestSuite suite) { suite.addTest(TestExpectationSet.suite()); } public static void addTestExpectationValue(TestSuite suite) { suite.addTest(TestExpectationValue.suite()); } public static void addTestExpectationDoubleValue(TestSuite suite) { suite.addTest(TestExpectationDoubleValue.suite()); } public static void addTestMapEntry(TestSuite suite) { suite.addTest(TestMapEntry.suite()); } public static void addTestNull(TestSuite suite) { suite.addTestSuite(TestNull.class); } public static void addTestVerifier(TestSuite suite) { suite.addTest(TestVerifier.suite()); } public static void addTestReturnObjectList(TestSuite suite) { suite.addTestSuite(TestReturnObjectList.class); } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return SuiteBuilder.buildTest(THIS); } } mockobjects-0.09/src/core/test/mockobjects/AutoTestSuite.java0000644000175000017500000000730007560517670026040 0ustar craftermcrafterm00000000000000package test.mockobjects; import java.io.File; import java.lang.reflect.Modifier; import java.util.StringTokenizer; import junit.framework.*; /** A TestSuite containing all test classes found on the class path in a * hierarchy that matches the class-path and package structure of the system. */ public class AutoTestSuite extends TestSuite { /** Constructs a SystemTestSuite by finding all the test classes and * building the test hierarchy. */ public AutoTestSuite() { super("System Tests"); String class_path= System.getProperty("java.class.path"); String separator= System.getProperty("path.separator"); StringTokenizer path_elements = new StringTokenizer( class_path, separator ); while( path_elements.hasMoreTokens() ) { File root = new File( path_elements.nextToken() ); if( root.isDirectory() ) { TestSuite sub_suite = new AutoTestSuite( root.toString(), root, root ); if( sub_suite.testCount() > 0 ) addTest( sub_suite ); } } } private AutoTestSuite( String name, File root, File dir ) { super( name ); File[] contents = dir.listFiles(); for( int i = 0; i < contents.length; i++ ) { File f = contents[i]; if( f.isDirectory() ) { addNonEmptySuite(new AutoTestSuite( f.getName(), root, f )); } else if( isTestClass(f) ) { try { Class test_class = fileToClass( root, f ); if( isInstantiable(test_class) ) { addNonEmptySuite(new TestSuite(test_class)); } } catch( ClassNotFoundException ex ) { System.err.println("failed to load class " + f ); ex.printStackTrace(); // Continue adding other classes to the test suite } } } } private void addNonEmptySuite(TestSuite suite) { if( suite.testCount() > 0 ) { addTest( suite ); } } private boolean isInstantiable( Class c ) { int mods = c.getModifiers(); return !Modifier.isAbstract(mods) && !Modifier.isInterface(mods) && Modifier.isPublic(mods); } /** Is `f' a class-file containing a test case? */ protected boolean isTestClass( File f ) { String name = f.getName(); return name.endsWith("Test.class") || ( name.endsWith(".class") && name.startsWith("Test") && !isFilenameOfInnerClass(name) ); } private boolean isFilenameOfInnerClass(String name) { return name.indexOf('$') >= 0; } private Class fileToClass( File root, File f ) throws ClassNotFoundException { String class_name = pathToClassName( root.toString(), f.toString() ); return Class.forName( class_name ); } private String pathToClassName( String root, String f ) { int root_len = root.length(); if( !root.endsWith("/") ) root_len++; int tail_len = f.length() - ".class".length(); return f.substring( root_len, tail_len ).replace('/','.'); } /** Constructs and returns a SystemTestSuite. */ public static TestSuite suite() { return new AutoTestSuite(); } public static void main( String[] args ) { junit.swingui.TestRunner.main( new String[]{ AutoTestSuite.class.getName() } ); } } mockobjects-0.09/src/core/test/mockobjects/TestAssertMo.java0000644000175000017500000001224707557063615025662 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.util.AssertMo; import com.mockobjects.util.TestCaseMo; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; import java.util.Vector; public class TestAssertMo extends TestCaseMo { private static final Class THIS = TestAssertMo.class; public TestAssertMo(String name) { super(name); } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testAssertExcludes() { AssertMo.assertExcludes( "Should not include substring", "dog", "The quick brown fox"); } public void testAssertExcludesFails() { Throwable result = null; try { AssertMo.assertExcludes( "Should fail on exclude", "fox", "The quick brown fox"); } catch (AssertionFailedError ex) { result = ex; } assertTrue("Should get an exception", result != null); } public void testAssertIncludes() { AssertMo.assertIncludes( "Should include a substring", "fox", "The quick brown fox"); } public void testAssertIncludesFails() { Throwable result = null; try { AssertMo.assertIncludes( "Should fail if no include", "dog", "The quick brown fox"); } catch (AssertionFailedError ex) { result = ex; } assertTrue("Should get an exception", result != null); } public void testAssertStartsWith() { AssertMo.assertStartsWith( "Should start with fox", "fox", "fox quick brown"); } public void testAssertStartsWithFails() { Throwable result = null; try { AssertMo.assertStartsWith( "Should fail if it doesn't start with fox", "fox", "The quick brown fox"); } catch (AssertionFailedError ex) { result = ex; } assertTrue("Should get an exception", result != null); } public void testDifferentArrays() { Object[] anExpectedArray = new Object[] { "one", new Integer(2)}; Object[] anActualArray = new Object[] { "two", new Integer(2)}; boolean threwException = false; try { AssertMo.assertEquals( "Should be expected value", anExpectedArray, anActualArray); } catch (AssertionFailedError ignoredException) { threwException = true; } assertTrue("should have thrown assertion failure", threwException); } public void testDifferentLengthArrays() { Object[] anExpectedArray = new Object[] { "one", new Integer(2)}; Object[] anActualArray = new Object[] { "one" }; boolean threwException = false; try { AssertMo.assertEquals( "Should be expected value", anExpectedArray, anActualArray); } catch (AssertionFailedError ignoredException) { threwException = true; } assertTrue("should have thrown assertion failure", threwException); } public void testDifferentObjectArrays() { Object[] anExpectedArray = new Object[] { "one", new Integer(2)}; Object[] anActualArray = new Object[] { new Integer(2), new Vector()}; boolean threwException = false; try { AssertMo.assertEquals( "Should be expected value", anExpectedArray, anActualArray); } catch (AssertionFailedError ignoredException) { threwException = true; } assertTrue("should have thrown assertion failure", threwException); } public void testEqualArrays() { Object[] anExpectedArray = new Object[] { "one", new Integer(2)}; Object[] anActualArray = new Object[] { "one", new Integer(2)}; AssertMo.assertEquals( "Should be expected value", anExpectedArray, anActualArray); } public void testEqualEmptyArrays() { Object[] anExpectedArray = new Object[0]; Object[] anActualArray = new Object[0]; AssertMo.assertEquals( "Should be expected value", anExpectedArray, anActualArray); } public void testFailureCheckerWithFailure() { AssertMo.assertFails("Test Description", new Runnable() { public void run() { fail("Should not be propagated"); } }); } public void testFailureCheckerWithoutFailure() { final String TEST_MESSAGE = "Test Description"; try { AssertMo.assertFails(TEST_MESSAGE, new Runnable() { public void run() {} }); } catch (AssertionFailedError expected) { assertEquals(TEST_MESSAGE, expected.getMessage()); return; } fail("Should have thrown an exception"); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationCollection.java0000644000175000017500000001166507555102466030423 0ustar craftermcrafterm00000000000000package test.mockobjects; import java.util.*; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.util.*; public abstract class TestExpectationCollection extends TestCaseMo { ExpectationCollection myExpectation; public TestExpectationCollection(String name) { super(name); } public void testEmpty() { myExpectation.verify(); } public void testFailImmediately() { myExpectation.addExpected("A"); myExpectation.addExpected("B"); myExpectation.addActual("A"); try { myExpectation.addActual("C"); } catch (AssertionFailedError ex) { return; } fail("Should have failed immediately"); } public void testFailImmediatelyAddingTooMany() { myExpectation.addExpected("A"); myExpectation.addActual("A"); try { myExpectation.addActual("C"); } catch (AssertionFailedError ex) { return; } fail("Should have failed immediately"); } public void testFailOnSizes() { myExpectation.addExpected("A"); myExpectation.addExpected("B"); myExpectation.addActual("A"); myExpectation.addActual("B"); try { myExpectation.addActual("C"); } catch (AssertionFailedError ex) { return; } fail("Should have failed immediately"); } public void testFailOnVerify() { myExpectation.setFailOnVerify(); myExpectation.addExpectedMany(new String[] { "A", "B" }); myExpectation.addActualMany(new String[] { "C", "A" }); assertVerifyFails(myExpectation); } public void testFlushActual() { myExpectation.addActual("a value"); myExpectation.setExpectNothing(); myExpectation.verify(); } public void testHasExpectations() { assertTrue( "Should not have any expectations", !myExpectation.hasExpectations()); myExpectation.addExpected("item"); assertTrue("Should have an expectation", myExpectation.hasExpectations()); } public void testHasExpectationsForAddingManyArray() { assertTrue( "Should not have any expectations", !myExpectation.hasExpectations()); myExpectation.addExpectedMany(new Object[0]); assertTrue("Should have an expectation", myExpectation.hasExpectations()); } public void testHasExpectationsForAddingManyVector() { assertTrue( "Should not have any expectations", !myExpectation.hasExpectations()); myExpectation.addExpectedMany(new Vector().elements()); assertTrue("Should have an expectation", myExpectation.hasExpectations()); } public void testHasNoExpectations() { myExpectation.addActual("a value"); assertTrue("Has no expectations", !myExpectation.hasExpectations()); } public void testManyFromEnumeration() { Vector expectedItems = new Vector(); expectedItems.addElement("A"); expectedItems.addElement("B"); Vector actualItems = (Vector) expectedItems.clone(); myExpectation.addExpectedMany(expectedItems.elements()); myExpectation.addActualMany(actualItems.elements()); myExpectation.verify(); } public void testManyFromIterator() { Vector expectedItems = new Vector(); expectedItems.addElement("A"); expectedItems.addElement("B"); Vector actualItems = (Vector) expectedItems.clone(); myExpectation.addExpectedMany(expectedItems.iterator()); myExpectation.addActualMany(actualItems.iterator()); myExpectation.verify(); } public void testMultiFailureFromEnumeration() { Vector expectedItems = new Vector(); expectedItems.addElement("A"); expectedItems.addElement("B"); Vector actualItems = new Vector(); actualItems.addElement("A"); actualItems.addElement("C"); myExpectation.addExpectedMany(expectedItems.elements()); myExpectation.setFailOnVerify(); myExpectation.addActualMany(actualItems.elements()); assertVerifyFails(myExpectation); } public void testMultiFailureFromIterator() { Vector expectedItems = new Vector(); expectedItems.addElement("A"); expectedItems.addElement("B"); Vector actualItems = new Vector(); actualItems.addElement("A"); actualItems.addElement("C"); myExpectation.addExpectedMany(expectedItems.iterator()); myExpectation.setFailOnVerify(); myExpectation.addActualMany(actualItems.iterator()); assertVerifyFails(myExpectation); } public void testMultiFailureSizes() { myExpectation.addExpectedMany(new String[] { "A", "B" }); myExpectation.setFailOnVerify(); myExpectation.addActualMany(new String[] { "A", "B", "C" }); assertVerifyFails(myExpectation); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationCounter.java0000644000175000017500000000465307555102466027746 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.util.*; /** * JUnit test case for TestExpectationCounter */ public class TestExpectationCounter extends TestCaseMo { private static final Class THIS = TestExpectationCounter.class; public TestExpectationCounter(String name) { super(name); } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testExpectNothing() { ExpectationCounter e = new ExpectationCounter(""); e.setExpectNothing(); assertTrue("Has expectation", e.hasExpectations()); e.verify(); } public void testExpectNothingFailure() { ExpectationCounter e = new ExpectationCounter(""); e.setExpectNothing(); assertTrue("Has expectation", e.hasExpectations()); try { e.inc(); } catch (AssertionFailedError ex) { return; } fail("Should have failed immediately"); } public void testFailImmediately() { ExpectationCounter aCounter = new ExpectationCounter("a test counter"); aCounter.setExpected(1); aCounter.inc(); try { aCounter.inc(); } catch (AssertionFailedError ex) { return; } fail("Should have failed immediately"); } public void testFailOnVerify() { ExpectationCounter aCounter = new ExpectationCounter("a test counter"); aCounter.setExpected(1); aCounter.setFailOnVerify(); aCounter.inc(); aCounter.inc(); assertVerifyFails(aCounter); } public void testFailure() { ExpectationCounter e = new ExpectationCounter(""); e.setExpected(1); assertVerifyFails(e); } public void testFlushActual() { ExpectationCounter e = new ExpectationCounter(""); e.inc(); e.setExpected(1); e.inc(); e.verify(); } public void testHasNoExpectations() { ExpectationCounter aCounter = new ExpectationCounter("a test counter"); aCounter.inc(); assertTrue("Has no expectations", !aCounter.hasExpectations()); } public void testSuccess() { ExpectationCounter e = new ExpectationCounter(""); e.setExpected(1); e.inc(); e.verify(); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationDoubleValue.java0000644000175000017500000000435407555102466030534 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.util.*; public class TestExpectationDoubleValue extends TestCaseMo { private static final Class THIS = TestExpectationDoubleValue.class; private ExpectationDoubleValue myExpectation = new ExpectationDoubleValue("ExpectationDoubleValue for testing"); public TestExpectationDoubleValue(String name) { super(name); } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testExpectNothing() { myExpectation.setExpectNothing(); assertTrue("Should have an expectation", myExpectation.hasExpectations()); } public void testExpectNothingFail() { myExpectation.setExpectNothing(); try { myExpectation.setActual(100.0); fail("Should fail fast"); } catch (AssertionFailedError ex) { // expected } } public void testFailOnVerify() { myExpectation.setExpected( 0.0, 0.0 ); myExpectation.setFailOnVerify(); myExpectation.setActual(1.0); assertVerifyFails(myExpectation); } public void testFlushActual() { myExpectation.setActual(10); myExpectation.setExpectNothing(); myExpectation.verify(); } public void testHasNoExpectations() { myExpectation.setActual(0.0); assertTrue( "Has no expectations", !myExpectation.hasExpectations()); } public void testFailOutsideError() { myExpectation.setExpected( 100.0, 1.0 ); try { myExpectation.setActual(102.0); fail("Should fail fast on double"); } catch (AssertionFailedError ex) { //expected } } public void testPassOnError() { myExpectation.setExpected( 100.0, 1.0 ); myExpectation.setActual(101.0); myExpectation.verify(); } public void testPassWithinError() { myExpectation.setExpected( 100.0, 1.0 ); myExpectation.setActual(100); myExpectation.verify(); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationList.java0000644000175000017500000000152307570131754027232 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.Test; import junit.framework.TestSuite; import com.mockobjects.ExpectationList; public class TestExpectationList extends TestExpectationCollection { private static final Class THIS = TestExpectationList.class; public TestExpectationList(String name) { super(name); myExpectation = new ExpectationList(name); } public void lookAtTheSuperclassForTests() { } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testSorted() { myExpectation.addExpected("A"); myExpectation.addExpected("B"); myExpectation.addActual("A"); myExpectation.addActual("B"); myExpectation.verify(); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationMap.java0000644000175000017500000000510107570131754027030 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.awtui.TestRunner; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.util.*; /** * JUnit test case for TestExpectationMap */ public class TestExpectationMap extends TestCaseMo { private static final Class THIS = TestExpectationMap.class; public TestExpectationMap(String name) { super(name); } public static void main(String[] args) { TestRunner.run(THIS); } public void testExpectMissingEntry() { ExpectationMap map = new ExpectationMap("map"); map.addExpectedMissing("key"); assertEquals("one entry", null, map.get("key")); map.verify(); } public void testExpectNullEntry() { ExpectationMap map = new ExpectationMap("map"); try { map.addExpected("key", null); assertEquals("one entry", null, map.get("key")); map.verify(); } catch (NullPointerException ex) { AssertMo.assertStartsWith( "Should be JDK 1.1.7A", "1.1", System.getProperty("java.version")); } } public void testExpectOneEntry() { ExpectationMap map = new ExpectationMap("map"); map.addExpected("key", "value"); assertEquals("one entry", "value", map.get("key")); map.verify(); } public void testExpectTwoEntries() { ExpectationMap map = new ExpectationMap("map"); map.addExpected("key", "value"); map.addExpected("key1", "value1"); assertEquals("two entries", "value", map.get("key")); assertEquals("two entries", "value1", map.get("key1")); map.verify(); } public void testFailOneEntry() { try { ExpectationMap map = new ExpectationMap("map"); map.setExpectNothing(); map.get("key"); } catch (AssertionFailedError ex) { return; } fail("should fail one entry"); } public void testFailOnVerify() { ExpectationMap map = new ExpectationMap("map"); map.setExpectNothing(); map.setFailOnVerify(); map.get("key"); try { map.verify(); } catch (AssertionFailedError ex) { return; } fail("should fail one entry"); } public void testOverwriteEntry() { ExpectationMap map = new ExpectationMap("map"); map.addExpected("key", "value"); map.addExpected("key", "value1"); assertEquals("overwrite entry", "value1", map.get("key")); map.verify(); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationSegment.java0000644000175000017500000000456707570131754027734 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; import com.mockobjects.ExpectationSegment; import com.mockobjects.util.TestCaseMo; public class TestExpectationSegment extends TestCaseMo { private static final Class THIS = TestExpectationSegment.class; private ExpectationSegment myExpectation; public TestExpectationSegment(String name) { super(name); } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public void setUp() { myExpectation = new ExpectationSegment("Expectation segment"); } public static Test suite() { return new TestSuite(THIS); } public void testExpectNothing() { myExpectation.setExpectNothing(); assertTrue("Should have an expectation", myExpectation.hasExpectations()); } public void testExpectNothingFail() { myExpectation.setExpectNothing(); boolean hasThrownException = false; try { myExpectation.setActual("some string"); } catch (AssertionFailedError ex) { hasThrownException = true; } assertTrue("Should fail fast", hasThrownException); } public void testFailOnVerify() { myExpectation.setExpected("a segment"); myExpectation.setFailOnVerify(); myExpectation.setActual("string without stuff"); assertVerifyFails(myExpectation); } public void testFailsImmediately() { boolean hasThrownException = false; myExpectation.setExpected("inner"); try { myExpectation.setActual("String not containing segment"); } catch (AssertionFailedError expected) { hasThrownException = true; } assertTrue("Should have thrown exception", hasThrownException); } public void testFlushActual() { myExpectation.setActual("a string"); myExpectation.setExpectNothing(); myExpectation.verify(); } public void testHasNoExpectations() { myExpectation.setActual("a string"); assertTrue("Has no expectations", !myExpectation.hasExpectations()); } public void testPasses() { myExpectation.setExpected("inner"); myExpectation.setActual("String containing inner segment"); myExpectation.verify(); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationSet.java0000644000175000017500000000430507660455516027060 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.ExpectationSet; import com.mockobjects.MapEntry; import junit.framework.Test; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Vector; public class TestExpectationSet extends TestExpectationCollection { private static final Class THIS = TestExpectationSet.class; public TestExpectationSet(String name) { super(name); myExpectation = new ExpectationSet(name); } public void lookAtTheSuperclassForTests() { } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testMultiUnsorted() { myExpectation.addExpectedMany(new String[] { "A", "B" }); myExpectation.addActualMany(new String[] { "A", "B" }); myExpectation.verify(); } public void testChangingHashcode() { final Vector value = new Vector(); myExpectation.addExpected(new MapEntry("key", value)); myExpectation.addActual(new MapEntry("key", value)); value.add(getName()); myExpectation.verify(); } public void testChanginHashcodeImediateCheck() { final Vector value = new Vector(); myExpectation.addExpected(new MapEntry("key", value)); value.add(getName()); myExpectation.addActual(new MapEntry("key", value)); myExpectation.verify(); } public void testMultiUnsortedSet() { myExpectation.addExpectedMany(new String[] { "A", "B" }); myExpectation.addActualMany(new String[] { "A", "B", "A", "B" }); myExpectation.verify(); } public void testUnsorted() { myExpectation.addExpected("A"); myExpectation.addExpected("B"); myExpectation.addActual("B"); myExpectation.addActual("A"); myExpectation.verify(); } public void testUnsortedSet() { myExpectation.addExpected("A"); myExpectation.addExpected("B"); myExpectation.addActual("A"); myExpectation.addActual("B"); myExpectation.addActual("A"); myExpectation.addActual("B"); myExpectation.verify(); } } mockobjects-0.09/src/core/test/mockobjects/TestExpectationValue.java0000644000175000017500000001103507555102466027373 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.util.*; /** * JUnit test case for TestExpectationValue */ public class TestExpectationValue extends TestCaseMo { private static final Class THIS = TestExpectationValue.class; private ExpectationValue myExpectation = new ExpectationValue("ExpectationValue for testing"); public TestExpectationValue(String name) { super(name); } public static void main(String[] args) { start(new String[] { THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testBooleanFail() { myExpectation.setExpected(true); boolean testPasses = false; try { myExpectation.setActual(false); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on boolean", testPasses); } public void testBooleanPass() { myExpectation.setExpected(true); myExpectation.setActual(true); myExpectation.verify(); } public void testExpectNothing() { myExpectation.setExpectNothing(); assertTrue("Should have an expectation", myExpectation.hasExpectations()); } public void testExpectNothingFail() { myExpectation.setExpectNothing(); boolean testPasses = false; try { myExpectation.setActual("another object"); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on object", testPasses); } public void testFailOnVerify() { myExpectation.setExpected("string object"); myExpectation.setFailOnVerify(); myExpectation.setActual("another object"); assertVerifyFails(myExpectation); } public void testFlushActual() { myExpectation.setActual(10); myExpectation.setExpectNothing(); myExpectation.verify(); } public void testHasNoExpectations() { myExpectation.setActual("a value"); assertTrue("Has no expectations", !myExpectation.hasExpectations()); } public void testIntFail() { myExpectation.setExpected(100); boolean testPasses = false; try { myExpectation.setActual(150); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on int", testPasses); } public void testIntPass() { myExpectation.setExpected(100); myExpectation.setActual(100); myExpectation.verify(); } public void testLongFail() { myExpectation.setExpected(100L); boolean testPasses = false; try { myExpectation.setActual(150L); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on long", testPasses); } public void testLongPass() { myExpectation.setExpected(100L); myExpectation.setActual(100L); myExpectation.verify(); } public void testDoubleFail() { myExpectation.setExpected(100.0); boolean testPasses = false; try { myExpectation.setActual(150.0); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on double", testPasses); } public void testDoublePass() { myExpectation.setExpected(100.0); myExpectation.setActual(100.0); myExpectation.verify(); } public void testNullFail() { myExpectation.setExpected(null); boolean testPasses = false; try { myExpectation.setActual("another object"); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on object", testPasses); } public void testNullPass() { myExpectation.setExpected(null); myExpectation.setActual(null); myExpectation.verify(); } public void testObject() { myExpectation.setExpected("string object"); myExpectation.setActual("string object"); myExpectation.verify(); } public void testObjectFail() { myExpectation.setExpected("string object"); boolean testPasses = false; try { myExpectation.setActual("another object"); } catch (AssertionFailedError ex) { testPasses = true; } assertTrue("Should fail fast on object", testPasses); } } mockobjects-0.09/src/core/test/mockobjects/TestMapEntry.java0000644000175000017500000000405107555102466025652 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.MapEntry; import com.mockobjects.util.TestCaseMo; import junit.framework.Test; import junit.framework.TestSuite; /** * JUnit test case for TestMapEntry */ public class TestMapEntry extends TestCaseMo { public TestMapEntry(String name) { super(name); } public static void main(String[] args) { start(new String[]{TestMapEntry.class.getName()}); } public static Test suite() { return new TestSuite(TestMapEntry.class); } public void testEquals() { assertEquals( "Should be expected value", new MapEntry("A", "2"), new MapEntry("A", "2")); assertTrue( "Should not be equal", !new MapEntry("A", "2").equals(new MapEntry("A", "1"))); assertTrue( "Should not be equal", !new MapEntry("A", "2").equals(new MapEntry("B", "2"))); assertEquals( "Should be equal with null value", new MapEntry("A", null), new MapEntry("A", null)); assertEquals( "Should be equal with null key", new MapEntry(null, "A"), new MapEntry(null, "A")); assertEquals( "Should be equal byte arrays", new MapEntry("A", "A".getBytes()), new MapEntry("A", "A".getBytes())); assertTrue( "Should not be equal byte arrays", !new MapEntry("A", "AB".getBytes()).equals(new MapEntry("A", "A".getBytes()))); assertTrue( "Should not be equal byte arrays", !new MapEntry("A", "A".getBytes()).equals(new MapEntry("A", "AB".getBytes()))); assertTrue( "Should not be equal byte arrays", !new MapEntry("A", null).equals(new MapEntry("A", "AB".getBytes()))); } public void testHashCode() { assertEquals( "Should be equal hashcodes", new MapEntry("A", "A".getBytes()).hashCode(), new MapEntry("A", "A".getBytes()).hashCode()); } } mockobjects-0.09/src/core/test/mockobjects/TestNull.java0000644000175000017500000000241307570131754025024 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.Test; import junit.framework.TestSuite; import com.mockobjects.util.Null; import com.mockobjects.util.TestCaseMo; /** * JUnit test case for TestMapEntry */ public class TestNull extends TestCaseMo { public TestNull(String name) { super(name); } public static void main(String[] args) { start(new String[] { TestNull.class.getName()}); } public static Test suite() { return new TestSuite(TestNull.class); } public void testEquals() { assertEquals("Should be same value", new Null(), new Null()); assertEquals("Should be same hashCode", new Null().hashCode(), new Null().hashCode()); assertEquals("Should be same value", new Null("one"), new Null("two")); assertEquals("Should be same hashCode", new Null("one").hashCode(), new Null("two").hashCode()); // Compare with other objects to assert that they are not equal assertEquals("Not equal to something else", false, new Null("one").equals("one")); assertEquals("Not equal to something else", false, new Null().equals(new Integer(2))); } public void testDescription() { assertEquals("Description", "what it is", new Null("what it is").toString()); } } mockobjects-0.09/src/core/test/mockobjects/TestReturnObjectBag.java0000644000175000017500000000546007651477217027146 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.util.TestCaseMo; import com.mockobjects.ReturnObjectBag; import junit.framework.AssertionFailedError; public class TestReturnObjectBag extends TestCaseMo { private final ReturnObjectBag bag = new ReturnObjectBag(getName()); private static final String KEY1 = "key1"; private static final String KEY2 = "key2"; private static final short SHORT_KEY1 = 1; private static final short SHORT_KEY2 = 2; private static final String VALUE_ONE = "one"; private static final String VALUE_TWO = "two"; public TestReturnObjectBag(String name) { super(name); } public static void main(String[] args) { start(new String[] { TestReturnObjectBag.class.getName()}); } public void testLeftoverObjectFails() { bag.putObjectToReturn(KEY1, VALUE_ONE); assertVerifyFails(bag); } public void testEmptyList() { bag.verify(); } public void testReturnSucceeds() { bag.putObjectToReturn(KEY1, VALUE_ONE); bag.putObjectToReturn(KEY2, VALUE_TWO); assertEquals("Should be first result", VALUE_ONE, bag.getNextReturnObject(KEY1)); assertEquals("Should be second result", VALUE_TWO, bag.getNextReturnObject(KEY2)); bag.verify(); } public void testReturnInt() { bag.putObjectToReturn(KEY1, 1); assertEquals("Should be 1", 1, bag.getNextReturnInt(KEY1)); bag.verify(); } public void testReturnBoolean() { bag.putObjectToReturn(KEY1, true); assertEquals("Should be true", true, bag.getNextReturnBoolean(KEY1)); bag.verify(); } public void testShortKey(){ bag.putObjectToReturn(SHORT_KEY1, VALUE_ONE); bag.putObjectToReturn(SHORT_KEY2, VALUE_TWO); assertEquals("Should be first result", VALUE_ONE, bag.getNextReturnObject(SHORT_KEY1)); assertEquals("Should be second result", VALUE_TWO, bag.getNextReturnObject(SHORT_KEY2)); bag.verify(); } public void testNoListForKey(){ try { bag.getNextReturnObject(KEY1); fail("AssertionFiledError not thrown"); } catch (AssertionFailedError e) { assertEquals(getName() + " does not contain key1", e.getMessage()); } } public void testNullKey(){ bag.putObjectToReturn(null, VALUE_ONE); assertEquals(VALUE_ONE, bag.getNextReturnObject(null)); } public void testTooManyReturns() { bag.putObjectToReturn(KEY1, VALUE_ONE); bag.getNextReturnObject(KEY1); try { bag.getNextReturnObject(KEY1); fail("AssertionFiledError not thrown"); } catch (AssertionFailedError e) { assertEquals(getName() + ".key1 has run out of objects.", e.getMessage()); } } } mockobjects-0.09/src/core/test/mockobjects/TestReturnObjectList.java0000644000175000017500000000227407570131754027361 0ustar craftermcrafterm00000000000000package test.mockobjects; import junit.framework.AssertionFailedError; import com.mockobjects.ReturnObjectList; import com.mockobjects.util.TestCaseMo; public class TestReturnObjectList extends TestCaseMo { private ReturnObjectList list = new ReturnObjectList("test"); public TestReturnObjectList(String name) { super(name); } public static void main(String[] args) { start(new String[] { TestReturnObjectList.class.getName()}); } public void testLeftoverObjectFails() { list.addObjectToReturn("one"); assertVerifyFails(list); } public void testEmptyList() { list.verify(); } public void testReturnSucceeds() { list.addObjectToReturn("one"); list.addObjectToReturn("two"); assertEquals("Should be first result", "one", list.nextReturnObject()); assertEquals("Should be second result", "two", list.nextReturnObject()); list.verify(); } public void testTooManyReturns() { try{ list.nextReturnObject(); fail("Error should have been raised"); } catch(AssertionFailedError expected){ } } } mockobjects-0.09/src/core/test/mockobjects/TestReturnValue.java0000644000175000017500000000256007635626402026372 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.util.TestCaseMo; import com.mockobjects.ReturnValue; import junit.framework.AssertionFailedError; public class TestReturnValue extends TestCaseMo { private final ReturnValue value = new ReturnValue(getName()); public void testGetNull(){ value.setValue(null); assertTrue(value.getValue()==null); } public void testGetValue(){ value.setValue(this); assertEquals(this, value.getValue()); } public void testGetBooleanValue(){ value.setValue(true); assertTrue(value.getBooleanValue()); } public void testIntValue(){ value.setValue(13); assertEquals(13, value.getIntValue()); } public void testLongValue(){ long now = System.currentTimeMillis(); value.setValue(now); assertEquals(now, value.getLongValue()); value.getIntValue(); } public void testValueNotSet() { try { value.getValue(); fail("Error not thrown"); } catch (AssertionFailedError e) { assertEquals("The return value \"" + getName() + "\" has not been set.", e.getMessage()); } } public TestReturnValue(String name) { super(name); } public static void main(String[] args) { start(new String[] { TestReturnValue.class.getName()}); } } mockobjects-0.09/src/core/test/mockobjects/TestVerifier.java0000644000175000017500000000623207555102466025671 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; import com.mockobjects.util.TestCaseMo; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; public class TestVerifier extends TestCaseMo { private static final Class THIS = TestVerifier.class; class OneVerifiable extends MockObject { private ExpectationValue myValue = new ExpectationValue("should fail"); private int unusedField; public OneVerifiable() { myValue.setFailOnVerify(); myValue.setExpected("good"); } public void setValue(String aValue) { myValue.setActual(aValue); } } class InheritVerifiable extends OneVerifiable { } class LoopingVerifiable extends MockObject { LoopingVerifiable myRef = this; boolean inVerify = false; LoopingVerifiable() { super(); } public void setRef(LoopingVerifiable aRef) { myRef = aRef; } public void verify() { assertTrue("Looping verification detected", !inVerify); inVerify = true; super.verify(); inVerify = false; } } public TestVerifier(String name) { super(name); } public static void main(String[] args) { start(new String[]{THIS.getName()}); } public static Test suite() { return new TestSuite(THIS); } public void testInheritVerifiableFails() { InheritVerifiable inheritVerifiable = new InheritVerifiable(); inheritVerifiable.setValue("bad"); boolean hasThrownException = false; try { inheritVerifiable.verify(); } catch (AssertionFailedError ex) { hasThrownException = true; } assertTrue("Should have thrown exception", hasThrownException); } public void testInheritVerifiablePasses() { InheritVerifiable inheritVerifiable = new InheritVerifiable(); inheritVerifiable.setValue("good"); inheritVerifiable.verify(); } public void testNoVerifiables() { class NoVerifiables extends MockObject { } new NoVerifiables().verify(); } public void testOneVerifiableFails() { OneVerifiable oneVerifiable = new OneVerifiable(); oneVerifiable.setValue("bad"); boolean hasThrownException = false; try { oneVerifiable.verify(); } catch (AssertionFailedError ex) { hasThrownException = true; } assertTrue("Should have thrown exception", hasThrownException); } public void testOneVerifiablePasses() { OneVerifiable oneVerifiable = new OneVerifiable(); oneVerifiable.setValue("good"); oneVerifiable.verify(); } public void testNoLoopVerifySingleLevel() { new LoopingVerifiable().verify(); } public void testNoLoopVerifyMultiLevel() { LoopingVerifiable a = new LoopingVerifiable(); LoopingVerifiable b = new LoopingVerifiable(); a.setRef(b); b.setRef(a); a.verify(); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/0000755000175000017500000000000010117310266024017 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/core/test/mockobjects/dynamic/CTest.java0000644000175000017500000000056407661772071025731 0ustar craftermcrafterm00000000000000/* * Created on 30-Apr-03 */ package test.mockobjects.dynamic; import com.mockobjects.dynamic.C; import junit.framework.TestCase; public class CTest extends TestCase { public CTest(String name) { super(name); } public void testEqObjectArray() { assertTrue("Should be equals for object arrays", C.eq(new String[]{"a", "b"}).eval(new String[]{"a","b"})); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/CallBagTest.java0000644000175000017500000001327707662270504027034 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import com.mockobjects.dynamic.*; import com.mockobjects.util.*; import junit.framework.*; public class CallBagTest extends TestCase { final String METHOD_A_NAME = "methodA"; final String METHOD_A_RESULT = "resultA"; final String METHOD_B_NAME = "methodB"; final String METHOD_B_RESULT = "resultB"; final Throwable METHOD_A_EXCEPTION = new DummyThrowable("Configured test throwable"); final String[] METHOD_A_ARGS = new String[] { "a1", "a2" }; final ConstraintMatcher METHOD_A_CONSTRAINTS = C.args(C.eq("a1"), C.eq("a2")); final String[] METHOD_B_ARGS = new String[] { "b1", "b2" }; private CallBag callSet = new CallBag(); private Mock unusedMock = null; private MockCallable methodA = new MockCallable(); private MockCallable methodB = new MockCallable(); private MockCallable mockCallable = new MockCallable(); public CallBagTest(String name) { super(name); } public void testCallFailsOnEmptySet() throws Throwable { try { callSet.call(unusedMock, "missingMethod", new Object[0]); } catch (AssertionFailedError ex) { AssertMo.assertIncludes("reports empty set in error message", "no methods", ex.getMessage()); return; } fail("Should fail for a missing item"); } public void testCallPassedToContainedElements() throws Throwable { methodA.setExpectedMatches(METHOD_A_NAME, METHOD_A_ARGS); methodA.setupMatchesReturn(true); methodA.setExpectedCall(unusedMock, METHOD_A_NAME, METHOD_A_ARGS); methodA.setupCallReturn(METHOD_A_RESULT); methodB.setExpectedCallCount(0); callSet.addExpect(methodA); callSet.addExpect(methodB); assertSame("expected result from method A", METHOD_A_RESULT, callSet.call(unusedMock, METHOD_A_NAME, METHOD_A_ARGS)); methodA.verifyExpectations(); methodB.verifyExpectations(); } public void testExpectOverridesMatch() throws Throwable { Callable methodASignature = new CallSignature(METHOD_A_NAME,METHOD_A_CONSTRAINTS, new ReturnStub("result1")); Callable anotherMethodASignature = new CallSignature(METHOD_A_NAME,METHOD_A_CONSTRAINTS, new ReturnStub("result2")); callSet.addMatch(methodASignature); callSet.addExpect(new CallOnceExpectation(anotherMethodASignature)); assertSame("expected result from method B, as expect has precendence over match", "result2", callSet.call(unusedMock, METHOD_A_NAME, METHOD_A_ARGS)); } public void testCallPassedToContainedElementsOtherOrder() throws Throwable { methodA.setExpectedMatches(METHOD_B_NAME, METHOD_B_ARGS); methodA.setupMatchesReturn(false); methodA.setExpectedCallCount(0); methodB.setExpectedCall(unusedMock, METHOD_B_NAME, METHOD_B_ARGS); methodB.setupCallReturn(METHOD_B_RESULT); methodB.setExpectedMatches(METHOD_B_NAME, METHOD_B_ARGS); methodB.setupMatchesReturn(true); callSet.addExpect(methodA); callSet.addExpect(methodB); assertSame("expected result from method B", METHOD_B_RESULT, callSet.call(unusedMock, METHOD_B_NAME, METHOD_B_ARGS)); methodA.verifyExpectations(); methodB.verifyExpectations(); } public void testConfiguredResultReturned() throws Throwable { final String result = "result"; mockCallable.setupCallReturn(result); mockCallable.setupMatchesReturn(true); callSet.addExpect(mockCallable); assertSame("result is returned by mock", result, callSet.call(unusedMock, "method", new Object[0])); } public void testCallableThrowableThrown() throws Throwable { final Throwable throwable = new DummyThrowable(); mockCallable.setupMatchesReturn(true); mockCallable.setupCallThrow(throwable); callSet.addExpect(mockCallable); try { callSet.call(unusedMock, "hello", new String[0]); } catch (Throwable ex) { assertSame("exception is caught by mock", throwable, ex); } } public void testEmptySetVerifies() throws Exception { callSet.verify(); } public void testFailureIfNoElementMatches() throws Throwable { final String methodCName = "methodC"; final String[] methodCArgs = { "c1", "c2" }; methodA.setExpectedMatches(methodCName, methodCArgs); methodA.setupMatchesReturn(false); methodA.setExpectedCallCount(0); methodA.setupGetDescription("***methodA-description****"); methodB.setExpectedCall(unusedMock, methodCName, methodCArgs); methodB.setupMatchesReturn(false); methodB.setExpectedCallCount(0); methodB.setupGetDescription("***methodB-description****"); callSet.addExpect(methodA); callSet.addExpect(methodB); try { callSet.call(unusedMock, methodCName, methodCArgs); } catch (AssertionFailedError ex) { AssertMo.assertIncludes("method name is in error message", "methodC", ex.getMessage()); AssertMo.assertIncludes("argument is in error message (1)", methodCArgs[0], ex.getMessage()); AssertMo.assertIncludes("argument is in error message (2)", methodCArgs[1], ex.getMessage()); AssertMo.assertIncludes("shows set contents (A)", methodA.getDescription(), ex.getMessage()); AssertMo.assertIncludes("shows set contents (B)", methodB.getDescription(), ex.getMessage()); return; } fail("Should fail for a missing item"); } public void testVerifiesIfAllContainedElementsVerify() throws Throwable { methodA.setExpectedVerifyCalls(1); methodB.setExpectedVerifyCalls(1); callSet.addExpect(methodA); callSet.addExpect(methodB); callSet.verify(); methodA.verifyExpectations(); methodB.verifyExpectations(); } public void testVerifyFailsIfContainedElementDoesNotVerify() throws Exception { methodA.setExpectedVerifyCalls(1); methodA.setupVerifyThrow(new AssertionFailedError("verify failed")); callSet.addExpect(methodA); try { callSet.verify(); } catch (AssertionFailedError ex) { methodA.verifyExpectations(); return; } fail("Should have got a failure for contained element failing"); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/CallMatchTest.java0000644000175000017500000000637307662265315027402 0ustar craftermcrafterm00000000000000/* * Created on 04-Apr-2003 */ package test.mockobjects.dynamic; import junit.framework.TestCase; import com.mockobjects.dynamic.*; public class CallMatchTest extends TestCase { private static final Object[] IGNORED_ARGS = new Object[0]; final String METHOD_NAME = "methodName"; Mock mock = new Mock(DummyInterface.class, "mock"); MockCallable mockCallable = new MockCallable(); MockConstraintMatcher mockConstraintMatcher = new MockConstraintMatcher(); CallSignature callSignature = new CallSignature(METHOD_NAME, mockConstraintMatcher, mockCallable); public CallMatchTest(String name) { super(name); } public void testCallArgumentsArePropagatedToDecorated() throws Throwable { final Object[] arguments = IGNORED_ARGS; final String result = "result"; mockCallable.setExpectedCall(mock, METHOD_NAME, arguments); mockCallable.setupCallReturn(result); callSignature.call(mock, METHOD_NAME, arguments); mockCallable.verifyExpectations(); } public void testUncalledCallVerifies() { mockCallable.setExpectedVerifyCalls(1); callSignature.verify(); mockCallable.verifyExpectations(); } public void testCallSuccessVerifies() throws Throwable { mockCallable.setExpectedVerifyCalls(1); mockCallable.setupCallReturn("result"); callSignature.call(mock, "methodName", IGNORED_ARGS); callSignature.verify(); mockCallable.verifyExpectations(); } public void testMultipleCallsSucceed() throws Throwable { mockCallable.setupCallReturn("result"); callSignature.call(mock, METHOD_NAME, IGNORED_ARGS); callSignature.call(mock, METHOD_NAME, IGNORED_ARGS); mockCallable.verifyExpectations(); } public void testCallFailure() throws Throwable { // na } public void testCallDoesNotMatchWhenWrongName() throws Throwable { assertFalse("call does not match", callSignature.matches("anotherName", IGNORED_ARGS)); mockCallable.verifyExpectations(); } public void testMatchesAfterCalls() throws Throwable { mockCallable.setupCallReturn("result"); mockCallable.setupMatchesReturn(true); mockConstraintMatcher.setupMatches(true); callSignature.call(mock, METHOD_NAME, IGNORED_ARGS); assertTrue("matches after first call", callSignature.matches(METHOD_NAME, IGNORED_ARGS)); callSignature.call(mock, METHOD_NAME, IGNORED_ARGS); assertTrue("matches after further calls", callSignature.matches(METHOD_NAME, IGNORED_ARGS)); mockCallable.verifyExpectations(); } public void testMatchesDelegatesToContraintMatcher() throws Throwable { final String[] args = new String[] { "a1", "a2" }; mockConstraintMatcher.addExpectedMatches(args); mockConstraintMatcher.setupMatches(true); assertTrue("matches delegated to constraint matcher", callSignature.matches(METHOD_NAME, args)); mockConstraintMatcher.verify(); } public void testMatchesFailure() throws Throwable { mockConstraintMatcher.setupMatches(false); assertFalse("Should not match if constraint matcher doesn't", callSignature.matches(METHOD_NAME, IGNORED_ARGS)); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/CallOnceExpectationTest.java0000644000175000017500000000611307662270504031422 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import com.mockobjects.dynamic.*; import com.mockobjects.util.*; import junit.framework.*; public class CallOnceExpectationTest extends TestCase { final String RESULT = "result!"; final String METHOD_NAME = "methodName"; final Object[] ARGS = { "arg1", "arg2" }; final String DECORATED_DESCRIPTION = DynamicUtil.methodToString( METHOD_NAME, ARGS ); Mock ignoredMock = null; MockCallable mockCallable = new MockCallable(); CallOnceExpectation call = new CallOnceExpectation( mockCallable ); public CallOnceExpectationTest(String name) { super(name); } public void setUp() { mockCallable.setupGetDescription(DECORATED_DESCRIPTION); } public void testDescription() { AssertMo.assertIncludes( "should contain decorated's description", DECORATED_DESCRIPTION, call.getDescription() ); AssertMo.assertIncludes( "should say that decorated call has called status", "called", call.getDescription() ); } public void testDoesNotVerifyIfNotCalled() { try { call.verify(); } catch( AssertionFailedError ex ) { AssertMo.assertIncludes( "should include description of expected call", DECORATED_DESCRIPTION, ex.getMessage() ); return; } fail( "verify did not fail when expected call not called"); } public void testVerifiesIfCalled() throws Throwable { mockCallable.setupCallReturn( RESULT ); mockCallable.setExpectedVerifyCalls(1); call.call( ignoredMock, METHOD_NAME, ARGS ); call.verify(); mockCallable.verifyExpectations(); } public void testMatchesDelegated() throws Throwable { mockCallable.setExpectedMatches( METHOD_NAME, ARGS ); mockCallable.setupMatchesReturn(true); assertTrue( "returns matches to be true", call.matches( METHOD_NAME, ARGS ) ); mockCallable.verifyExpectations(); } public void testCallArgumentsPassedThrough() throws Throwable { mockCallable.setExpectedCall(ignoredMock, METHOD_NAME, ARGS); mockCallable.setupCallReturn(RESULT); call.call( ignoredMock, METHOD_NAME, ARGS ); mockCallable.verifyExpectations(); } public void testDoesNotMatchAfterMethodCalled() throws Throwable { mockCallable.setupMatchesReturn(true); mockCallable.setupCallReturn(RESULT); assertTrue( "First time should match", call.matches(METHOD_NAME, ARGS)); call.call(ignoredMock, METHOD_NAME, ARGS); assertFalse( "Second time should not match", call.matches(METHOD_NAME, ARGS)); } public void testDecoratedResultPassedThrough() throws Throwable { mockCallable.setupCallReturn(RESULT); assertSame( "should return decorated's result", RESULT, call.call( ignoredMock, METHOD_NAME, ARGS ) ); mockCallable.verifyExpectations(); } public void testDecoratedExceptionPassedThrough() throws Throwable { final Throwable exception = new DummyThrowable(); mockCallable.setupCallThrow(exception); try { call.call( ignoredMock, METHOD_NAME, ARGS ); fail("expected decorated's throwable to be thrown"); } catch( DummyThrowable ex ) { // expected } mockCallable.verifyExpectations(); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/CallSequenceTest.java0000644000175000017500000001656107662270504030112 0ustar craftermcrafterm00000000000000/* * Created on 14-Apr-2003 */ package test.mockobjects.dynamic; import com.mockobjects.dynamic.*; import com.mockobjects.dynamic.C; import com.mockobjects.dynamic.CallSignature; import com.mockobjects.dynamic.CallSequence; import com.mockobjects.dynamic.Callable; import com.mockobjects.dynamic.CallOnceExpectation; import com.mockobjects.dynamic.Mock; import com.mockobjects.dynamic.ReturnStub; import com.mockobjects.util.AssertMo; import junit.framework.AssertionFailedError; import junit.framework.TestCase; public class CallSequenceTest extends TestCase { final String METHOD_A_NAME = "methodA"; final String METHOD_A_RESULT = "resultA"; final String METHOD_B_NAME = "methodB"; final String METHOD_B_RESULT = "resultB"; final Throwable METHOD_A_EXCEPTION = new DummyThrowable("Configured test throwable"); final String[] METHOD_A_ARGS = new String[] { "a1", "a2" }; final ConstraintMatcher METHOD_A_CONSTRAINTS = C.args(C.eq("a1"), C.eq("a2")); final String[] METHOD_B_ARGS = new String[] { "b1", "b2" }; private CallSequence callSequence = new CallSequence(); private Mock unusedMock = null; private MockCallable methodA = new MockCallable(); private MockCallable methodB = new MockCallable(); private MockCallable mockCallable = new MockCallable(); public CallSequenceTest(String name) { super(name); } public void testCallableThrowableThrown() throws Throwable { final Throwable throwable = new DummyThrowable(); mockCallable.setupMatchesReturn(true); mockCallable.setupCallThrow(throwable); callSequence.addExpect(mockCallable); try { callSequence.call(unusedMock, "hello", new String[0]); } catch (Throwable ex) { assertSame("exception is caught by mock", throwable, ex); } } public void testCallFailsOnEmptyList() throws Throwable { try { callSequence.call(unusedMock, "missingMethod", new Object[0]); } catch (AssertionFailedError ex) { AssertMo.assertIncludes("reports empty set in error message", "no methods", ex.getMessage()); return; } fail("Should fail for a missing item"); } public void testCallFailsWithTooManyCalls() throws Throwable { mockCallable.setupMatchesReturn(true); mockCallable.setupCallReturn(METHOD_A_RESULT); callSequence.addExpect(mockCallable); callSequence.call(unusedMock, "willdefinitelyMatch", new Object[0]); try { callSequence.call(unusedMock, "oneMethodTooMany", new Object[0]); } catch (AssertionFailedError ex) { AssertMo.assertIncludes("reports one method call too many", "too many", ex.getMessage()); return; } fail("Should fail for calling too many times"); } public void testCallPassedToContainedElements() throws Throwable { methodA.setExpectedMatches(METHOD_A_NAME, METHOD_A_ARGS); methodA.setupMatchesReturn(true); methodA.setExpectedCall(unusedMock, METHOD_A_NAME, METHOD_A_ARGS); methodA.setupCallReturn(METHOD_A_RESULT); methodB.setExpectedCallCount(0); callSequence.addExpect(methodA); callSequence.addExpect(methodB); assertSame("expected result from method A", METHOD_A_RESULT, callSequence.call(unusedMock, METHOD_A_NAME, METHOD_A_ARGS)); methodA.verifyExpectations(); methodB.verifyExpectations(); } public void testCallPassedToContainedElementsOtherOrderShouldFail() throws Throwable { methodA.setupMatchesReturn(false); methodA.setupGetDescription("***methodA-description****"); methodB.setupGetDescription("***methodB-description****"); callSequence.addExpect(methodA); callSequence.addExpect(methodB); try { assertSame("expected result from method B", METHOD_B_RESULT, callSequence.call(unusedMock, METHOD_B_NAME, METHOD_B_ARGS)); } catch (AssertionFailedError ex) { String message = ex.getMessage(); AssertMo.assertIncludes("Should have expected error message", "Unexpected call: methodB", message); AssertMo.assertIncludes("Should have arguments in error message (1)", METHOD_B_ARGS[0], message); AssertMo.assertIncludes("Should have arguments in error message (2)", METHOD_B_ARGS[1], message); AssertMo.assertIncludes("Should have Index pointer next to correct item", methodA.getDescription() + " <<<", message); AssertMo.assertIncludes("shows set contents (A)", methodA.getDescription(), message); AssertMo.assertIncludes("shows set contents (B)", methodB.getDescription(), message); AssertMo.assertTrue("Method A should be before method B", message.indexOf(methodA.getDescription()) < message.indexOf(methodB.getDescription())); return; } fail("Should fail due to wrong order"); } public void testConfiguredResultReturned() throws Throwable { final String result = "result"; mockCallable.setupCallReturn(result); mockCallable.setupMatchesReturn(true); callSequence.addExpect(mockCallable); assertSame("result is returned by mock", result, callSequence.call(unusedMock, "method", new Object[0])); } public void testEmptySetVerifies() throws Exception { callSequence.verify(); } public void testFailureIfNoElementMatches() throws Throwable { final String methodCName = "methodC"; final String[] methodCArgs = { "c1", "c2" }; methodA.setExpectedMatches(methodCName, methodCArgs); methodA.setupMatchesReturn(false); methodA.setExpectedCallCount(0); methodA.setupGetDescription("***methodA-description****"); methodB.setExpectedCall(unusedMock, methodCName, methodCArgs); methodB.setupMatchesReturn(false); methodB.setExpectedCallCount(0); methodB.setupGetDescription("***methodB-description****"); callSequence.addExpect(methodA); callSequence.addExpect(methodB); try { callSequence.call(unusedMock, methodCName, methodCArgs); } catch (AssertionFailedError ex) { AssertMo.assertIncludes("method name is in error message", "methodC", ex.getMessage()); AssertMo.assertIncludes("argument is in error message (1)", methodCArgs[0], ex.getMessage()); AssertMo.assertIncludes("argument is in error message (2)", methodCArgs[1], ex.getMessage()); AssertMo.assertIncludes("shows set contents (A)", methodA.getDescription(), ex.getMessage()); AssertMo.assertIncludes("shows set contents (B)", methodB.getDescription(), ex.getMessage()); return; } fail("Should fail for a missing item"); } public void testVerifiesIfAllContainedElementsVerify() throws Throwable { methodA.setExpectedVerifyCalls(1); methodB.setExpectedVerifyCalls(1); callSequence.addExpect(methodA); callSequence.addExpect(methodB); callSequence.verify(); methodA.verifyExpectations(); methodB.verifyExpectations(); } public void testVerifyFailsIfContainedElementDoesNotVerify() throws Exception { methodA.setExpectedVerifyCalls(1); methodA.setupVerifyThrow(new AssertionFailedError("verify failed")); callSequence.addExpect(methodA); try { callSequence.verify(); } catch (AssertionFailedError ex) { methodA.verifyExpectations(); return; } fail("Should have got a failure for contained element failing"); } public void testExpectOverridesMatch() throws Throwable { Callable methodASignature = new CallSignature(METHOD_A_NAME,METHOD_A_CONSTRAINTS, new ReturnStub("result1")); Callable anotherMethodASignature = new CallSignature(METHOD_A_NAME,METHOD_A_CONSTRAINTS, new ReturnStub("result2")); callSequence.addMatch(methodASignature); callSequence.addExpect(new CallOnceExpectation(anotherMethodASignature)); assertSame("expected result from method B, as expect has precendence over match", "result2", callSequence.call(unusedMock, METHOD_A_NAME, METHOD_A_ARGS)); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/ConstraintMatcherTest.java0000644000175000017500000000660407661772071031200 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import com.mockobjects.dynamic.*; import com.mockobjects.dynamic.ConstraintMatcher; import junit.framework.TestCase; public class ConstraintMatcherTest extends TestCase { public ConstraintMatcherTest(String name) { super(name); } public void testNoMatchWhenTooManyArguments() throws Throwable { String[] args = { "arg1", "arg2" }; MockConstraint[] constraints = { new MockConstraint("constraint1", args[0], true) }; ConstraintMatcher constraintMatcher = new FullConstraintMatcher(constraints); assertFalse("Should not match if too many arguments", constraintMatcher.matches(args)); } public void testNoMatchWhenTooFewArguments() throws Throwable { String[] args = { "arg1" }; MockConstraint[] constraints = { new MockConstraint("constraint1", args[0], true), new MockConstraint("constraint2", args[0], true) }; ConstraintMatcher constraintMatcher = new FullConstraintMatcher(constraints); assertFalse("Should not match if too few arguments", constraintMatcher.matches(args)); } public void testNoMatchWhenConstraintIsViolated() throws Throwable { String[] args = { "argA", "argB", "argC" }; MockConstraint[] constraints = { new MockConstraint("constraintA", args[0], true), new MockConstraint("constraintB", args[1], false), new MockConstraint("constraintC", args[2], true) }; ConstraintMatcher constraintMatcher = new FullConstraintMatcher(constraints); assertFalse("Should not match", constraintMatcher.matches(args)); } public void testNoMatchWithNoArgumentsAndCalleeHasArguments() throws Throwable { String[] args = new String[] { "arg1", "arg2" }; MockConstraint[] constraints = new MockConstraint[0]; ConstraintMatcher constraintMatcher = new FullConstraintMatcher(constraints); assertFalse("Should not match", constraintMatcher.matches(args)); } public void testMatchWithNoArguments() throws Throwable { String[] args = new String[0]; MockConstraint[] constraints = new MockConstraint[0]; ConstraintMatcher constraintMatcher = new FullConstraintMatcher(constraints); assertTrue("Should match", constraintMatcher.matches(args)); } public void testMatchAndArgumentsCheckedAgainstConstraints() throws Throwable { String[] args = { "argA", "argB", "argC" }; MockConstraint constraintA = new MockConstraint("constraintA", args[0], true); MockConstraint constraintB = new MockConstraint("constraintB", args[1], true); MockConstraint constraintC = new MockConstraint("constraintC", args[2], true); MockConstraint[] constraints = { constraintA, constraintB, constraintC }; ConstraintMatcher constraintMatcher = new FullConstraintMatcher(constraints); assertTrue("Should match", constraintMatcher.matches(args)); constraintA.verify(); constraintB.verify(); constraintC.verify(); } public void testMatchWithArgument() throws Throwable { String[] args = { "argA" }; MockConstraint constraintA = new MockConstraint("constraintA", args[0], true); ConstraintMatcher constraintMatcher = new FullConstraintMatcher(new MockConstraint[] { constraintA }); assertTrue("Should match", constraintMatcher.matches(args)); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/DummyInterface.java0000644000175000017500000000046407661772072027623 0ustar craftermcrafterm00000000000000/* * Created on 04-Apr-2003 */ package test.mockobjects.dynamic; /** * @author dev */ public interface DummyInterface { public String twoArgMethod( String arg1, String arg2 ) throws Throwable; public String oneArgMethod( String arg1); public void noArgMethodVoid(); public String noArgMethod(); } mockobjects-0.09/src/core/test/mockobjects/dynamic/DummyThrowable.java0000644000175000017500000000036707661772072027654 0ustar craftermcrafterm00000000000000/* * Created on 04-Apr-2003 */ package test.mockobjects.dynamic; /** * @author dev */ public class DummyThrowable extends Throwable { public DummyThrowable() { super(); } public DummyThrowable(String message) { super(message); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/DynamicUtilTest.java0000644000175000017500000000375407661772073027777 0ustar craftermcrafterm00000000000000/* * Created on 16-Apr-2003 */ package test.mockobjects.dynamic; import com.mockobjects.dynamic.DynamicUtil; import com.mockobjects.dynamic.Mock; import com.mockobjects.util.AssertMo; import junit.framework.TestCase; /** * @author e2x */ public class DynamicUtilTest extends TestCase { public DynamicUtilTest(String name) { super(name); } public void testMethodToStringWithoutProxyArg() throws Exception { String[] args = new String[] {"arg1", "arg2" }; String result = DynamicUtil.methodToString("methodName", args); AssertMo.assertIncludes("Should contain method name", "methodName", result); AssertMo.assertIncludes("Should contain firstArg", "arg1", result); AssertMo.assertIncludes("Should contain second Arg", "arg2", result); } public void testMethodToStringWithStringArray() throws Exception { Object[] args = new Object[] { new String[] {"arg1","arg2"}}; String result = DynamicUtil.methodToString("methodName", args); AssertMo.assertIncludes("Should contain method name", "methodName", result); AssertMo.assertIncludes("Should contain args as an array", "[, ]", result); } public void testMethodToStringWithPrimitiveArray() throws Exception { Object[] args = new Object[] { new long[] {1,2}}; String result = DynamicUtil.methodToString("methodName", args); AssertMo.assertIncludes("Should contain method name", "methodName", result); AssertMo.assertIncludes("Should contain args as an array", "[<1>, <2>]", result); } public void testMethodToStringWithProxyArg() throws Exception { Mock mockDummyInterface = new Mock(DummyInterface.class, "DummyMock"); Object[] args = new Object[] {"arg1", mockDummyInterface.proxy()}; String result = DynamicUtil.methodToString("methodName", args); AssertMo.assertIncludes("Should contain method name", "methodName", result); AssertMo.assertIncludes("Should contain firstArg", "arg1", result); AssertMo.assertIncludes("Should contain second Arg", "DummyMock", result); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/ErrorMessageExamples.java0000644000175000017500000000072107661772072031000 0ustar craftermcrafterm00000000000000/* * Created on 30-Apr-03 */ package test.mockobjects.dynamic; import junit.framework.Assert; import junit.textui.TestRunner; public class ErrorMessageExamples { public static void main(String[] args) { TestRunner.main(new String[] { ErrorMessageExamples.class.getName() }); //TODO work out how to build up test methods to be run just by this app } public void testUncalledMethodError() { Assert.assertEquals("should not be equa1", "a", "b"); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/MockCallFactory.java0000644000175000017500000001764407662267447027742 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import com.mockobjects.*; import com.mockobjects.dynamic.CallFactory; import com.mockobjects.dynamic.Callable; import com.mockobjects.dynamic.ConstraintMatcher; public class MockCallFactory implements CallFactory{ private ExpectationCounter myCreateReturnStubCalls = new ExpectationCounter("MockCallFactory.createReturnStub(Object)"); private ReturnValues myActualCreateReturnStubReturnValues = new ReturnValues("MockCallFactory.createReturnStub(Object)", true); private ExpectationList myCreateReturnStubParameter0Values = new ExpectationList("MockCallFactory.createReturnStub(Object) java.lang.Object"); private ExpectationCounter myCreateThrowStubCalls = new ExpectationCounter("MockCallFactory.createThrowStub(Throwable)"); private ReturnValues myActualCreateThrowStubReturnValues = new ReturnValues("MockCallFactory.createThrowStub(Throwable)", true); private ExpectationList myCreateThrowStubParameter0Values = new ExpectationList("MockCallFactory.createThrowStub(Throwable) java.lang.Throwable"); private ExpectationCounter myCreateVoidStubCalls = new ExpectationCounter("MockCallFactory.createVoidStub()"); private ReturnValues myActualCreateVoidStubReturnValues = new ReturnValues("MockCallFactory.createVoidStub()", true); private ExpectationCounter myCreateCallExpectationCalls = new ExpectationCounter("MockCallFactory.createCallExpectation(Callable)"); private ReturnValues myActualCreateCallExpectationReturnValues = new ReturnValues("MockCallFactory.createCallExpectation(Callable)", true); private ExpectationList myCreateCallExpectationParameter0Values = new ExpectationList("MockCallFactory.createCallExpectation(Callable) com.mockobjects.dynamic.Callable"); private ExpectationCounter myCreateCallSignatureCalls = new ExpectationCounter("MockCallFactory.createCallMatch(String, ConstraintMatcher, Callable)"); private ReturnValues myActualCreateCallSignatureReturnValues = new ReturnValues("MockCallFactory.createCallMatch(String, ConstraintMatcher, Callable)", true); private ExpectationList myCreateCallSignatureParameter0Values = new ExpectationList("MockCallFactory.createCallMatch(String, ConstraintMatcher, Callable) java.lang.String"); private ExpectationList myCreateCallSignatureParameter1Values = new ExpectationList("MockCallFactory.createCallMatch(String, ConstraintMatcher, Callable) com.mockobjects.dynamic.ConstraintMatcher"); private ExpectationList myCreateCallSignatureParameter2Values = new ExpectationList("MockCallFactory.createCallMatch(String, ConstraintMatcher, Callable) com.mockobjects.dynamic.Callable"); public void setExpectedCreateReturnStubCalls(int calls){ myCreateReturnStubCalls.setExpected(calls); } public void addExpectedCreateReturnStub(Object arg0){ myCreateReturnStubParameter0Values.addExpected(arg0); } public Callable createReturnStub(Object arg0){ myCreateReturnStubCalls.inc(); myCreateReturnStubParameter0Values.addActual(arg0); Object nextReturnValue = myActualCreateReturnStubReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return (Callable) nextReturnValue; } public void setupExceptionCreateReturnStub(Throwable arg){ myActualCreateReturnStubReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupCreateReturnStub(Callable arg){ myActualCreateReturnStubReturnValues.add(arg); } public void setExpectedCreateThrowStubCalls(int calls){ myCreateThrowStubCalls.setExpected(calls); } public void addExpectedCreateThrowStub(Throwable arg0){ myCreateThrowStubParameter0Values.addExpected(arg0); } public Callable createThrowStub(Throwable arg0){ myCreateThrowStubCalls.inc(); myCreateThrowStubParameter0Values.addActual(arg0); Object nextReturnValue = myActualCreateThrowStubReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return (Callable) nextReturnValue; } public void setupExceptionCreateThrowStub(Throwable arg){ myActualCreateThrowStubReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupCreateThrowStub(Callable arg){ myActualCreateThrowStubReturnValues.add(arg); } public void setExpectedCreateVoidStubCalls(int calls){ myCreateVoidStubCalls.setExpected(calls); } public Callable createVoidStub(){ myCreateVoidStubCalls.inc(); Object nextReturnValue = myActualCreateVoidStubReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return (Callable) nextReturnValue; } public void setupExceptionCreateVoidStub(Throwable arg){ myActualCreateVoidStubReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupCreateVoidStub(Callable arg){ myActualCreateVoidStubReturnValues.add(arg); } public void setExpectedCreateCallExpectationCalls(int calls){ myCreateCallExpectationCalls.setExpected(calls); } public void addExpectedCreateCallExpectation(Callable arg0){ myCreateCallExpectationParameter0Values.addExpected(arg0); } public Callable createCallExpectation(Callable arg0){ myCreateCallExpectationCalls.inc(); myCreateCallExpectationParameter0Values.addActual(arg0); Object nextReturnValue = myActualCreateCallExpectationReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return (Callable) nextReturnValue; } public void setupExceptionCreateCallExpectation(Throwable arg){ myActualCreateCallExpectationReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupCreateCallExpectation(Callable arg){ myActualCreateCallExpectationReturnValues.add(arg); } public void setExpectedCreateCallSignatureCalls(int calls){ myCreateCallSignatureCalls.setExpected(calls); } public void addExpectedCreateCallSignature(String arg0, ConstraintMatcher arg1, Callable arg2){ myCreateCallSignatureParameter0Values.addExpected(arg0); myCreateCallSignatureParameter1Values.addExpectedMany(arg1.getConstraints()); myCreateCallSignatureParameter2Values.addExpected(arg2); } public Callable createCallSignature(String arg0, ConstraintMatcher arg1, Callable arg2){ myCreateCallSignatureCalls.inc(); myCreateCallSignatureParameter0Values.addActual(arg0); myCreateCallSignatureParameter1Values.addActualMany(arg1.getConstraints()); myCreateCallSignatureParameter2Values.addActual(arg2); Object nextReturnValue = myActualCreateCallSignatureReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return (Callable) nextReturnValue; } public void setupExceptionCreateCallSignature(Throwable arg){ myActualCreateCallSignatureReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupCreateCallSignature(Callable arg){ myActualCreateCallSignatureReturnValues.add(arg); } public void verify(){ myCreateReturnStubCalls.verify(); myCreateReturnStubParameter0Values.verify(); myCreateThrowStubCalls.verify(); myCreateThrowStubParameter0Values.verify(); myCreateVoidStubCalls.verify(); myCreateCallExpectationCalls.verify(); myCreateCallExpectationParameter0Values.verify(); myCreateCallSignatureCalls.verify(); myCreateCallSignatureParameter0Values.verify(); myCreateCallSignatureParameter1Values.verify(); myCreateCallSignatureParameter2Values.verify(); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/MockCallable.java0000644000175000017500000000616107661772071027217 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.dynamic.Callable; import com.mockobjects.dynamic.Mock; import com.mockobjects.util.*; public class MockCallable implements Callable { private ExpectationCounter callCount = new ExpectationCounter("call.count"); private ExpectationValue callMock = new ExpectationValue("call.mock"); private ExpectationValue callMethodName = new ExpectationValue("call.methodName"); private ExpectationList callArgs = new ExpectationList("call.args"); private ReturnValue callResult = new ReturnValue("call.return"); private Throwable callThrow = null; private ExpectationValue matchesMethodName = new ExpectationValue("matches.methodName"); private ExpectationList matchesArgs = new ExpectationList("matches.args"); private ReturnValue matchesResult = new ReturnValue("matches.return"); private ExpectationCounter matchesCount = new ExpectationCounter("matches.count"); private ExpectationCounter verifyCount = new ExpectationCounter("verify.count"); private AssertionFailedError verifyError = null; private ReturnValue toStringResult = new ReturnValue("toString.return"); public void setExpectedCallCount( int count ) { callCount.setExpected(count); } public void setExpectedCall( Mock mock, String methodName, Object[] args ) { callMock.setExpected(mock); callMethodName.setExpected(methodName); callArgs.addExpectedMany(args); } public void setupCallReturn( Object result ) { callResult.setValue(result); } public void setupCallThrow( Throwable thrown ) { callThrow = thrown; } public Object call(Mock mock, String methodName, Object[] args) throws Throwable { callMock.setActual(mock); callMethodName.setActual(methodName); callArgs.addActualMany(args); callCount.inc(); if( callThrow != null ) { throw callThrow; } else { return callResult.getValue(); } } public void setExpectedMatches( String methodName, Object[] args ) { matchesMethodName.setExpected(methodName); matchesArgs.addExpectedMany(args); } public void setExpectedMatchesCount(int count) { matchesCount.setExpected(count); } public void setupMatchesReturn( boolean result ) { matchesResult.setValue(result); } public boolean matches(String methodName, Object[] args) { matchesMethodName.setActual(methodName); matchesArgs.addActualMany(args); matchesCount.inc(); return matchesResult.getBooleanValue(); } public void setExpectedVerifyCalls( int count ) { verifyCount.setExpected(count); } public void setupVerifyThrow( AssertionFailedError err ) { verifyError = err; } /** @deprecated to avoid calling verify instead of verifyExpectations */ public void verify() { verifyCount.inc(); if( verifyError != null ) throw verifyError; } /** We have to rename 'verify' because we want to mock the behaviour of the * verify method itself. */ public void verifyExpectations() { Verifier.verifyObject(this); } public void setupGetDescription( String result ) { toStringResult.setValue(result); } public String getDescription() { return (String)toStringResult.getValue(); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/MockCallableAddable.java0000644000175000017500000001250007661772072030447 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import com.mockobjects.*; import com.mockobjects.dynamic.Callable; import com.mockobjects.dynamic.CallableAddable; import com.mockobjects.dynamic.Mock; import com.mockobjects.util.NotImplementedException; //Mock modified for []args public class MockCallableAddable extends MockObject implements CallableAddable { private ExpectationCounter myAddMatchCalls = new ExpectationCounter("com.mockobjects.dynamic.CallableAddable AddMatchCalls"); private ExpectationList myAddMatchParameter0Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable AddMatchParameter0Values"); private ExpectationCounter myAddExpectCalls = new ExpectationCounter("com.mockobjects.dynamic.CallableAddable AddExpectCalls"); private ExpectationList myAddExpectParameter0Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable AddExpectParameter0Values"); private ExpectationCounter myMatchesCalls = new ExpectationCounter("com.mockobjects.dynamic.CallableAddable MatchesCalls"); private ReturnValues myActualMatchesReturnValues = new ReturnValues(true); private ExpectationList myMatchesParameter0Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable MatchesParameter0Values"); private ExpectationList myMatchesParameter1Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable MatchesParameter1Values"); private ExpectationCounter myGetDescriptionCalls = new ExpectationCounter("com.mockobjects.dynamic.CallableAddable GetDescriptionCalls"); private ReturnValues myActualGetDescriptionReturnValues = new ReturnValues(true); private ExpectationCounter myCallCalls = new ExpectationCounter("com.mockobjects.dynamic.CallableAddable CallCalls"); private ReturnValues myActualCallReturnValues = new ReturnValues(true); private ExpectationList myCallParameter0Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable CallParameter0Values"); private ExpectationList myCallParameter1Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable CallParameter1Values"); private ExpectationList myCallParameter2Values = new ExpectationList("com.mockobjects.dynamic.CallableAddable CallParameter2Values"); private ExpectationCounter myVerifyCalls = new ExpectationCounter("com.mockobjects.dynamic.CallableAddable VerifyCalls"); public void reset() { throw new NotImplementedException(); } public void setExpectedAddMatchCalls(int calls) { myAddMatchCalls.setExpected(calls); } public void addExpectedAddMatch(Callable arg0) { myAddMatchParameter0Values.addExpected(arg0); } public void addMatch(Callable arg0) { myAddMatchCalls.inc(); myAddMatchParameter0Values.addActual(arg0); } public void setExpectedAddExpectCalls(int calls) { myAddExpectCalls.setExpected(calls); } public void addExpectedAddExpect(Callable arg0) { myAddExpectParameter0Values.addExpected(arg0); } public void addExpect(Callable arg0) { myAddExpectCalls.inc(); myAddExpectParameter0Values.addActual(arg0); } public void setExpectedMatchesCalls(int calls) { myMatchesCalls.setExpected(calls); } public void addExpectedMatches(String arg0, Object[] arg1) { myMatchesParameter0Values.addExpected(arg0); myMatchesParameter1Values.addExpected(arg1); } public boolean matches(String arg0, Object[] arg1) { myMatchesCalls.inc(); myMatchesParameter0Values.addActual(arg0); myMatchesParameter1Values.addActual(arg1); Object nextReturnValue = myActualMatchesReturnValues.getNext(); return ((Boolean) nextReturnValue).booleanValue(); } public void setupMatches(boolean arg) { myActualMatchesReturnValues.add(new Boolean(arg)); } public void setExpectedGetDescriptionCalls(int calls) { myGetDescriptionCalls.setExpected(calls); } public String getDescription() { myGetDescriptionCalls.inc(); Object nextReturnValue = myActualGetDescriptionReturnValues.getNext(); return (String) nextReturnValue; } public void setupGetDescription(String arg) { myActualGetDescriptionReturnValues.add(arg); } public void setExpectedCallCalls(int calls) { myCallCalls.setExpected(calls); } public void addExpectedCall(Mock arg0, String arg1, Object[] arg2) { myCallParameter0Values.addExpected(arg0); myCallParameter1Values.addExpected(arg1); myCallParameter2Values.addExpectedMany(arg2); } public Object call(Mock arg0, String arg1, Object[] arg2) throws Throwable { myCallCalls.inc(); myCallParameter0Values.addActual(arg0); myCallParameter1Values.addActual(arg1); myCallParameter2Values.addActualMany(arg2); Object nextReturnValue = myActualCallReturnValues.getNext(); return (Object) nextReturnValue; } public void setupCall(Object arg) { myActualCallReturnValues.add(arg); } public void setExpectedVerifyCalls(int calls) { myVerifyCalls.setExpected(calls); } /** @deprected use verifyExpectations as this is a mockmock */ public void verify() { myVerifyCalls.inc(); } public void verifyExpectations() { myAddMatchCalls.verify(); myAddMatchParameter0Values.verify(); myAddExpectCalls.verify(); myAddExpectParameter0Values.verify(); myMatchesCalls.verify(); myMatchesParameter0Values.verify(); myMatchesParameter1Values.verify(); myGetDescriptionCalls.verify(); myCallCalls.verify(); myCallParameter0Values.verify(); myCallParameter1Values.verify(); myCallParameter2Values.verify(); myVerifyCalls.verify(); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/MockConstraint.java0000644000175000017500000000154007661772073027642 0ustar craftermcrafterm00000000000000/* * Created on 04-Apr-2003 */ package test.mockobjects.dynamic; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.constraint.*; /** * @author dev */ public class MockConstraint extends Assert implements Constraint, Verifiable { private String description; private Object expectedArg; private boolean result; private boolean wasChecked = false; public MockConstraint( String description, Object expectedArg, boolean result ) { this.description = description; this.expectedArg = expectedArg; this.result = result; } public String toString() { return description; } public boolean eval( Object arg ) { assertSame( "Should be expected argument", expectedArg, arg ); wasChecked = true; return result; } public void verify() { assertTrue( description + " should have been checked", wasChecked ); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/MockConstraintMatcher.java0000644000175000017500000000474607661772073031161 0ustar craftermcrafterm00000000000000package test.mockobjects.dynamic; import com.mockobjects.*; import com.mockobjects.dynamic.ConstraintMatcher; public class MockConstraintMatcher implements ConstraintMatcher{ private ExpectationCounter myMatchesCalls = new ExpectationCounter("MockConstraintMatcher.matches(Object[])"); private ReturnValues myActualMatchesReturnValues = new ReturnValues("MockConstraintMatcher.matches(Object[])", true); private ExpectationList myMatchesParameter0Values = new ExpectationList("MockConstraintMatcher.matches(Object[]) java.lang.Object"); private ExpectationCounter myGetConstraintsCalls = new ExpectationCounter("MockConstraintMatcher.getConstraints()"); private ReturnValues myActualGetConstraintsReturnValues = new ReturnValues("MockConstraintMatcher.getConstraints()", true); public void setExpectedMatchesCalls(int calls){ myMatchesCalls.setExpected(calls); } public void addExpectedMatches(Object[] arg0){ myMatchesParameter0Values.addExpected(arg0); } public boolean matches(Object[] arg0){ myMatchesCalls.inc(); myMatchesParameter0Values.addActual(arg0); Object nextReturnValue = myActualMatchesReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return ((Boolean) nextReturnValue).booleanValue(); } public void setupExceptionMatches(Throwable arg){ myActualMatchesReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupMatches(boolean arg){ myActualMatchesReturnValues.add(new Boolean(arg)); } public void setExpectedGetConstraintsCalls(int calls){ myGetConstraintsCalls.setExpected(calls); } public Object[] getConstraints(){ myGetConstraintsCalls.inc(); Object nextReturnValue = myActualGetConstraintsReturnValues.getNext(); if (nextReturnValue instanceof ExceptionalReturnValue && ((ExceptionalReturnValue)nextReturnValue).getException() instanceof RuntimeException) throw (RuntimeException)((ExceptionalReturnValue)nextReturnValue).getException(); return (Object[]) nextReturnValue; } public void setupExceptionGetConstraints(Throwable arg){ myActualGetConstraintsReturnValues.add(new ExceptionalReturnValue(arg)); } public void setupGetConstraints(Object[] arg){ myActualGetConstraintsReturnValues.add(arg); } public void verify(){ myMatchesCalls.verify(); myMatchesParameter0Values.verify(); myGetConstraintsCalls.verify(); } } mockobjects-0.09/src/core/test/mockobjects/dynamic/MockTest.java0000644000175000017500000003767707662267447026466 0ustar craftermcrafterm00000000000000/* * Created on 04-Apr-2003 */ package test.mockobjects.dynamic; import com.mockobjects.constraint.*; import com.mockobjects.constraint.IsEqual; import com.mockobjects.dynamic.*; import com.mockobjects.util.*; import junit.framework.*; public class MockTest extends TestCase { private static final String MOCK_NAME = "Test mock"; final String METHOD_NOARG_NAME = "noArgMethodVoid"; final String METHOD_NOARGANDRETURN_NAME = "noArgMethod"; final String METHOD_NOARGANDRETURN_RESULT = "resultNoArgs"; final String METHOD_ONEARG_NAME = "oneArgMethod"; final String METHOD_ONEARG_RESULT = "result1Args"; final String METHOD_TWOARG_NAME = "twoArgMethod"; final String METHOD_TWOARG_RESULT = "resultTwoArgs"; final Throwable METHOD_EXCEPTION = new DummyThrowable("Configured test throwable"); final Object[] METHOD_NOARG_ARGS = new Object[0]; final String[] METHOD_ONEARG_ARGS = new String[] { "oneP1" }; final ConstraintMatcher METHOD_ONEARG_CONSTRAINTS = C.args(C.eq("oneP1")); final String[] METHOD_TWOARG_ARGS = new String[] { "twoP1", "twoP2" }; final ConstraintMatcher METHOD_TWOARG_CONSTRAINTS = C.args(C.eq("twoP1"), C.eq("twoP2")); private DummyInterface proxy; private Mock mock; private MockCallFactory mockCallFactory = new MockCallFactory(); private MockCallable mockCallMatch = new MockCallable(); private MockCallable mockExpectedCall = new MockCallable(); private MockCallable mockReturnStub = new MockCallable(); private MockCallable mockThrowStub = new MockCallable(); private MockCallable mockVoidStub = new MockCallable(); private MockCallableAddable mockCallableAddable = new MockCallableAddable(); public MockTest(String name) throws Exception { super(name); } public void setUp() { mock = new Mock(mockCallFactory, mockCallableAddable, DummyInterface.class, MOCK_NAME); try { proxy = (DummyInterface)mock.proxy(); } catch (ClassCastException ex) { fail("proxy is not of expected interface type"); } } public void testExpectManyAndVoid() throws Throwable { mockCallFactory.setExpectedCreateVoidStubCalls(1); mockCallFactory.setupCreateVoidStub(mockVoidStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, mockVoidStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expect(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectNoneAndReturn() throws Throwable { mockCallFactory.addExpectedCreateReturnStub(METHOD_NOARGANDRETURN_RESULT); mockCallFactory.setupCreateReturnStub(mockReturnStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_NOARGANDRETURN_NAME, C.NO_ARGS, mockReturnStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expectAndReturn(METHOD_NOARGANDRETURN_NAME, METHOD_NOARGANDRETURN_RESULT); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectNoneAndThrow() throws Throwable { mockCallFactory.addExpectedCreateThrowStub(METHOD_EXCEPTION); mockCallFactory.setupCreateThrowStub(mockThrowStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_NOARGANDRETURN_NAME, C.NO_ARGS, mockThrowStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expectAndThrow(METHOD_NOARGANDRETURN_NAME, METHOD_EXCEPTION); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectOneAndThrow() throws Throwable { mockCallFactory.addExpectedCreateThrowStub(METHOD_EXCEPTION); mockCallFactory.setupCreateThrowStub(mockThrowStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockThrowStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expectAndThrow(METHOD_ONEARG_NAME, METHOD_ONEARG_ARGS[0], METHOD_EXCEPTION); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectNoneAndVoid() throws Throwable { mockCallFactory.setExpectedCreateVoidStubCalls(1); mockCallFactory.setupCreateVoidStub(mockVoidStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_NOARG_NAME, C.NO_ARGS, mockVoidStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expect(METHOD_NOARG_NAME); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectOneAndVoid() throws Throwable { mockCallFactory.setExpectedCreateVoidStubCalls(1); mockCallFactory.setupCreateVoidStub(mockVoidStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockVoidStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expect(METHOD_ONEARG_NAME, METHOD_ONEARG_ARGS[0]); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectWithConstraint() throws Throwable { mockCallFactory.setupCreateVoidStub(mockVoidStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockVoidStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expect(METHOD_ONEARG_NAME, new IsEqual(METHOD_ONEARG_ARGS[0])); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectWithConstraintArray() throws Throwable { mockCallFactory.setupCreateVoidStub(mockVoidStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockVoidStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mock.expect(METHOD_ONEARG_NAME, new Constraint[] { new IsEqual(METHOD_ONEARG_ARGS[0])}); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectManyAndReturn() throws Throwable { mockCallFactory.addExpectedCreateReturnStub(METHOD_TWOARG_RESULT); mockCallFactory.setupCreateReturnStub(mockReturnStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, mockReturnStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mockCallableAddable.setupCall(METHOD_TWOARG_RESULT); mock.expectAndReturn(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, METHOD_TWOARG_RESULT); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectManyAndThrow() throws Throwable { mockCallFactory.addExpectedCreateThrowStub(METHOD_EXCEPTION); mockCallFactory.setupCreateThrowStub(mockThrowStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, mockThrowStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mockCallableAddable.setupCall(METHOD_TWOARG_RESULT); mock.expectAndThrow(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, METHOD_EXCEPTION); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testExpectOneAndReturn() throws Throwable { mockCallFactory.addExpectedCreateReturnStub(METHOD_ONEARG_RESULT); mockCallFactory.setupCreateReturnStub(mockReturnStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockReturnStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallFactory.addExpectedCreateCallExpectation(mockCallMatch); mockCallFactory.setupCreateCallExpectation(mockExpectedCall); mockCallableAddable.addExpectedAddExpect(mockExpectedCall); mockCallableAddable.setupCall(METHOD_ONEARG_RESULT); mock.expectAndReturn(METHOD_ONEARG_NAME, METHOD_ONEARG_ARGS[0], METHOD_ONEARG_RESULT); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMatchManyAndReturn() throws Throwable { mockCallFactory.addExpectedCreateReturnStub(METHOD_TWOARG_RESULT); mockCallFactory.setupCreateReturnStub(mockReturnStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, mockReturnStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallableAddable.addExpectedAddMatch(mockCallMatch); mockCallableAddable.setupCall(METHOD_TWOARG_RESULT); mock.matchAndReturn(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, METHOD_TWOARG_RESULT); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMatchNoneAndThrow() throws Throwable { mockCallFactory.addExpectedCreateThrowStub(METHOD_EXCEPTION); mockCallFactory.setupCreateThrowStub(mockThrowStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_NOARG_NAME, C.NO_ARGS, mockThrowStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallableAddable.addExpectedAddMatch(mockCallMatch); mockCallableAddable.setupCall(METHOD_NOARGANDRETURN_RESULT); mock.matchAndThrow(METHOD_NOARG_NAME, METHOD_EXCEPTION); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMatchOneAndThrow() throws Throwable { mockCallFactory.addExpectedCreateThrowStub(METHOD_EXCEPTION); mockCallFactory.setupCreateThrowStub(mockThrowStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockThrowStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallableAddable.addExpectedAddMatch(mockCallMatch); mockCallableAddable.setupCall(METHOD_ONEARG_RESULT); mock.matchAndThrow(METHOD_ONEARG_NAME, METHOD_ONEARG_ARGS[0], METHOD_EXCEPTION); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMatchManyAndThrow() throws Throwable { mockCallFactory.addExpectedCreateThrowStub(METHOD_EXCEPTION); mockCallFactory.setupCreateThrowStub(mockThrowStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, mockThrowStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallableAddable.addExpectedAddMatch(mockCallMatch); mockCallableAddable.setupCall(METHOD_TWOARG_RESULT); mock.matchAndThrow(METHOD_TWOARG_NAME, METHOD_TWOARG_CONSTRAINTS, METHOD_EXCEPTION); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMatchOneAndReturn() throws Throwable { mockCallFactory.addExpectedCreateReturnStub(METHOD_ONEARG_RESULT); mockCallFactory.setupCreateReturnStub(mockReturnStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_ONEARG_NAME, METHOD_ONEARG_CONSTRAINTS, mockReturnStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallableAddable.addExpectedAddMatch(mockCallMatch); mockCallableAddable.setupCall(METHOD_ONEARG_RESULT); mock.matchAndReturn(METHOD_ONEARG_NAME, METHOD_ONEARG_ARGS[0], METHOD_ONEARG_RESULT); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMatchNoneAndReturn() throws Throwable { mockCallFactory.addExpectedCreateReturnStub(METHOD_NOARGANDRETURN_RESULT); mockCallFactory.setupCreateReturnStub(mockReturnStub); mockCallFactory.addExpectedCreateCallSignature(METHOD_NOARG_NAME, C.NO_ARGS, mockReturnStub); mockCallFactory.setupCreateCallSignature(mockCallMatch); mockCallableAddable.addExpectedAddMatch(mockCallMatch); mockCallableAddable.setupCall(METHOD_ONEARG_RESULT); mock.matchAndReturn(METHOD_NOARG_NAME, METHOD_NOARGANDRETURN_RESULT); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMockAnnotatesAssertionFailedErrors() throws Throwable { final String originalMessage = "original message"; mockCallableAddable.setupCall(new AssertionFailedError(originalMessage)); try { proxy.noArgMethodVoid(); } catch (AssertionFailedError err) { AssertMo.assertIncludes("should contain original message", originalMessage, err.getMessage()); AssertMo.assertIncludes("should contain mock name", MOCK_NAME, err.getMessage()); } } public void testMockNameFromClass() throws Exception { assertEquals("mockString", Mock.mockNameFromClass(String.class)); } public void testMockProxyReturnsConfiguredResult() throws Throwable { final String result = "configured result"; mockCallableAddable.setupCall(result); assertSame("result is returned by mock", result, proxy.oneArgMethod(METHOD_TWOARG_ARGS[0])); } public void testMockProxySendsAllArgument() throws Throwable { mockCallableAddable.addExpectedCall(mock, METHOD_TWOARG_NAME, METHOD_TWOARG_ARGS); mockCallableAddable.setupCall("result ignored"); proxy.twoArgMethod(METHOD_TWOARG_ARGS[0], METHOD_TWOARG_ARGS[1]); mockCallableAddable.verifyExpectations(); } public void testMockProxySendsEmptyArrayWhenNoArguments() throws Exception { mockCallableAddable.addExpectedCall(mock, METHOD_NOARG_NAME, METHOD_NOARG_ARGS); mockCallableAddable.setupCall("result ignored"); proxy.noArgMethodVoid(); Verifier.verifyObject(this); mockCallableAddable.verifyExpectations(); } public void testMockProxyThrowsConfiguredExceptions() throws Throwable { final Throwable throwable = new DummyThrowable(); mockCallableAddable.setupCall(new ThrowStub(throwable)); try { proxy.noArgMethodVoid(); } catch (Throwable ex) { assertSame("exception is caught by mock", throwable, ex); } } public void testMockToStringContainsName() { AssertMo.assertIncludes("result of toString() should include name", MOCK_NAME, mock.toString()); } public void testMockVerifies() throws Exception { mockCallableAddable.setExpectedVerifyCalls(1); mock.verify(); mockCallableAddable.verifyExpectations(); } public void testProxyEquality() throws Exception { assertTrue("Should handle proxy equality without checking expectations", proxy.equals(proxy)); } public void testProxyInEquality() throws Exception { boolean IGNORED_RESULT = true; CallStub ret = new ReturnStub(new Boolean(IGNORED_RESULT)); mockCallFactory.setupCreateReturnStub(ret); mockCallFactory.setupCreateCallSignature(new CallSignature("call",C.anyArgs(1),ret)); mockCallableAddable.setupCall(new Boolean(false)); mock.matchAndReturn("call", C.anyArgs(1), IGNORED_RESULT); assertFalse("Should handle proxy inequality by calling through", proxy.equals("not a proxy")); Verifier.verifyObject(this); } public void testProxyToString() throws Exception { assertEquals("Should get a mock name without touching the underlying mock", MOCK_NAME, DynamicUtil.proxyToString(proxy)); mock.verify(); // should not fail on a proxyToString call } } mockobjects-0.09/src/core/test/mockobjects/dynamic/StubTest.java0000644000175000017500000000200707661772072026457 0ustar craftermcrafterm00000000000000/* * Created on 07-Apr-2003 */ package test.mockobjects.dynamic; import com.mockobjects.dynamic.*; import junit.framework.*; /** * @author dev */ public class StubTest extends TestCase { public StubTest(String name) { super(name); } public void testReturnStub() throws Throwable { final String result = "result"; ReturnStub stub = new ReturnStub(result); String ignoredMethodName = "methodName"; Mock ignoredMock = null; Object[] ignoredArgs = new Object[0]; assertSame( "Should be the same result object", result, stub.call( ignoredMock, ignoredMethodName, ignoredArgs ) ); } public void testThrowStub() { final Throwable throwable = new DummyThrowable(); ThrowStub stub = new ThrowStub(throwable); String ignoredMethodName = "methodName"; Mock ignoredMock = null; Object[] ignoredArgs = new Object[0]; try { stub.call( ignoredMock, ignoredMethodName, ignoredArgs ); } catch( Throwable t ) { assertSame( "Should be the same throwable", throwable, t ); } } } mockobjects-0.09/src/core/Readme.txt0000644000175000017500000000012607331064400021046 0ustar craftermcrafterm00000000000000Core library for implementing mock objects and implementation for core java libraries mockobjects-0.09/src/core/mo_java1_compatibility.jar0000644000175000017500000001367607331064400024252 0ustar craftermcrafterm00000000000000PK³* META-INF/þÊPKPK³*META-INF/MANIFEST.MFóMÌËLK-.Ñ K-*ÎÌϳR0Ô3àår.JM,IMÑuª ë(h—æ)øf&åW—¤æ+xæ%ëiòrñrPK3ù5¤DDPK í²*com/PK í²*com/mockobjects/PK í²*com/mockobjects/test/PKí²* com/mockobjects/test/Vector.javaµRKO1¾“ðæˆì/¸È£!U n0ki´°Û]ÛY1þw[¶¢ ‰M3ýóMvK.ÖüQ‚(r’b]<¬¤@KPZì6ÍF5AºH(¤SHfÓ9R˜ÓÙú½;66Nné˜NÒ^ʦOêÏØpDaÔK OÓ{J'ëáM‡tÈ%p½ô tÈœƒ‘Ï•2r X€ ¥áX°UY½8öYTîÛƒ¬Ñ&hY=dJ€È¸µ0w€3o(õÒŠ¿pR¡ÊH>¼܉£¨.\¾€‰B[4U¨ó\j$[N\aV-hy;Çe–î©[¿|ž8®JnxJ+T<ð’ …ï®Ç_£8|_s$Ý>ãÿÃn)"`L #½É)µ½èÐêïEÛGDû»‡é»P…âçW6+£AË׳…OÊ~³s÷ PK¦ÏH]PKí²*com/mockobjects/ArrayList.java½T]oÚ0}Gâ?ܾZ™²—=P¤…UÙhA4bBUŒc:·!a¶ÃÚMýﻎ†´ú0+ þ8÷Üs¯OXSö@ï8°lEV{È÷œiÕk6šN»Ù€6DóIÑ&Óñ,0 ¦sø×á9øÓ©?…ׄ—“Qp\E~ޝ |0 ‡\øÑ÷ ¸*ؾ¿uI—|šÆf]òÉtLÆfƒ%T)ð¥¤O#¡4ðGÍÓXÁ=ÝP’k‘êË$ü1hÀÑi·íÉ«8–¥J˼€bm+žjRÂ:v²Î‰`UŒ×2¤à†Ê×\z­žÝyþx6ø²¦’®@¤B šœÓ5eB?áZ¿'!ûa5÷ÿEr aî,L™ä†äƒu˜¸C¶÷Ë=© ÚÉD 4޽qarš¯DIA䈷ØX©¬1A%Ù†ûIâ¨Ô¡•Ï"Ë$þ3§‰òªJðµÃ,–à)ñ›c¾£~qLì²UaÌ\ç2…%Òñ^™ÍŒ%Þµm>ôá´‡?g`p~|¼“¬Lx¤E¸­ÂÇ–´ˆSZØ>Ø×Q£¥Ü~®¦^äÿÖ!w{øOµ×·ÐFJÓ”ñlY®¾?Ž®êxËPn‰ä¨ùÍÎÖ‰uêîxió˜?îètÖ&[í+€¯†šKj¾Tá&^eʽ =sm¯ÑY7· ³¢xïeCr•'»®CÓØJú§=qV¸Áy¦Î2–àFܢܳk€ý6¶ÒŒÏ_PKŒsf:ŸPKí²*com/mockobjects/HashMap.java½O;OÃ0Þ+õ?ÜØF•£°0t!iL µQQÇ‹c m^ŠBüwì&U…@0pòpçû÷ÕÈøÈU)*v¨’=gRÌÇ£ñÈ4Æ#0 ÞEâ¢u¸õ\ [ºÞco¼¬ìÍÊ·#ðüèŽú4ˆíØ  vÖž»¤°TK‡Æ÷”G­÷Ö"¹,S=€E.ôÂÔ~u›ä–£°Bñäc üEò2°Çg$­Ìr¢7“œÃ›f*Ó0ºFY DV•B6-“U£Ó¼”d™]ÓöŒÉT B_¢­y3™Î»Ÿ÷¿:ÁU •™Ì0_`,“¯j–ߣç¤/î;Güù$¯0½Æ£ÊƒêgÖñN„~8;E†UïPKïBâÇÉPKí²*com/mockobjects/HashSet.java½TQoÚ0~Gâ?ÜÞ­BÙËh¥…•l- ˆ˜ªªƘխq˜íÐuÓþû.Ž%„vâaŽýÝwßÝ}ÉŠÐ'òM–þ2¡OÉì‘Q£;õZ½ÖjÖkЄøvB<„Ñx8z!LÃñ-tƒIt ý`ÒŸ„1D7£ëð&ÄA ¸;ŽzW!\#è†ñ·0X®/½¯m¿í"çÙ´ýÙE+ËW¯QA´†>Ñf€ý4LÎ5<’5ñSÃ…?Em‰‚ßpµšÍ|ƒÔRäåškƒµHmTj¡X×’Iã°V¾Y¥3Ái‘Ékd”à–NWLyN~òçø\ðyEY—Üp".ÉŠPn^ðÙ¼-å  …eÄ\@¨»‹$U,#9ªªÓ,jŸëýbO+‚Êõ»ôë„ÏÌçÞÐZ¸aË|á}0\ûØC¸Ôž…4¶ˆ yBaÓå ·rRÁˆª°–z“5 „pTzßlŽg–$H"ýH‰Ð^ñbä÷.ଃçäkþ‹!;ð““€¼n(ncX®*Àå.dK1“* TÄ:ÛëöC‚ÞÕb³o´XeÇk)!Ðòìßšìl‚²Kðýª ‘”%‹Â×%U.Ÿ#+FÖÈè^ d¨·2îu%e¡‘aŠdï-w›]s9Éž7HÛÄCæÊ ½»“ØÏƒ·9PL§bÏaù=(«E”T’7Œûf€³/jõÿáõ[¿b埜l¤àºy –Aµ ª`ï`ý9íªòÂ^SHšR®\eÃaßi·ÏÛ‹_¥Míµß=øbQ 2t 4SLp«g.ñ"5·ß»8»þ~PKvéšUŽPKí²*com/mockobjects/Map.java­VïoÛ6ý¼ùÐÙF /ù2 uÚ¶²ºuâÀu2ìËZ:Û\$Q%©dưÿ}GR¢$ÿJ ÌZËä½»{÷ø¨œEOl‰4HEô$–a¤Õ»ó³ó³~ïü zp?ŽBø8›ŽÃ9ÜÌæpËrXlsžÁ§ñg¸ .ƒ_X|œ|ú»›-è{7Ó),þ¸ax7¦6Ÿ=NÆá3§“ÛÉÝpÂhv{?™†Îç³9ÜÁãäËÃp ÃßBø4|0o(=E¹ŒWÍTãS‡‹¡Í˜µ¾é /– ¨NrÅ"´¥ÿCËôÙ[ 3-·Õªùô{½ò¡sÔ…Ìè Ân‰/)Qå"‹y¶-h+@TA>øWi£¿+¸ï¾Ìì<`ú3n;];—×ê{fI'“LVvkÊòœ–=̆)X"f 1ÏÃJŠÔî\’P E@g¹µ¿q¢Ži!R` õ{;èÓW¹ÙÂEÖ½°!TR‘hbåê‰X’“EãŠgŸ¦ïõÞŽøhBOR˜'¤ƒoä^¸ÞØ­*Lj¯8ÆÉwDngIƒb¾ó»$ÞL)ŠõÆ¡ÚI]€Å=Ì7ì™ Ù&‹þ÷\oÑŽ%Y¼µcôP{ã<<Æã;0–œI––ÍføR~£~–D á™ú²C£ñI|œilGí$7ô½(xÈT‘çBjŒgU­áßZê+zLWy¡wZª°~pØTe&4x8(Ùi?ØK?J˜R#¦ô^ÎȬ¸É5$âºõ0eê\â3õªhnBK4›¾R}&I‚k– åºH ¬U)3Uh/¦V%ÿ[!wE’Ü kªu»þ tdÓ(R®wŠ0ÓÊÆË–©.€eñ!*il§Â[âi;‚ª¡|¶pµ;4a$RÒzé uŒÀÊN,~-XÂuCò•A›ò´,ÊóUŠe͉ö ›3¬0˕äî=’ Ð/®p*J"MÑ“+¥ÞÈmnir¦¢”¬c{aâ_¹çãØ†¯´ç}“hûo/ƒêÚº¾6{›¯v7½…F``‰Tƶ.¹ä›7ÇÒ•&ÿZÂö¶*eùk;iùc·ÛÂôM÷ȶíøUáT´÷‡åØLQoD /B>):kƉšm$…ªoИ¯V( å<Í4gÙÚ•7ƒJï1}_)eT½ÄuiQ©ËÙsä·ÄÚP²WÞ¾gðÞ¡0tXi¢‡ª>ûþ^Ñ¥ ² ÊA”'T>ÍWº7Ô\\]ঽ†ì[oô0ÄnóÄÙÙ•=*¨î[ËÞ[´†ïä·«c€ð³‘V-f“tD9IMðçðñÖá•0ß§FwÆkawËÎHa¼ÜÓz…£½u®ëk: õ£ 5̲lk(tN²ƒpÐQÈÈc}-¸¬¯Ø5ft''>>ÈÜ]ebÝü} -g?üšø :¨ãby)üXwyp¹¥Ç-GKEÓ …üûñßó3úûPK=Ø3ˆƒ PK í²*com/mockobjects/sql/PKí²*com/mockobjects/sql/Array.java±‚0E÷&ý‡;3”àâàTä…Tl0Ž¥T#0ÈbŒÿnêxsNÎ}Z7Ø»‡›G1În˜ÛÞ»õ%ú®u;Î8‹#ÎÁ\5ÁTÐuÕ¨ŒÐP}E*ÏjUèTiTU)­U–r©‘’¹•ÿÆ!;&"[Ø© ‰Ø‡ŸÇ´úåf‡\ûƇ³/g?PK*à·øŸPKí²*com/mockobjects/sql/Blob.java±‚0E÷&ý‡;3”àâàDå…Tl0ŒPª„e3þ»©ãÍ99÷ÙÙ©»9X?‹ÙÛÉ÷£³ë[ŒCowœqGœ!‚i5ÁTÐuÕ¨ŒÐPÝB¦gµ‡*ô‰ *MjTUIÖ*Ë yª!É\ˆÊ㑈-ºe‰Ø‡Ÿû²º×µ³òá{|8ûröPKh­rŽžPKí²*com/mockobjects/sql/Clob.java½‚0E÷&}‡;3”àâàÄÏRh°Á8–R Ô(›ñÝMoÎɹOc'ss°~³·“ïGg×·‡Þî8ã,Ž8C}QÝ@µM' BGíYz’9d¥ŽTQ­S-›:HY+‹’P¦ é3Qýoì‹C"±…Y†0ˆMqø¹/«{]uȾLJ³/g?PK¨r‹³ŽžPKí²*com/mockobjects/sql/Ref.java±‚0E÷&ý‡;3”àâàòBªMm0Œ¥#0ÊfüwSÇ›srîÓºÉÞ=Ü:‹yuÓÚÞmo1ö;pÆYq†¦USC麑9¡!Ý"K¯òYª •T™ÔȺ R¦e^ŠT!#s#ªþS~ND"ö°K± ?eó¯Á:í|8ûröPK@’Ÿ'PK³* META-INF/þÊPK³*3ù5¤DD=META-INF/MANIFEST.MFPK í²*Ãcom/PK í²*åcom/mockobjects/PK í²*com/mockobjects/test/PKí²*¦ÏH] Fcom/mockobjects/test/Vector.javaPKí²*Œsf:ŸÜcom/mockobjects/ArrayList.javaPKí²*ïBâÇÉbcom/mockobjects/HashMap.javaPKí²*T‡”3¥Êcom/mockobjects/HashSet.javaPKí²*véšUŽG com/mockobjects/Iterator.javaPKí²*=Ø3ˆƒ ç com/mockobjects/Map.javaPK í²*µcom/mockobjects/sql/PKí²**à·øŸçcom/mockobjects/sql/Array.javaPKí²*h­rŽžÂcom/mockobjects/sql/Blob.javaPKí²*¨r‹³Žž›com/mockobjects/sql/Clob.javaPKí²*@’Ÿ'tcom/mockobjects/sql/Ref.javaPK]Kmockobjects-0.09/src/examples/0000755000175000017500000000000010117310266017777 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/0000755000175000017500000000000010117310266020555 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/0000755000175000017500000000000010117310266023060 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/examples/0000755000175000017500000000000010117310266024676 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/0000755000175000017500000000000010117310266027027 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/AllTests.java0000644000175000017500000000162607331064400031432 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import junit.framework.Test; import junit.framework.TestSuite; import com.mockobjects.util.SuiteBuilder; import com.mockobjects.util.TestCaseMo; public class AllTests extends TestCaseMo { private static final Class THIS = AllTests.class; public AllTests(String name) { super(name); } public static void addTestCalculator(TestSuite suite) { suite.addTestSuite(TestCalculator.class); } public static void addTestCalculatorServlet(TestSuite suite) { suite.addTestSuite(TestCalculatorServlet.class); } public static void addTestSavingCalculator(TestSuite suite) { suite.addTestSuite(TestSavingCalculator.class); } public static void main(String[] args) { start(new String[]{ THIS.getName()}); } public static Test suite() { return SuiteBuilder.buildTest(THIS); } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/Calculator.java0000644000175000017500000000112007331064401031756 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; public class Calculator implements IntCalculator { /** * Calculator constructor comment. */ public Calculator() { super(); } public int calculate(int value1, int value2, String operation) throws CalculatorException { if ("/add".equalsIgnoreCase(operation)) { return value1 + value2; } else if ("/subtract".equalsIgnoreCase(operation)) { return value1 - value2; } else { throw new CalculatorException("Bad operation: " + operation); } } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/CalculatorException.java0000644000175000017500000000147207331064401033647 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; public class CalculatorException extends Exception { /** * CalculatorException constructor comment. */ public CalculatorException() { super(); } /** * CalculatorException constructor comment. * @param arg1 java.lang.String */ public CalculatorException(String arg1) { super(arg1); } /** * CalculatorException constructor comment. * @param arg1 java.lang.String * @param arg2 java.lang.Throwable */ public CalculatorException(String msg, Throwable ex) { this(msg + ex.toString()); } /** * CalculatorException constructor comment. * @param arg1 java.lang.Throwable */ public CalculatorException(Throwable ex) { this(ex.toString()); } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/CalculatorServlet.java0000644000175000017500000000404207335314235033340 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CalculatorServlet extends HttpServlet { IntCalculator myCalculator; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } public String getServletInfo() { return super.getServletInfo(); } public void init() throws ServletException { try { Connection connection = Database.createConnection(); myCalculator = new SqlSavingCalculator( new Calculator(), connection.prepareStatement("INSERT INTO LOG VALUES (?)")); } catch (SQLException ex) { throw new ServletException(ex); } } public void init(IntCalculator calculator) { myCalculator = calculator; } public void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter wr = response.getWriter(); try { int value1 = Integer.parseInt(request.getParameter("value1")); int value2 = Integer.parseInt(request.getParameter("value2")); String operation = request.getPathInfo(); wr.println(myCalculator.calculate(value1, value2, operation)); } catch (NumberFormatException ex) { wr.println("Calculation failed " + ex); } catch (CalculatorException ex) { wr.println("Calculation failed " + ex); } } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/Database.java0000644000175000017500000000121307331064401031374 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import java.sql.Connection; import java.sql.DriverManager; import javax.servlet.ServletException; /** * Creation date: (18/Mar/01 6:21 pm) * @author: */ public class Database { /** * Database constructor comment. */ public Database() { super(); } public static Connection createConnection() throws ServletException { try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); return DriverManager.getConnection("jdbc:mysql:///test"); } catch (Exception ex) { throw new ServletException(ex); } } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/IntCalculator.java0000644000175000017500000000025107331064401032435 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; public interface IntCalculator { int calculate(int value1, int value2, String operation) throws CalculatorException; }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/MockCalculator.java0000644000175000017500000000247607331064401032607 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; public class MockCalculator extends MockObject implements IntCalculator { private int myResult; private ExpectationValue myValue1 = new ExpectationValue("value1"); private ExpectationValue myValue2 = new ExpectationValue("value2"); private ExpectationValue myOperation = new ExpectationValue("operation"); private String myBadOperation; /** * MockCalculator constructor comment. */ public MockCalculator() { super(); } public int calculate(int value1, int value2, String operation) throws CalculatorException { myValue1.setActual(value1); myValue2.setActual(value2); myOperation.setActual(operation); return myResult; } public void setExpectedCalculation(int value1, int value2, String operation) { myValue1.setExpected(value1); myValue2.setExpected(value2); myOperation.setExpected(operation); } public void setupResult(int result) { myResult = result; } public void setupThrowBadOperation(String opName) { myBadOperation = opName; } public void verify() { myValue1.verify(); myValue2.verify(); myOperation.verify(); } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/SqlSavingCalculator.java0000644000175000017500000000154207331064401033616 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import java.sql.PreparedStatement; import java.sql.SQLException; public class SqlSavingCalculator implements IntCalculator { private IntCalculator myIntCalculator; private PreparedStatement myStatement; public SqlSavingCalculator(IntCalculator intCalculator, PreparedStatement preparedStatement) { super(); myIntCalculator = intCalculator; myStatement = preparedStatement; } public int calculate(int value1, int value2, java.lang.String operation) throws CalculatorException { int result = myIntCalculator.calculate(value1, value2, operation); try { myStatement.setInt(1, result); myStatement.execute(); return result; } catch (SQLException ex) { throw new CalculatorException(ex); } } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/TestCalculator.java0000644000175000017500000000172107331064401032625 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import com.mockobjects.util.TestCaseMo; /** * JUnit test case for CalculatorImplTest */ public class TestCalculator extends TestCaseMo { private static final Class THIS = TestCalculator.class; Calculator myCalculator = new Calculator(); public TestCalculator(String name) { super(name); } public static void main(String[] args) { start(new String[]{ THIS.getName()}); } public void testAdd() throws CalculatorException { assertEquals("add", 9, myCalculator.calculate(5, 4, "/add")); } public void testBadOperation() { try { myCalculator.calculate(5, 4, "Bad operation"); fail("Should have thrown an exception"); } catch (CalculatorException expected) { } } public void testSubtract() throws CalculatorException { assertEquals("subtract", 1, myCalculator.calculate(5, 4, "/subtract")); } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/TestCalculatorServlet.java0000644000175000017500000000413307331064401034172 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import java.io.IOException; import javax.servlet.ServletException; import com.mockobjects.servlet.MockHttpServletRequest; import com.mockobjects.servlet.MockHttpServletResponse; import com.mockobjects.util.AssertMo; import com.mockobjects.util.TestCaseMo; public class TestCalculatorServlet extends TestCaseMo { private static final Class THIS = TestCalculatorServlet.class; MockHttpServletRequest myMockHttpRequest = new MockHttpServletRequest(); MockHttpServletResponse myMockHttpResponse = new MockHttpServletResponse(); CalculatorServlet myServlet = new CalculatorServlet(); public TestCalculatorServlet(String name) { super(name); } public static void main(String[] args) { start(new String[]{ THIS.getName()}); } public void testBadParameter() throws ServletException, IOException { myMockHttpRequest.setupAddParameter("value1", "5"); myMockHttpRequest.setupAddParameter("value2", "fred"); myMockHttpResponse.setExpectedContentType("text/plain"); myServlet.init(new MockCalculator()); myServlet.doGet(myMockHttpRequest, myMockHttpResponse); myMockHttpResponse.verify(); AssertMo.assertIncludes("Should include result", "failed", myMockHttpResponse.getOutputStreamContents()); } public void testSuccessfulCalculation() throws ServletException, IOException { myMockHttpRequest.setupAddParameter("value1", "5"); myMockHttpRequest.setupAddParameter("value2", "3"); myMockHttpRequest.setupPathInfo("/add"); MockCalculator mockCalculator = new MockCalculator(); mockCalculator.setupResult(666); myMockHttpResponse.setExpectedContentType("text/plain"); mockCalculator.setExpectedCalculation(5, 3, "/add"); myServlet.init(mockCalculator); myServlet.doGet(myMockHttpRequest, myMockHttpResponse); mockCalculator.verify(); myMockHttpResponse.verify(); AssertMo.assertIncludes("Should get expected result", "666", myMockHttpResponse.getOutputStreamContents()); } }mockobjects-0.09/src/examples/com/mockobjects/examples/calcserver/TestSavingCalculator.java0000644000175000017500000000362007333354122034001 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.calcserver; import java.sql.SQLException; import com.mockobjects.sql.MockPreparedStatement; import com.mockobjects.util.TestCaseMo; public class TestSavingCalculator extends TestCaseMo { private static final Class THIS = TestSavingCalculator.class; public TestSavingCalculator(String name) { super(name); } public static void main(String[] args) { start(new String[]{ THIS.getName()}); } public void testSave() throws CalculatorException { MockCalculator myMockCalculator = new MockCalculator(); MockPreparedStatement myMockStatement = new MockPreparedStatement(); SqlSavingCalculator mySavingCalculator = new SqlSavingCalculator(myMockCalculator, myMockStatement); myMockCalculator.setupResult(666); myMockCalculator.setExpectedCalculation(5, 3, "/add"); myMockStatement.addExpectedSetParameter(1, 666); myMockStatement.setExpectedExecuteCalls(1); mySavingCalculator.calculate(5, 3, "/add"); myMockCalculator.verify(); myMockStatement.verify(); } public void testSqlFailure() throws CalculatorException { MockCalculator myMockCalculator = new MockCalculator(); MockPreparedStatement myMockStatement = new MockPreparedStatement(); SqlSavingCalculator mySavingCalculator = new SqlSavingCalculator(myMockCalculator, myMockStatement); myMockCalculator.setExpectedCalculation(5, 3, "/add"); myMockStatement.setExpectedExecuteCalls(1); myMockStatement.setupThrowExceptionOnExecute(new SQLException("Mock exception")); try { mySavingCalculator.calculate(5, 3, "/add"); fail("Should throw exception"); } catch (CalculatorException expected) { // } myMockCalculator.verify(); myMockStatement.verify(); } }mockobjects-0.09/src/examples/com/mockobjects/examples/dynamic/0000755000175000017500000000000010117310266026322 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/examples/dynamic/MailSender.java0000644000175000017500000000031707661772074031234 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.dynamic; // An example interface that has an Object[] as a parameter public interface MailSender { boolean sendMail(String subject, String[] recipients, String body); } mockobjects-0.09/src/examples/com/mockobjects/examples/dynamic/SimpleServlet.java0000644000175000017500000000246007661772073032007 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.dynamic; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * @author dev */ public class SimpleServlet extends HttpServlet { private Timer timer; private MailSender mailSender; public SimpleServlet(Timer aTimer, MailSender aMailSender) { super(); timer = aTimer; mailSender = aMailSender; } public SimpleServlet() { this(null,null); // really this would be a proper timer and mail sender... } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String body = request.getParameter("body"); String subject = request.getParameter("subject"); String[] recipients = request.getParameterValues("recipients"); String browser = request.getParameter("browser-identifier"); // Cause a failure by calling something unexpected //String pet = request.getParameter("favourite-pet"); int age = request.getIntHeader("age"); response.setContentType("text/html"); PrintWriter writer = response.getWriter(); writer.print("timer before:" + timer.getTime()); mailSender.sendMail(subject, recipients, body); writer.print("timer after:" + timer.getTime()); } } mockobjects-0.09/src/examples/com/mockobjects/examples/dynamic/SimpleServletTest.java0000644000175000017500000000713507662265315032650 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.dynamic; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import com.mockobjects.dynamic.C; import com.mockobjects.dynamic.Mock; import com.mockobjects.dynamic.OrderedMock; /** * A sample test case showing usage of the dynamic mock library. * It has also been used as an acceptance test for the implementation * of the library, and so uses different variations of some of the calls */ public class SimpleServletTest extends TestCase { final String SUBJECT = "Mail Subject"; final String[] RECIPIENTS = new String[]{ "tim@hotmail.com", "steve@yahoo.com"}; final String BODY = "Mail Body"; public SimpleServletTest(String name) { super(name); } /* public void testDoGetOldStyle() throws ServletException, IOException { Mock mockHttpServletResponse = new Mock(HttpServletResponse.class); Mock mockHttpServletRequest = new Mock(HttpServletRequest.class); CallSequence params = new CallSequence(); params.expectAndReturn( new Constraint[] { C.eq("body") }, "this is the body" ); params.expectAndReturn( new Constraint[] { C.eq("subject") }, "mail from tim" ); params.expectAndReturn( new Constraint[] { C.eq("recipients") }, new String[] { "nat.pryce@b13media.com", "steve@m3p.com" } ); mockHttpServletRequest.expect( "getParameter", params ); SimpleServlet aServlet = new SimpleServlet(); aServlet.doGet((HttpServletRequest) mockHttpServletRequest.proxy(), (HttpServletResponse) mockHttpServletResponse.proxy()); mockHttpServletRequest.verify(); mockHttpServletResponse.verify(); } */ public void testDoGet() throws ServletException, IOException { Mock mockHttpServletRequest = new Mock(HttpServletRequest.class); Mock mockHttpServletResponse = new OrderedMock(HttpServletResponse.class, "Response with non-default name"); Mock mockTimer = new Mock(Timer.class); Mock mockMailSender = new Mock(MailSender.class); // Set no expectations but answer a value for the specified method mockHttpServletRequest.matchAndReturn( "getParameter", C.eq("browser-identifier"), "MSIE-5.0" ); mockHttpServletRequest.matchAndReturn("getIntHeader", C.ANY_ARGS, 20); mockHttpServletRequest.expectAndReturn( "getParameter", "subject", SUBJECT ); mockHttpServletRequest.expectAndReturn("getParameterValues", "recipients", RECIPIENTS); mockHttpServletRequest.expectAndReturn( "getParameter", C.args(C.eq("body")), BODY ); mockTimer.expectAndReturn("getTime", 10000); mockTimer.expectAndReturn("getTime", 20000); mockMailSender.expectAndReturn("sendMail", C.eq(SUBJECT, RECIPIENTS, BODY),true); final PrintWriter contentWriter = new PrintWriter(new StringWriter()); mockHttpServletResponse.expect( "setContentType", "text/html"); mockHttpServletResponse.expectAndReturn( "getWriter", contentWriter ); // Proposed enhancement to allow individual ordering // // CallSignature m1 = mockHttpServletResponse.expect( "setContentType", "text/html"); // CallSignature m2 = mockHttpServletResponse.expectAndReturn( "getWriter", C.args(), contentWriter ); // m1.expectBefore(m2); SimpleServlet aServlet = new SimpleServlet((Timer)mockTimer.proxy(), (MailSender)mockMailSender.proxy()); aServlet.doGet((HttpServletRequest) mockHttpServletRequest.proxy(), (HttpServletResponse) mockHttpServletResponse.proxy()); mockHttpServletRequest.verify(); mockHttpServletResponse.verify(); mockTimer.verify(); mockMailSender.verify(); } } mockobjects-0.09/src/examples/com/mockobjects/examples/dynamic/Timer.java0000644000175000017500000000014107661772073030263 0ustar craftermcrafterm00000000000000 package com.mockobjects.examples.dynamic; public interface Timer { int getTime(); } mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/0000755000175000017500000000000010117310266027212 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/AllTests.java0000644000175000017500000000122307331064401031607 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; import junit.framework.TestSuite; import junit.framework.Test; import com.mockobjects.util.TestCaseMo; import com.mockobjects.util.SuiteBuilder; public class AllTests extends TestCaseMo { private static final Class THIS = AllTests.class; public AllTests(String name) { super(name); } public static void addTestMailingList(TestSuite suite) { suite.addTestSuite(TestMailingList.class); } public static void main(String[] args) { start(new String[]{ THIS.getName()}); } public static Test suite() { return SuiteBuilder.buildTest(THIS); } }mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/DatabaseConstants.java0000644000175000017500000000022307333354122033460 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; public interface DatabaseConstants { public final static int UNIQUE_CONSTRAINT_VIOLATED = 1; } mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/ListAction.java0000644000175000017500000000023707342331656032144 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; public interface ListAction { public void applyTo(String email, String name) throws MailingListException; } mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/MailingList.java0000644000175000017500000000375407342331656032316 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; import java.sql.*; public class MailingList { static public final String INSERT_SQL = "insert into mailing_list(email_address, name) values(?, ?)"; static public final String DELETE_SQL = "delete from mailing_list where email_address = ?"; static public final String LIST_SQL = "select * from mailing_list"; public void addMember(Connection connection, String emailAddress, String name) throws MailingListException, SQLException { PreparedStatement statement = connection.prepareStatement(INSERT_SQL); try { statement.setString(1, emailAddress); statement.setString(2, name); statement.execute(); } catch (SQLException ex) { if (ex.getErrorCode() == DatabaseConstants.UNIQUE_CONSTRAINT_VIOLATED) { throw new MailingListException("Email address exists: " + emailAddress); } else { throw ex; } } finally { statement.close(); } } public void removeMember(Connection connection, String emailAddress) throws MailingListException, SQLException { PreparedStatement statement = connection.prepareStatement(DELETE_SQL); try { statement.setString(1, emailAddress); if (statement.executeUpdate() == 0) { throw new MailingListException("Could not find email address: " + emailAddress); } } finally { statement.close(); } } public void applyToAllMembers(Connection connection, ListAction listMembers) throws MailingListException, SQLException { Statement statement = connection.createStatement(); try { ResultSet results = statement.executeQuery(LIST_SQL); while (results.next()) { listMembers.applyTo(results.getString("email_address"), results.getString("name")); } } finally { statement.close(); } } } mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/MailingListException.java0000644000175000017500000000032607331064401034152 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; public class MailingListException extends Exception { public MailingListException(String s) { super(s); } public MailingListException() { } } mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/MockListAction.java0000644000175000017500000000250107342331656032752 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; import com.mockobjects.MockObject; import com.mockobjects.ExpectationList; import com.mockobjects.MapEntry; import com.mockobjects.ExpectationCounter; public class MockListAction extends MockObject implements ListAction { private ExpectationList members = new ExpectationList("MockListAction.members"); private ExpectationCounter memberCount = new ExpectationCounter("MockListAction.count"); private MailingListException memberException = null; public void applyTo(String email, String name) throws MailingListException { memberCount.inc(); if (null != memberException) { throw memberException; } members.addActual(constructEntry(email, name)); } public void addExpectedMember(String email, String name) { members.addExpected(constructEntry(email, name)); } public void setExpectedMemberCount(int count) { memberCount.setExpected(count); } public void setExpectNoMembers() { memberCount.setExpectNothing(); members.setExpectNothing(); } public void setupThrowExceptionOnMember(MailingListException exception) { memberException = exception; } private Object constructEntry(String email, String name) { return new MapEntry(email, name); } } mockobjects-0.09/src/examples/com/mockobjects/examples/mailinglist/TestMailingList.java0000644000175000017500000002017607375434430033153 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.mailinglist; import java.sql.SQLException; import com.mockobjects.sql.*; import com.mockobjects.util.TestCaseMo; public class TestMailingList extends TestCaseMo { public TestMailingList(String name) { super(name); } public final static String[] COLUMN_NAMES = new String[] {"email_address", "name"}; public final static String EMAIL = "fred.bloggs@an.address"; public final static String NAME = "Fred Bloggs"; public final static String[] ONE_ROW = new String[] {EMAIL, NAME}; public final static String[][] TWO_ROWS = new String[][] { ONE_ROW, new String[] {EMAIL + 2, NAME + 2}}; private MailingList list = new MailingList(); private MockListAction mockListAction = new MockListAction(); private MockConnection mockConnection = new MockConnection(); private MockPreparedStatement mockPreparedStatement = new MockPreparedStatement(); private MockStatement mockStatement = new MockStatement(); public void setUp() { mockConnection.setupAddPreparedStatement(mockPreparedStatement); mockConnection.setupStatement(mockStatement); } public void testAddNewMember() throws MailingListException, SQLException { setExpectationsForAddMember(); list.addMember(mockConnection, EMAIL, NAME); verifyJDBC(); } public void testAddExistingMember() throws SQLException { mockPreparedStatement.setupThrowExceptionOnExecute( new SQLException("MockStatment", "Duplicate", DatabaseConstants.UNIQUE_CONSTRAINT_VIOLATED)); setExpectationsForAddMember(); try { list.addMember(mockConnection, EMAIL, NAME); fail("Should have thrown exception"); } catch (MailingListException ignored) { } verifyJDBC(); } public void testPrepareStatementFailsForAdd() throws MailingListException { mockConnection.setupThrowExceptionOnPrepareOrCreate(new SQLException("MockConnection")); mockConnection.addExpectedPreparedStatementString(MailingList.INSERT_SQL); mockPreparedStatement.setExpectedExecuteCalls(0); mockPreparedStatement.setExpectedCloseCalls(0); try { list.addMember(mockConnection, EMAIL, NAME); fail("Should have thrown exception"); } catch (SQLException expected) { } verifyJDBC(); } public void testRemoveMember() throws MailingListException, SQLException { mockPreparedStatement.setupUpdateCount(1); setExpectationsForRemoveMember(); list.removeMember(mockConnection, EMAIL); verifyJDBC(); } public void testRemoveMissingMember() throws SQLException { mockPreparedStatement.setupUpdateCount(0); setExpectationsForRemoveMember(); try { list.removeMember(mockConnection, EMAIL); fail("Should have thrown exception"); } catch (MailingListException expected) { } verifyJDBC(); } public void testListNoMembers() throws MailingListException, SQLException { MockMultiRowResultSet mockResultSet = makeMultiRowResultSet(); mockResultSet.setExpectedNextCalls(1); mockListAction.setExpectNoMembers(); setExpectationsForListMembers(); list.applyToAllMembers(mockConnection, mockListAction); verifyJDBC(); mockResultSet.verify(); mockListAction.verify(); } public void testListOneMember() throws MailingListException, SQLException { MockSingleRowResultSet mockResultSet = new MockSingleRowResultSet(); mockStatement.setupResultSet(mockResultSet); mockResultSet.addExpectedNamedValues(COLUMN_NAMES, ONE_ROW); mockResultSet.setExpectedNextCalls(2); mockListAction.addExpectedMember(EMAIL, NAME); setExpectationsForListMembers(); list.applyToAllMembers(mockConnection, mockListAction); verifyJDBC(); mockResultSet.verify(); mockListAction.verify(); } public void testListTwoMembers() throws MailingListException, SQLException { MockMultiRowResultSet mockResultSet = makeMultiRowResultSet(); mockResultSet.setupRows(TWO_ROWS); mockResultSet.setExpectedNextCalls(3); mockListAction.setExpectedMemberCount(2); setExpectationsForListMembers(); list.applyToAllMembers(mockConnection, mockListAction); verifyJDBC(); mockResultSet.verify(); mockListAction.verify(); } public void testListmembersFailure() throws SQLException { MockMultiRowResultSet mockResultSet = makeMultiRowResultSet(); mockResultSet.setupRows(TWO_ROWS); mockListAction.setupThrowExceptionOnMember(new MailingListException()); mockResultSet.setExpectedNextCalls(1); setExpectationsForListMembers(); try { list.applyToAllMembers(mockConnection, mockListAction); fail("Should have thrown exception"); } catch (MailingListException expected) { } mockResultSet.verify(); mockListAction.verify(); } public void testListResultSetFailure() throws MailingListException { MockMultiRowResultSet mockResultSet = makeMultiRowResultSet(); mockResultSet.setupRows(TWO_ROWS); mockResultSet.setupThrowExceptionOnGet(new SQLException("Mock Exception")); mockResultSet.setExpectedNextCalls(1); mockListAction.setExpectNoMembers(); setExpectationsForListMembers(); try { list.applyToAllMembers(mockConnection, mockListAction); fail("Should have thrown exception"); } catch (SQLException expected) { } mockResultSet.verify(); mockListAction.verify(); } public void testListStatementFailure() throws MailingListException { mockStatement.setupThrowExceptionOnExecute(new SQLException("Mock exception")); mockListAction.setExpectNoMembers(); setExpectationsForListMembers(); try { list.applyToAllMembers(mockConnection, mockListAction); fail("Should have thrown exception"); } catch (SQLException expected) { } mockListAction.verify(); } public void testListConnectionFailure() throws MailingListException { mockConnection.setupThrowExceptionOnPrepareOrCreate(new SQLException("Mock Exception")); mockConnection.setExpectedCreateStatementCalls(1); mockStatement.setExpectedCloseCalls(0); mockStatement.setExpectedExecuteCalls(0); mockListAction.setExpectNoMembers(); try { list.applyToAllMembers(mockConnection, mockListAction); fail("Should have thrown exception"); } catch (SQLException expected) { } mockListAction.verify(); } private MockMultiRowResultSet makeMultiRowResultSet() { MockMultiRowResultSet mockResultSet = new MockMultiRowResultSet(); mockStatement.setupResultSet(mockResultSet); mockResultSet.setupColumnNames(COLUMN_NAMES); return mockResultSet; } private void setExpectationsForListMembers() { mockConnection.setExpectedCreateStatementCalls(1); mockStatement.setExpectedQueryString(MailingList.LIST_SQL); mockStatement.setExpectedCloseCalls(1); mockStatement.setExpectedExecuteCalls(1); } private void setExpectationsForAddMember() { setExpectationsForPreparedStatement(MailingList.INSERT_SQL); mockPreparedStatement.addExpectedSetParameters(ONE_ROW); } private void setExpectationsForRemoveMember() { setExpectationsForPreparedStatement(MailingList.DELETE_SQL); mockPreparedStatement.addExpectedSetParameters(new Object[] {EMAIL}); } private void setExpectationsForPreparedStatement(String sqlStatement) { mockConnection.addExpectedPreparedStatementString(sqlStatement); mockPreparedStatement.setExpectedExecuteCalls(1); mockPreparedStatement.setExpectedCloseCalls(1); } private void verifyJDBC() { mockConnection.verify(); mockStatement.verify(); mockPreparedStatement.verify(); } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/0000755000175000017500000000000010117310266026540 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/examples/com/mockobjects/examples/password/AllTests.java0000644000175000017500000000124007375434455031156 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; import junit.framework.Test; import junit.framework.TestSuite; import com.mockobjects.util.SuiteBuilder; import com.mockobjects.util.TestCaseMo; public class AllTests extends TestCaseMo { private static final Class THIS = AllTests.class; public AllTests(String name) { super(name); } public static void addForgotPasswordServlet(TestSuite suite) { suite.addTestSuite(TestForgotPasswordServlet.class); } public static void main(String[] args) { start(new String[]{ THIS.getName()}); } public static Test suite() { return SuiteBuilder.buildTest(THIS); } }mockobjects-0.09/src/examples/com/mockobjects/examples/password/ForgotPasswordServlet.java0000644000175000017500000000256507375434455033766 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ForgotPasswordServlet extends HttpServlet { public static final String SENT_PARAM_NAME = "sent"; public static final String EMAIL_FAILED_PARAM_NAME = "bademail"; public static final String EMAIL_NOT_FOUND_PARAM_NAME = "noemail"; public static final String EMAIL_PARAM = "email"; private PasswordReminder passwordReminder; public ForgotPasswordServlet(PasswordReminder aPasswordReminder) { super(); passwordReminder = aPasswordReminder; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String emailAddress = request.getParameter(EMAIL_PARAM); try { passwordReminder.sendReminder(emailAddress); redirectFor(response, emailAddress); } catch (NotFoundException e) { throw new ServletException("Password not found", e); } } private void redirectFor(HttpServletResponse response, String emailAddress) throws IOException { response.sendRedirect("sent_uri?" + EMAIL_PARAM + "=" + emailAddress); } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/MailingException.java0000644000175000017500000000033007644124011032640 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; public class MailingException extends Exception { public MailingException() { super(); } public MailingException(String s) { super(s); } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/MockPasswordReminder.java0000644000175000017500000000142607340324133033512 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; public class MockPasswordReminder extends MockObject implements PasswordReminder { private ExpectationValue emailAddress = new ExpectationValue("MockPasswordReminder email"); private boolean emailNotFound = false; public void sendReminder(String anEmailAddress) throws NotFoundException { emailAddress.setActual(anEmailAddress); if (emailNotFound) { throw new NotFoundException("Not found: " + anEmailAddress); } } public void setExpectedEmailAddress(String anEmailAddress) { emailAddress.setExpected(anEmailAddress); } public void setupEmailNotFound() { emailNotFound = true; } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/NotFoundException.java0000644000175000017500000000034307375434455033041 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; public class NotFoundException extends PasswordException { public NotFoundException() { super(); } public NotFoundException(String s) { super(s); } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/PasswordException.java0000644000175000017500000000033307375434455033106 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; public class PasswordException extends Exception { public PasswordException() { super(); } public PasswordException(String s) { super(s); } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/PasswordReminder.java0000644000175000017500000000023607340324133032676 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; public interface PasswordReminder { public void sendReminder(String emailAddress) throws NotFoundException; } mockobjects-0.09/src/examples/com/mockobjects/examples/password/StubServletConfig.java0000644000175000017500000000126307342426370033027 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import junit.framework.AssertionFailedError; public class StubServletConfig implements ServletConfig { public String getInitParameter(String s) { throw new AssertionFailedError("not expected: " + s); } public Enumeration getInitParameterNames() { throw new AssertionFailedError("not expected"); } public ServletContext getServletContext() { throw new AssertionFailedError("not expected"); } public String getServletName() { throw new AssertionFailedError("not expected"); } } mockobjects-0.09/src/examples/com/mockobjects/examples/password/TestForgotPasswordServlet.java0000644000175000017500000000505007375434455034616 0ustar craftermcrafterm00000000000000package com.mockobjects.examples.password; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import com.mockobjects.servlet.MockHttpServletRequest; import com.mockobjects.servlet.MockHttpServletResponse; import com.mockobjects.util.TestCaseMo; public class TestForgotPasswordServlet extends TestCaseMo { public static final String SENT_URI = "sent_uri"; public static final String EMAIL_FAILED_URI = "bad_email_uri"; public static final String EMAIL_NOT_FOUND_URI = "no_email_uri"; public static final String EMAIL = "email@an.address"; public TestForgotPasswordServlet(String name) { super(name); } private MockHttpServletRequest mockRequest = new MockHttpServletRequest(); private MockHttpServletResponse mockResponse = new MockHttpServletResponse(); private MockPasswordReminder mockReminder = new MockPasswordReminder(); private ForgotPasswordServlet passwordServlet; public void setUp() throws ServletException, IOException { passwordServlet = new ForgotPasswordServlet(mockReminder); mockRequest.setupAddParameter(ForgotPasswordServlet.EMAIL_PARAM, EMAIL); } public void testReminderEmailSent() throws ServletException, IOException { mockReminder.setExpectedEmailAddress(EMAIL); mockResponse.setExpectedRedirect( SENT_URI + "?" + ForgotPasswordServlet.EMAIL_PARAM + "=" + EMAIL); passwordServlet.doGet(mockRequest, mockResponse); mockResponse.verify(); mockReminder.verify(); } /* public void testEmailNotFound() throws ServletException, IOException { mockReminder.setupEmailNotFound(); mockReminder.setExpectedEmailAddress(EMAIL); mockResponse.setExpectedRedirect(EMAIL_NOT_FOUND_URI + "?email=" + EMAIL); passwordServlet.doGet(mockRequest, mockResponse); mockResponse.verify(); mockReminder.verify(); } private ServletConfig createStubServletConfig() { return new StubServletConfig() { public String getInitParameter(String s) { if (ForgotPasswordServlet.SENT_PARAM_NAME.equals(s)) { return SENT_URI; } else if (ForgotPasswordServlet.EMAIL_FAILED_PARAM_NAME.equals(s)) { return EMAIL_FAILED_URI; } else if (ForgotPasswordServlet.EMAIL_NOT_FOUND_PARAM_NAME.equals(s)) { return EMAIL_NOT_FOUND_URI; } return super.getInitParameter(s); } }; }*/ } mockobjects-0.09/src/examples/Readme.txt0000644000175000017500000000006407513001241021731 0ustar craftermcrafterm00000000000000Examples of how to use the core mockobjects library.mockobjects-0.09/src/extensions/0000755000175000017500000000000010117310266020360 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/alt/0000755000175000017500000000000010117310266021140 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/alt/org/0000755000175000017500000000000010117310266021727 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/alt/org/apache/0000755000175000017500000000000010117310266023150 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/alt/org/apache/commons/0000755000175000017500000000000010117310266024623 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/alt/org/apache/commons/httpclient/0000755000175000017500000000000010117310266027001 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/alt/org/apache/commons/httpclient/HttpClientFactory.java0000644000175000017500000000025707466473266033305 0ustar craftermcrafterm00000000000000package alt.org.apache.commons.httpclient; import org.apache.commons.httpclient.HttpClient; public interface HttpClientFactory { public HttpClient createHttpClient(); } mockobjects-0.09/src/extensions/alt/org/apache/commons/httpclient/HttpClientFactoryImpl.java0000644000175000017500000000036307466473266034125 0ustar craftermcrafterm00000000000000package alt.org.apache.commons.httpclient; import org.apache.commons.httpclient.HttpClient; public class HttpClientFactoryImpl implements HttpClientFactory{ public HttpClient createHttpClient() { return new HttpClient(); } } mockobjects-0.09/src/extensions/alt/org/apache/commons/httpclient/HttpMethodFactory.java0000644000175000017500000000060607466473266033305 0ustar craftermcrafterm00000000000000package alt.org.apache.commons.httpclient; import org.apache.commons.httpclient.methods.*; public interface HttpMethodFactory { public PostMethod createPostMethod(); public GetMethod createGetMethod(); public PutMethod createPutMethod(); public DeleteMethod createDeleteMethod(); public HeadMethod createHeadMethod(); public OptionsMethod createOptionsMethod(); } mockobjects-0.09/src/extensions/alt/org/apache/commons/httpclient/HttpMethodFactoryImpl.java0000644000175000017500000000123207466473266034123 0ustar craftermcrafterm00000000000000package alt.org.apache.commons.httpclient; import org.apache.commons.httpclient.methods.*; public class HttpMethodFactoryImpl implements HttpMethodFactory{ public PostMethod createPostMethod() { return new PostMethod(); } public GetMethod createGetMethod() { return new GetMethod(); } public PutMethod createPutMethod() { return new PutMethod(); } public DeleteMethod createDeleteMethod() { return new DeleteMethod(); } public HeadMethod createHeadMethod() { return new HeadMethod(); } public OptionsMethod createOptionsMethod() { return new OptionsMethod(); } } mockobjects-0.09/src/extensions/alt/org/apache/commons/httpclient/HttpStateFactory.java0000644000175000017500000000025207466473266033142 0ustar craftermcrafterm00000000000000package alt.org.apache.commons.httpclient; import org.apache.commons.httpclient.HttpState; public interface HttpStateFactory{ public HttpState createHttpState(); } mockobjects-0.09/src/extensions/com/0000755000175000017500000000000010117310266021136 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/connextra/0000755000175000017500000000000010117310266023137 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/connextra/util/0000755000175000017500000000000010117310266024114 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/connextra/util/Clock.java0000644000175000017500000000022407644131562026023 0ustar craftermcrafterm00000000000000package com.connextra.util; import java.util.*; public interface Clock { public Date getDate(); public long getTime(); public void stop(); }mockobjects-0.09/src/extensions/com/connextra/util/ReaderFactory.java0000644000175000017500000000054007644131562027523 0ustar craftermcrafterm00000000000000package com.connextra.util; import java.io.*; import java.net.*; public interface ReaderFactory { public Reader create(File aFile) throws IOException; public Reader create(InputStream anInputStream); // BufferedReader due to ElectricXML parsing requiring a reader with mark interface public BufferedReader create(URL aURL) throws IOException; }mockobjects-0.09/src/extensions/com/connextra/util/RealClock.java0000644000175000017500000000071707644131562026636 0ustar craftermcrafterm00000000000000package com.connextra.util; import java.util.*; public class RealClock implements Clock { private long myStoppedTime = -1; public RealClock() { super(); } public Date getDate() { return new Date(); } public long getTime() { if (myStoppedTime != -1) { return myStoppedTime; } return System.currentTimeMillis(); } public void stop() { myStoppedTime = getTime(); } public String toString() { return String.valueOf(getTime()); } }mockobjects-0.09/src/extensions/com/connextra/util/RealReaderFactory.java0000644000175000017500000000070707644131562030334 0ustar craftermcrafterm00000000000000package com.connextra.util; import java.io.*; import java.net.*; public class RealReaderFactory implements ReaderFactory { public Reader create(File aFile) throws IOException { return new FileReader(aFile); } public Reader create(InputStream anInputStream) { return new InputStreamReader(anInputStream); } public BufferedReader create(URL aURL) throws IOException { return new BufferedReader(new InputStreamReader(aURL.openStream())); } }mockobjects-0.09/src/extensions/com/connextra/util/RealWriterFactory.java0000644000175000017500000000060107644131562030377 0ustar craftermcrafterm00000000000000package com.connextra.util; import java.io.*; public class RealWriterFactory implements WriterFactory { public RealWriterFactory() { super(); } public Writer create(OutputStream anOutputStream) { return new OutputStreamWriter(anOutputStream); } public Writer createFileWriter(String filename) throws java.io.IOException { return new FileWriter(new File(filename)); } }mockobjects-0.09/src/extensions/com/connextra/util/WriterFactory.java0000644000175000017500000000031307644131562027573 0ustar craftermcrafterm00000000000000package com.connextra.util; import java.io.*; public interface WriterFactory { public Writer create(OutputStream anOutputStream); public Writer createFileWriter(String filename) throws IOException; }mockobjects-0.09/src/extensions/com/mockobjects/0000755000175000017500000000000010117310266023441 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/apache/0000755000175000017500000000000010117310266024662 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/0000755000175000017500000000000010117310266026335 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/0000755000175000017500000000000010117310266030513 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockGetMethod.java0000644000175000017500000001450107660455667034101 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import com.mockobjects.*; import com.mockobjects.util.AssertMo; import com.mockobjects.util.Verifier; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.GetMethod; import java.io.File; import java.io.IOException; import java.io.InputStream; public class MockGetMethod extends GetMethod implements Verifiable { private ExpectationValue myFollowRedirects; // lazy initialise because of super constructor private ExpectationValue myPath = new ExpectationValue("path"); private ExpectationSet myPairs = new ExpectationSet("pairs"); private ReturnObjectList myStatusCodes = new ReturnObjectList("status code"); private String myResponseBody; private String myStatusText; private final MockMethodHelper helper = new MockMethodHelper(); public void setExpectedPath(String aPath) { myPath.setExpected(aPath); } public void setPath(String aPath) { myPath.setActual(aPath); } public String getPath() { AssertMo.notImplemented(getClass().getName()); return null; } public void setStrictMode(boolean b) { AssertMo.notImplemented(getClass().getName()); } public boolean isStrictMode() { AssertMo.notImplemented(getClass().getName()); return false; } public void setRequestHeader(String s, String s1) { AssertMo.notImplemented(getClass().getName()); } public void setUseDisk(boolean b) { AssertMo.notImplemented(getClass().getName()); } public void setRequestHeader(Header header) { AssertMo.notImplemented(getClass().getName()); } public boolean getUseDisk() { AssertMo.notImplemented(getClass().getName()); return false; } public void addRequestHeader(String s, String s1) { AssertMo.notImplemented(getClass().getName()); } public void setTempDir(String s) { AssertMo.notImplemented(getClass().getName()); } public void addRequestHeader(Header header) { AssertMo.notImplemented(getClass().getName()); } public String getTempDir() { AssertMo.notImplemented(getClass().getName()); return null; } public Header getRequestHeader(String s) { AssertMo.notImplemented(getClass().getName()); return null; } public void setTempFile(String s) { AssertMo.notImplemented(getClass().getName()); } public void removeRequestHeader(String s) { AssertMo.notImplemented(getClass().getName()); } public String getTempFile() { AssertMo.notImplemented(getClass().getName()); return null; } public boolean getFollowRedirects() { AssertMo.notImplemented(getClass().getName()); return false; } public File getFileData() { AssertMo.notImplemented(getClass().getName()); return null; } public void setExpectedFollowRedirects(boolean aFollowRedirects) { if (myFollowRedirects == null) { myFollowRedirects = new ExpectationValue("follow redirects"); } myFollowRedirects.setExpected(aFollowRedirects); } public void setFollowRedirects(boolean aFollowRedirects) { if (myFollowRedirects == null) { myFollowRedirects = new ExpectationValue("follow redirects"); } myFollowRedirects.setActual(aFollowRedirects); } public void setFileData(File file) { AssertMo.notImplemented(getClass().getName()); } public void setQueryString(String s) { AssertMo.notImplemented(getClass().getName()); } public String getName() { AssertMo.notImplemented(getClass().getName()); return null; } public void addExpectedQueryString(NameValuePair aPair) { myPairs.addExpected(new MapEntry(aPair.getName(), aPair.getValue())); } public void setQueryString(NameValuePair[] aPairs) { for (int i = 0; i < aPairs.length; i++) { myPairs.addActual(new MapEntry( aPairs[i].getName(), aPairs[i].getValue())); } } public void recycle() { AssertMo.notImplemented(getClass().getName()); } public String getQueryString() { AssertMo.notImplemented(getClass().getName()); return null; } public byte[] getResponseBody() { AssertMo.notImplemented(getClass().getName()); return new byte[]{}; } public Header[] getRequestHeaders() { AssertMo.notImplemented(getClass().getName()); return null; } public void setupGetResponseBodyAsString(String aResponseBody) { myResponseBody = aResponseBody; } public String getResponseBodyAsString() { return myResponseBody; } public boolean validate() { AssertMo.notImplemented(getClass().getName()); return false; } public InputStream getResponseBodyAsStream() throws IOException { AssertMo.notImplemented(getClass().getName()); return null; } public void addGetStatusCode(int aStatusCode) { myStatusCodes.addObjectToReturn(new Integer(aStatusCode)); } public int getStatusCode() { return ((Integer) myStatusCodes.nextReturnObject()).intValue(); } public void setupGetStatusText(String aStatusText) { myStatusText = aStatusText; } public String getStatusText() { return myStatusText; } public Header[] getResponseHeaders() { AssertMo.notImplemented(getClass().getName()); return new Header[]{}; } public Header getResponseHeader(String key) { return helper.getResponseHeader(key); } public void addGetResponseHeader(String key, Header header) { helper.addGetResponseHeader(key, header); } public boolean hasBeenUsed() { AssertMo.notImplemented(getClass().getName()); return false; } public int execute(HttpState state, HttpConnection connection) throws HttpException, IOException { AssertMo.notImplemented(getClass().getName()); return 0; } public boolean isHttp11() { AssertMo.notImplemented(getClass().getName()); return false; } public void setHttp11(boolean b) { AssertMo.notImplemented(getClass().getName()); } public void verify() { Verifier.verifyObject(this); } } mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpClient.java0000644000175000017500000000237307466473266034302 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpState; import com.mockobjects.*; import com.mockobjects.util.Verifier; public class MockHttpClient extends HttpClient implements Verifiable{ private final ExpectationValue method = new ExpectationValue("method"); private final ExpectationValue body = new ExpectationValue("body"); private int statusCode; private ExpectationValue httpState = new ExpectationValue("httpState"); public void setExpectedMethod(HttpMethod method){ this.method.setExpected(method); } public void setExpectedBody(String body){ this.body.setExpected(body); } public int executeMethod(HttpMethod method){ this.method.setActual(method); return statusCode; } public void setupStatusCode(int statusCode){ this.statusCode = statusCode; } public void setState(HttpState httpState){ this.httpState.setActual(httpState); } public void setExpectedState(HttpState httpState){ this.httpState.setExpected(httpState); } public void verify(){ Verifier.verifyObject(this); } } ././@LongLink0000644000175000017500000000014510117310275011321 Lustar 00000000000000mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpClientFactory.javamockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpClientFactory.java0000644000175000017500000000076707466473266035637 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import org.apache.commons.httpclient.HttpClient; import com.mockobjects.MockObject; import alt.org.apache.commons.httpclient.HttpClientFactory; public class MockHttpClientFactory extends MockObject implements HttpClientFactory { private HttpClient httpClient; public void setupCreateHttpClient(HttpClient httpClient){ this.httpClient = httpClient; } public HttpClient createHttpClient() { return httpClient; } } mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpMethod.java0000644000175000017500000000541107660455667034301 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import com.mockobjects.MockObject; import com.mockobjects.ReturnObjectBag; import org.apache.commons.httpclient.*; import java.io.IOException; import java.io.InputStream; public class MockHttpMethod extends MockMethodHelper implements HttpMethod { public String getName() { notImplemented(); return null; } public void setPath(String path) { notImplemented(); } public String getPath() { notImplemented(); return null; } public void setStrictMode(boolean strictMode) { notImplemented(); } public boolean isStrictMode() { notImplemented(); return false; } public void setRequestHeader(String name, String value) { notImplemented(); } public void setRequestHeader(Header header) { notImplemented(); } public void addRequestHeader(String name, String value) { notImplemented(); } public void addRequestHeader(Header header) { notImplemented(); } public Header getRequestHeader(String name) { notImplemented(); return null; } public void removeRequestHeader(String name) { notImplemented(); } public boolean getFollowRedirects() { notImplemented(); return false; } public void setFollowRedirects(boolean followRedirects) { notImplemented(); } public void setQueryString(String queryString) { notImplemented(); } public void setQueryString(NameValuePair[] nameValuePair) { notImplemented(); } public String getQueryString() { notImplemented(); return null; } public Header getRequestHeaders()[] { notImplemented(); return null; } public boolean validate() { notImplemented(); return false; } public int getStatusCode() { notImplemented(); return -1; } public String getStatusText() { notImplemented(); return null; } public Header getResponseHeaders()[] { notImplemented(); return null; } public byte getResponseBody()[] { notImplemented(); return null; } public String getResponseBodyAsString() { notImplemented(); return null; } public InputStream getResponseBodyAsStream() throws IOException { notImplemented(); return null; } public boolean hasBeenUsed() { notImplemented(); return false; } public int execute(HttpState state, HttpConnection connection) throws HttpException, IOException { notImplemented(); return -1; } public void recycle() { notImplemented(); } } ././@LongLink0000644000175000017500000000014510117310275011321 Lustar 00000000000000mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpMethodFactory.javamockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpMethodFactory.java0000644000175000017500000000226007466473266035627 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import com.mockobjects.MockObject; import com.mockobjects.ReturnObjectList; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.*; import alt.org.apache.commons.httpclient.HttpMethodFactory; public class MockHttpMethodFactory extends MockObject implements HttpMethodFactory { private final ReturnObjectList methods = new ReturnObjectList("methods"); public void addCreateMethod(HttpMethod method) { methods.addObjectToReturn(method); } public PostMethod createPostMethod() { return (PostMethod) methods.nextReturnObject(); } public PutMethod createPutMethod() { return (PutMethod) methods.nextReturnObject(); } public GetMethod createGetMethod() { return (GetMethod) methods.nextReturnObject(); } public DeleteMethod createDeleteMethod() { return (DeleteMethod) methods.nextReturnObject(); } public HeadMethod createHeadMethod() { return (HeadMethod) methods.nextReturnObject(); } public OptionsMethod createOptionsMethod() { return (OptionsMethod) methods.nextReturnObject(); } } mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpState.java0000644000175000017500000000205207466473266034136 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import com.mockobjects.*; import com.mockobjects.util.*; import org.apache.commons.httpclient.HttpState; public class MockHttpState extends HttpState implements Verifiable { public void addCookie(org.apache.commons.httpclient.Cookie cookie){ } public void addCookies(org.apache.commons.httpclient.Cookie[] cookie){ } public org.apache.commons.httpclient.Cookie getCookies()[]{ return null; } public org.apache.commons.httpclient.Cookie getCookies(String s1, int i1, String s2, boolean b1, java.util.Date d1)[]{ return null; } public boolean purgeExpiredCookies(){ return false; } public boolean purgeExpiredCookies(java.util.Date date){ return false; } public void setCredentials(String string, org.apache.commons.httpclient.Credentials credentials){ } public org.apache.commons.httpclient.Credentials getCredentials(String string){ return null; } public void verify(){ Verifier.verifyObject(this); } } mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockHttpStateFactory.java0000644000175000017500000000074307466473266035473 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import com.mockobjects.*; import org.apache.commons.httpclient.HttpState; import alt.org.apache.commons.httpclient.HttpStateFactory; public class MockHttpStateFactory extends MockObject implements HttpStateFactory{ private HttpState httpState; public void setupCreateHttpState(HttpState httpState){ this.httpState = httpState; } public HttpState createHttpState(){ return httpState; } } mockobjects-0.09/src/extensions/com/mockobjects/apache/commons/httpclient/MockMethodHelper.java0000644000175000017500000000110107660455667034571 0ustar craftermcrafterm00000000000000package com.mockobjects.apache.commons.httpclient; import com.mockobjects.ReturnObjectBag; import com.mockobjects.MockObject; import org.apache.commons.httpclient.Header; /** * @version $Revision: 1.1 $ */ class MockMethodHelper extends MockObject{ private final ReturnObjectBag header = new ReturnObjectBag("response header"); public Header getResponseHeader(String key) { return (Header) header.getNextReturnObject(key); } public void addGetResponseHeader(String key, Header header) { this.header.putObjectToReturn(key, header); } } mockobjects-0.09/src/extensions/com/mockobjects/atg/0000755000175000017500000000000010117310266024214 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/atg/MockDynamoHttpServletRequest.java0000644000175000017500000000564307377036026032723 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import java.io.IOException; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import com.mockobjects.ExpectationSet; import com.mockobjects.MapEntry; import com.mockobjects.util.Verifier; public class MockDynamoHttpServletRequest extends DynamoHttpServletRequest { private ExpectationSet myServicedLocalParameter = new ExpectationSet("Serviced Local Params"); private ExpectationSet myOutputParameters = new ExpectationSet("Output Parameters"); private HashMap myInputParameters = new HashMap(); private HashMap myNamedComponents = new HashMap(); private HashMap myCookieParameters = new HashMap(); private HashMap myHeaders = new HashMap(); public MockDynamoHttpServletRequest() { } public void setParameter(String key, Object value) { myOutputParameters.addActual(new MapEntry(key, value)); } public Object getObjectParameter(ParameterName name) { return getObjectParameter(name.getName()); } public Object getObjectParameter(String name) { return myInputParameters.get(name); } public Object getLocalParameter(String parameterName) { return myInputParameters.get(parameterName); } public String getParameter(String param1) { return (String) myInputParameters.get(param1); } public boolean serviceLocalParameter(String name, ServletRequest request, ServletResponse response) throws ServletException, IOException { myServicedLocalParameter.addActual(name); return true; } public void setupExpectedOutputParameter(String name, Object value) { myOutputParameters.addExpected(new MapEntry(name, value)); } public void setupExpectedServicedLocalParameter(String name) { myServicedLocalParameter.addExpected(name); } public void setupInputParameter(String param1, Object param2) { myInputParameters.put(param1, param2); } public String getCookieParameter(String parameter) { return (String) myCookieParameters.get(parameter); } public void setupCookieParameter(String key, String parameter) { myCookieParameters.put(key, parameter); } public void setupHeaders(String key, String header) { myHeaders.put(key, header); } public void setupNamedParameter(String name, Object parameter) { myNamedComponents.put(name, parameter); } public String encodeURL(String str) { return str + ";sessionId=123"; } public String getHeader(String param1) { return (String) myHeaders.get(param1); } public Object resolveName(String componentName, boolean param2) { return myNamedComponents.get(componentName); } public void verify() { Verifier.verifyObject(this); } public String toString() { return "MockDynamoServletRequest"; } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockDynamoHttpServletResponse.java0000644000175000017500000000301507331064401033044 0ustar craftermcrafterm00000000000000// Decompiled by Jad v1.5.7. Copyright 1997-99 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html // Decompiler options: packimports(3) // Source File Name: MockDynamoHttpServletResponse.java package com.mockobjects.atg; import javax.servlet.http.HttpServletResponse; import atg.servlet.*; import com.mockobjects.*; import java.io.IOException;public class MockDynamoHttpServletResponse extends DynamoHttpServletResponse implements Verifiable { private ExpectationList myLocalRedirect = new ExpectationList("Local redirect"); private boolean myShouldThrowExceptionOnRedirect = false; public MockDynamoHttpServletResponse() { } public MockDynamoHttpServletResponse(HttpServletResponse arg1) { super(arg1); } public void sendLocalRedirect(String url, DynamoHttpServletRequest request) throws IOException { myLocalRedirect.addActual(url); myLocalRedirect.addActual(request); if (myShouldThrowExceptionOnRedirect) { throw new IOException("Mock exception"); } } public void setExpectedLocalRedirect(String url, DynamoHttpServletRequest request) { myLocalRedirect.addExpected(url); myLocalRedirect.addExpected(request); } public void setupThrowExceptionOnRedirect() { myShouldThrowExceptionOnRedirect = true; } public String toString() { return "MockDynamoServletResponse"; } public void verify() { myLocalRedirect.verify(); } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockProfile.java0000644000175000017500000000117607331064401027277 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import java.util.Hashtable;public class MockProfile extends atg.userprofiling.Profile { private Hashtable propertyValues = new Hashtable(); /** * MockProfile constructor comment. */ public MockProfile() { super(); } /** * Insert the method's description here. * Creation date: (09/04/2001 13:06:52) */ public java.lang.Object getPropertyValue(java.lang.String key) { return this.propertyValues.get(key); } public void setupPropertyValue(String key, Object propertyValue) { this.propertyValues.put(key, propertyValue); } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockQuery.java0000644000175000017500000000100707331064401026775 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*;/** * Creation date: (06/04/2001 09:58:14) * @author: */ public class MockQuery implements Query { /** * MockQuery constructor comment. */ public MockQuery() { super(); } /** * getQueryOperation method comment. */ public String getQueryOperation() { return null; } /** * getQueryRepresentation method comment. */ public String getQueryRepresentation() { return null; } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockQueryBuilder.java0000644000175000017500000001101307331064401030302 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*;/** * Creation date: (06/04/2001 09:57:34) * @author: */ public class MockQueryBuilder implements QueryBuilder { /** * MockQueryBuilder constructor comment. */ public MockQueryBuilder() { super(); } /** * createAndQuery method comment. */ public Query createAndQuery(atg.repository.Query[] arg1) throws RepositoryException { return null; } /** * createComparisonQuery method comment. */ public Query createComparisonQuery(QueryExpression arg1, QueryExpression arg2, int arg3) throws RepositoryException { return null; } /** * createConstantQueryExpression method comment. */ public QueryExpression createConstantQueryExpression(Object arg1) throws RepositoryException { return null; } /** * createCountQueryExpression method comment. */ public QueryExpression createCountQueryExpression(QueryExpression arg1) throws RepositoryException { return null; } /** * createElementAtQueryExpression method comment. */ public QueryExpression createElementAtQueryExpression(QueryExpression arg1, QueryExpression arg2) throws RepositoryException { return null; } /** * createIdMatchingQuery method comment. */ public Query createIdMatchingQuery(java.lang.String[] arg1) throws RepositoryException { return null; } /** * createIncludesAllQuery method comment. */ public Query createIncludesAllQuery(QueryExpression arg1, QueryExpression arg2) throws RepositoryException { return null; } /** * createIncludesAnyQuery method comment. */ public Query createIncludesAnyQuery(QueryExpression arg1, QueryExpression arg2) throws RepositoryException { return null; } /** * createIncludesItemQuery method comment. */ public Query createIncludesItemQuery(QueryExpression arg1, Query arg2) throws RepositoryException { return null; } /** * createIncludesQuery method comment. */ public Query createIncludesQuery(QueryExpression arg1, QueryExpression arg2) throws RepositoryException { return null; } /** * createIndexOfQueryExpression method comment. */ public QueryExpression createIndexOfQueryExpression(QueryExpression arg1, QueryExpression arg2) throws RepositoryException { return null; } /** * createIsNullQuery method comment. */ public Query createIsNullQuery(QueryExpression arg1) throws RepositoryException { return null; } /** * createNotQuery method comment. */ public Query createNotQuery(Query arg1) throws RepositoryException { return null; } /** * createOrQuery method comment. */ public Query createOrQuery(atg.repository.Query[] arg1) throws RepositoryException { return null; } /** * createPatternMatchQuery method comment. */ public Query createPatternMatchQuery(QueryExpression arg1, QueryExpression arg2, int arg3) throws RepositoryException { return null; } /** * createPatternMatchQuery method comment. */ public Query createPatternMatchQuery(QueryExpression arg1, QueryExpression arg2, int arg3, boolean arg4) throws RepositoryException { return null; } /** * createPropertyQueryExpression method comment. */ public QueryExpression createPropertyQueryExpression(QueryExpression arg1, String arg2) throws RepositoryException { return null; } /** * createPropertyQueryExpression method comment. */ public QueryExpression createPropertyQueryExpression(String arg1) throws RepositoryException { return null; } /** * createTextSearchQuery method comment. */ public Query createTextSearchQuery(QueryExpression arg1, QueryExpression arg2, QueryExpression arg3) throws RepositoryException { return null; } /** * createTextSearchQuery method comment. */ public Query createTextSearchQuery(QueryExpression arg1, QueryExpression arg2, QueryExpression arg3, QueryExpression arg4) throws RepositoryException { return null; } /** * createUnconstrainedQuery method comment. */ public Query createUnconstrainedQuery() throws RepositoryException { return null; } /** * getRepositoryView method comment. */ public RepositoryView getRepositoryView() { return null; } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockQueryExpression.java0000644000175000017500000000105707331064401031062 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*;/** * Creation date: (06/04/2001 09:58:43) * @author: */ public class MockQueryExpression implements QueryExpression { /** * MockQueryExpression constructor comment. */ public MockQueryExpression() { super(); } /** * getQueryOperation method comment. */ public String getQueryOperation() { return null; } /** * getQueryRepresentation method comment. */ public String getQueryRepresentation() { return null; } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockRepository.java0000644000175000017500000000465707361361537030102 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*; import com.mockobjects.ExpectationMap; import com.mockobjects.Verifiable; import com.mockobjects.MockObject; import com.mockobjects.ExpectationValue; public class MockRepository extends MockObject implements Repository, Verifiable { RepositoryException exception; RepositoryItemDescriptor itemDescriptor; ExpectationMap items = new ExpectationMap("MockRepository items"); public MockRepository() { super(); } public String getDefaultViewName() { return null; } public RepositoryItem getItem(String id) throws RepositoryException { RepositoryItem result = (RepositoryItem)items.get(id); if (null != exception) { throw exception; } return result; } public RepositoryItem getItem(String arg1, String arg2) throws RepositoryException { if (exception != null) { throw exception; } return null; } public RepositoryItemDescriptor getItemDescriptor(String arg1) throws RepositoryException { if (exception != null) { throw exception; } return this.itemDescriptor; } public java.lang.String[] getItemDescriptorNames() { return null; } public atg.repository.RepositoryItem[] getItems(java.lang.String[] arg1) throws RepositoryException { if (exception != null) { throw exception; } return null; } public atg.repository.RepositoryItem[] getItems(java.lang.String[] arg1, String arg2) throws RepositoryException { if (exception != null) { throw exception; } return null; } public String getRepositoryName() { return null; } public RepositoryView getView(String arg1) throws RepositoryException { if (exception != null) { throw exception; } return null; } public java.lang.String[] getViewNames() { return null; } public void setupException(RepositoryException exception) { this.exception = exception; } public void setupRepositoryItemDescriptor(RepositoryItemDescriptor itemDescriptor) { this.itemDescriptor = itemDescriptor; } public void addExpectedGetItem(String id, RepositoryItem item) { items.addExpected(id, item); } public void setExpectNoItems() { items.setExpectNothing(); } } mockobjects-0.09/src/extensions/com/mockobjects/atg/MockRepositoryItem.java0000644000175000017500000000253707331064401030677 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*; import java.util.*;/** * Creation date: (06/04/2001 08:48:16) * @author: */ public class MockRepositoryItem implements RepositoryItem { private HashMap propertyValues = new HashMap(); /** * MockRepositoryItem constructor comment. */ public MockRepositoryItem() { super(); } /** * getItemDescriptor method comment. */ public RepositoryItemDescriptor getItemDescriptor() throws RepositoryException { return null; } /** * getItemDisplayName method comment. */ public String getItemDisplayName() { return null; } /** * getPropertyValue method comment. */ public Object getPropertyValue(String name) { return this.propertyValues.get(name); } /** * getRepository method comment. */ public Repository getRepository() { return null; } /** * getRepositoryId method comment. */ public String getRepositoryId() { return null; } /** * isTransient method comment. */ public boolean isTransient() { return false; } /** * getPropertyValue method comment. */ public void setupPropertyValue(String key, Object propertyValue) { this.propertyValues.put(key, propertyValue); } }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockRepositoryItemDescriptor.java0000644000175000017500000000465507331064401032741 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*;/** * Creation date: (06/04/2001 09:56:36) * @author: */ public class MockRepositoryItemDescriptor implements RepositoryItemDescriptor { private MockRepositoryView repositoryView; /** * MockRepositoryItemDescriptor constructor comment. */ public MockRepositoryItemDescriptor() { super(); } /** * addPropertyDescriptor method comment. */ public void addPropertyDescriptor(RepositoryPropertyDescriptor arg1) throws RepositoryException {} /** * areInstances method comment. */ public boolean areInstances(atg.beans.DynamicBeanInfo arg1) { return false; } /** * getBeanDescriptor method comment. */ public atg.beans.DynamicBeanDescriptor getBeanDescriptor() { return null; } /** * getItemDescriptorName method comment. */ public String getItemDescriptorName() { return null; } /** * getPropertyDescriptor method comment. */ public atg.beans.DynamicPropertyDescriptor getPropertyDescriptor(String arg1) { return null; } /** * getPropertyDescriptors method comment. */ public atg.beans.DynamicPropertyDescriptor[] getPropertyDescriptors() { return null; } /** * getPropertyNames method comment. */ public java.lang.String[] getPropertyNames() { return null; } /** * getRepository method comment. */ public Repository getRepository() { return null; } /** * getRepositoryView method comment. */ public RepositoryView getRepositoryView() { return this.repositoryView; } /** * hasProperty method comment. */ public boolean hasProperty(String arg1) { return false; } /** * isInstance method comment. */ public boolean isInstance(Object arg1) { return false; } /** * removePropertyDescriptor method comment. */ public void removePropertyDescriptor(String arg1) throws RepositoryException {} /** * getRepositoryView method comment. */ public void setupRepositoryView(MockRepositoryView repositoryView) { this.repositoryView = repositoryView; } /** * updatePropertyDescriptor method comment. */ public void updatePropertyDescriptor(RepositoryPropertyDescriptor arg1) throws RepositoryException {} }mockobjects-0.09/src/extensions/com/mockobjects/atg/MockRepositoryView.java0000644000175000017500000000535607331064401030715 0ustar craftermcrafterm00000000000000package com.mockobjects.atg; import atg.repository.*;/** * Creation date: (06/04/2001 09:59:28) * @author: */ public class MockRepositoryView implements RepositoryView { private MockQueryBuilder queryBuilder; private MockRepositoryItem[] repositoryItems; /** * MockRepositoryView constructor comment. */ public MockRepositoryView() { super(); } /** * executeCountQuery method comment. */ public int executeCountQuery(Query arg1) throws RepositoryException { return 0; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1) throws RepositoryException { return this.repositoryItems; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1, int arg2) throws RepositoryException { return this.repositoryItems; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1, int arg2, int arg3) throws RepositoryException { return this.repositoryItems; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1, int arg2, int arg3, SortDirectives arg4) throws RepositoryException { return this.repositoryItems; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1, int arg2, SortDirectives arg3) throws RepositoryException { return this.repositoryItems; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1, QueryOptions arg2) throws RepositoryException { return this.repositoryItems; } /** * executeQuery method comment. */ public atg.repository.RepositoryItem[] executeQuery(Query arg1, SortDirectives arg2) throws RepositoryException { return this.repositoryItems; } /** * getItemDescriptor method comment. */ public RepositoryItemDescriptor getItemDescriptor() throws RepositoryException { return null; } /** * getQueryBuilder method comment. */ public QueryBuilder getQueryBuilder() { return this.queryBuilder; } /** * getViewName method comment. */ public String getViewName() { return null; } /** * getQueryBuilder method comment. */ public void setupQueryBuilder(MockQueryBuilder queryBuilder) { this.queryBuilder = queryBuilder; } /** * getQueryBuilder method comment. */ public void setupRepositoryItems(MockRepositoryItem[] items) { this.repositoryItems = items; } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/0000755000175000017500000000000010117310266024533 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/0000755000175000017500000000000010117310266025332 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/ArgumentArray.java0000644000175000017500000000716607331064401030771 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql;class ArgumentArray { ArgumentArray(Object [] p_args) { m_args = p_args; } public boolean equals(Object p_other) { if (! (p_other instanceof ArgumentArray) ) { return false; } return arraysEqual(m_args, ((ArgumentArray)p_other).m_args); } public int hashCode() { return m_args.length; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("["); for (int i = 0; i < m_args.length; ++i) { if (i > 0) { sb.append(','); } sb.append(m_args[i]); } sb.append(']'); return sb.toString(); } private static boolean objectsEqual(final Object p_first, final Object p_second) { if (p_first == null && p_second == null) { return true; } else if ( p_first == Wildcard.WILDCARD || p_second == Wildcard.WILDCARD) { return true; } else if (p_first == null || p_second == null) { return false; } else { return p_first.equals(p_second); } } /** * compares two arrays; elements of an array match if both are * null, one is a wildcard, or they equal *@param p_first the first array *@param p_second the second array *@return boolean true if all elements match, false otherwise */ private static boolean arraysEqual(final Object[] p_first, final Object[] p_second) { //if the number of elements differs, the arrays don't match by //definition. if ( p_first.length != p_second.length ) { return false; } for (int i = 0; i < p_first.length; i++) { if ( ! objectsEqual(p_first[i],p_second[i]) ) { return false; } } return true; } private final Object [] m_args; }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/CallableStatement.java0000644000175000017500000001531307331064401031565 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.math.BigDecimal; import java.sql.SQLException; import java.util.Calendar; import java.util.Map; import java.util.Iterator; import java.util.SortedMap; import java.util.TreeMap;public class CallableStatement extends PreparedStatement implements java.sql.CallableStatement { CallableStatement(Connection p_connection, String p_sql) { super(p_connection,p_sql); } private Object [] m_results; private SortedMap m_outs = new TreeMap(); public boolean execute() throws SQLException { m_results = connection.getRegisteredCall(sql,getArguments()); return m_results.length > 0; } public void registerOutParameter(int parameterIndex, int sqlType) { m_outs.put(new Integer(parameterIndex), new Integer(sqlType)); setArg(parameterIndex,Connection.WILDCARD); } private Object getOutParameter(int i) throws SQLException { if (m_results == null) { throw new SQLException("Attempt to get OUT param before execute"); } if (m_results.length != m_outs.size()) { throw new SQLException( "# of result values supplied (" + m_results.length + ") not equal to # of OUT parameters (" + m_outs.size() + ")") ; } if (! m_outs.containsKey(new Integer(i))) { throw new SQLException("No OUT param registered at position " + i); } Iterator keys = m_outs.keySet().iterator(); int k = 0; while (keys.hasNext()) { int j = ((Integer) keys.next()).intValue(); if (j == i) { return m_results[k]; } k++; } throw new SQLException("No OUT parameter registered at position " + i); } public int getInt(int parameterIndex) throws SQLException { return ((Integer) getOutParameter(parameterIndex)).intValue(); } public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { return (BigDecimal) getOutParameter(parameterIndex); } public String getString(int parameterIndex) throws SQLException { Object o = getOutParameter(parameterIndex); if ( o == null ) { return null; } else { return o.toString(); } } // be afraid, be very afraid, for below this line // all methods throw the dreaded NotImplementedException ... public java.sql.Array getArray(int i) { throw new NotImplementedException(); } /** * @deprecated */ public BigDecimal getBigDecimal(int parameterIndex, int scale) { throw new NotImplementedException(); } public java.sql.Blob getBlob(int i) { throw new NotImplementedException(); } public boolean getBoolean(int parameterIndex) { throw new NotImplementedException(); } public byte getByte(int parameterIndex) { throw new NotImplementedException(); } public byte[] getBytes(int parameterIndex) { throw new NotImplementedException(); } public java.sql.Clob getClob(int i) { throw new NotImplementedException(); } public java.sql.Date getDate(int parameterIndex) { throw new NotImplementedException(); } public java.sql.Date getDate(int parameterIndex, Calendar cal) { throw new NotImplementedException(); } public double getDouble(int parameterIndex) { throw new NotImplementedException(); } public float getFloat(int parameterIndex) { throw new NotImplementedException(); } public long getLong(int parameterIndex) { throw new NotImplementedException(); } public Object getObject(int parameterIndex) { throw new NotImplementedException(); } public Object getObject(int i, Map map) { throw new NotImplementedException(); } public java.sql.Ref getRef(int i) { throw new NotImplementedException(); } public short getShort(int parameterIndex) { throw new NotImplementedException(); } public java.sql.Time getTime(int parameterIndex) { throw new NotImplementedException(); } public java.sql.Time getTime(int parameterIndex, Calendar cal) { throw new NotImplementedException(); } public java.sql.Timestamp getTimestamp(int parameterIndex) { throw new NotImplementedException(); } public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal) { throw new NotImplementedException(); } public void registerOutParameter(int parameterIndex, int sqlType, int scale) { throw new NotImplementedException(); } public void registerOutParameter(int paramIndex, int sqlType, String typeName) { throw new NotImplementedException(); } public boolean wasNull() { throw new NotImplementedException(); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/Connection.java0000644000175000017500000001714307331064401030303 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.sql.SQLException; import java.util.Map;public class Connection implements java.sql.Connection { Connection() { } public static final Object WILDCARD = Wildcard.WILDCARD; java.sql.ResultSet getRegisteredResult(String p_sql, Object [] p_args) throws SQLException { java.sql.ResultSet rs = (java.sql.ResultSet) m_resultMap.get(p_sql, p_args); rs.first(); return rs; } int getRegisteredUpdate(String p_sql, Object [] p_args) throws SQLException { Integer r = (Integer) m_updateMap.get(p_sql, p_args); return r.intValue(); } Object [] getRegisteredCall(String p_sql, Object [] p_args) throws SQLException { Object [] rv = (Object [] ) m_callMap.get(p_sql, p_args); return rv; } public String getRegistryContents() { return m_resultMap + "\n" + m_callMap + "\n" + m_updateMap; } public int getRegisteredResultCount() { return m_resultMap.size(); } public int getRegisteredCallCount() { return m_callMap.size(); } public int getRegisteredUpdateCount() { return m_updateMap.size(); } public int getRegisteredCount() { return ( getRegisteredResultCount() + getRegisteredCallCount() + getRegisteredUpdateCount() ); } public void registerResult(String p_sql, Object [] p_args, java.sql.ResultSet p_resultSet) { if (p_resultSet == null) { throw new IllegalArgumentException("ResultSet can't be null"); } if (p_args == null) { throw new IllegalArgumentException("Argument array can't be null"); } m_resultMap.put(p_sql, p_args, p_resultSet); } public void registerCall(String p_sql, Object [] p_args, Object [] p_output) { if (p_args == null) { throw new IllegalArgumentException("Argument array can't be null"); } if (p_output == null) { throw new IllegalArgumentException("Output array can't be null"); } m_callMap.put(p_sql,p_args, p_output); } public void registerUpdate(String p_sql, Object [] p_args, int p_result) { if (p_args == null) { throw new IllegalArgumentException("Argument array can't be null"); } m_updateMap.put(p_sql, p_args,new Integer(p_result)); } public void close() throws SQLException { m_closed = true; } public boolean isClosed() { return m_closed; } private boolean m_closed = false; public java.sql.CallableStatement prepareCall(String p_sql) throws SQLException { if ( isClosed() ) { throw new SQLException("Attempt to use a closed connection"); } return new CallableStatement(this,p_sql); } public java.sql.PreparedStatement prepareStatement(String p_sql) throws SQLException { if ( isClosed() ) { throw new SQLException("Attempt to use a closed connection"); } return new PreparedStatement(this,p_sql); } private ConnectionMap m_resultMap = new ConnectionMap("result set"); private ConnectionMap m_callMap = new ConnectionMap("call"); private ConnectionMap m_updateMap = new ConnectionMap("update"); // be afraid, be very afraid, for below this line // all methods throw the dreaded NotImplementedException ... public void clearWarnings() { throw new NotImplementedException(); } public void commit() { throw new NotImplementedException(); } public java.sql.Statement createStatement() { throw new NotImplementedException(); } public java.sql.Statement createStatement(int p_resultSetType, int p_resultSetConcurrency) { throw new NotImplementedException(); } public boolean getAutoCommit() { throw new NotImplementedException(); } public String getCatalog() { throw new NotImplementedException(); } public java.sql.DatabaseMetaData getMetaData() { throw new NotImplementedException(); } public int getTransactionIsolation() { throw new NotImplementedException(); } public Map getTypeMap() { throw new NotImplementedException(); } public java.sql.SQLWarning getWarnings() { throw new NotImplementedException(); } public boolean isReadOnly() { throw new NotImplementedException(); } public String nativeSQL(String p_sql) { throw new NotImplementedException(); } public java.sql.CallableStatement prepareCall(String p_sql, int rsType, int rsConcurrency) { throw new NotImplementedException(); } public java.sql.PreparedStatement prepareStatement(String p_sql, int rsType, int rsConcurrency) { throw new NotImplementedException(); } public void rollback() { throw new NotImplementedException(); } public void setAutoCommit(boolean p_autoCommit) { throw new NotImplementedException(); } public void setCatalog(String p_catalog) { throw new NotImplementedException(); } public void setReadOnly(boolean p_readOnly) { throw new NotImplementedException(); } public void setTransactionIsolation(int p_level) { throw new NotImplementedException(); } public void setTypeMap(Map p_map) { throw new NotImplementedException(); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/ConnectionMap.java0000644000175000017500000001056007331064401030735 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.sql.SQLException; import java.util.Map; import java.util.Iterator; import java.util.HashMap;class ConnectionMap { ConnectionMap(String p_type) { m_type = p_type; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(m_type); sb.append(NEWLINE); for (Iterator i = m_map.keySet().iterator(); i.hasNext(); ) { Object sql = i.next(); Map map = (Map) m_map.get(sql); sb.append(sql); sb.append(NEWLINE); for (Iterator j = map.keySet().iterator(); j.hasNext(); ) { Object args = j.next(); sb.append(args); sb.append(NEWLINE); } sb.append(NEWLINE); } return sb.toString(); } public int size() { int result = 0; for (Iterator i = m_map.values().iterator(); i.hasNext(); ) { Map m = (Map) i.next(); result += m.size(); } return result; } public void put(String p_sql, Object [] p_args, Object p_obj) { Map map = (Map) m_map.get(p_sql); if (map == null) { map = new HashMap(); m_map.put(p_sql,map); } map.put(new ArgumentArray(p_args),p_obj); } public Object get(String p_sql, Object [] p_args) throws SQLException { Map map = (Map) m_map.get(p_sql); if (map == null) { throw new SQLException("No " + m_type + " registered for " + p_sql); } else { ArgumentArray args = new ArgumentArray(p_args); Object result = map.get(args); if (result == null) { throw new SQLException("No " + m_type + " registered for " + p_sql + " with args "+ args + ". Possible argument matches are " + get(p_sql)); } map.remove(args); if (map.size() == 0) { m_map.remove(p_sql); } return result; } } /** * * @return array of arrays, really */ private ArgumentArray get(String p_sql) { Map map = (Map) m_map.get(p_sql); if (map == null) { return new ArgumentArray(new Object [0]); } return new ArgumentArray(map.keySet().toArray()); } private final Map m_map = new HashMap(); private final String m_type; private static final String NEWLINE = System.getProperty("line.separator"); }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/Driver.java0000644000175000017500000000523707331064401027440 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.util.Properties;public class Driver implements java.sql.Driver { public boolean acceptsURL(String p_url) { if (p_url.startsWith("jdbc:")) { return p_url.substring(6).startsWith("unittest:"); } else { return false; } } public java.sql.Connection connect(String p_url, Properties p_props) { return createConnection(); } public int getMajorVersion() { return 1; } public int getMinorVersion() { return 0; } public java.sql.DriverPropertyInfo [] getPropertyInfo(String p_url, Properties p_props) { return new java.sql.DriverPropertyInfo[0]; } public boolean jdbcCompliant() { return false; } /* * Convenience method for creating connections, since creating a * connection requires no properties. */ public static Connection createConnection() { return new Connection(); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/NotImplementedException.java0000644000175000017500000000321007331064401032775 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql;public class NotImplementedException extends RuntimeException { }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/PreparedStatement.java0000644000175000017500000001657507504121230031637 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.SQLException; import java.util.Calendar; import java.util.Vector; public class PreparedStatement extends Statement implements java.sql.PreparedStatement { protected final Vector m_args = new Vector(); protected void setArg(int p_pos, Object p_arg) { p_pos--; if(m_args.size() <= p_pos) { int size = m_args.size(); m_args.setSize(p_pos + 1); for(int i = size; i < m_args.size(); ++i) { m_args.set(i, Connection.WILDCARD); } } m_args.set(p_pos, p_arg); } protected final Object[] getArguments() { m_args.trimToSize(); return m_args.toArray(); } PreparedStatement(Connection p_connection, String p_sql) { super(p_connection, p_sql); } public void addBatch() { throw new NotImplementedException(); } public void clearParameters() { throw new NotImplementedException(); } public boolean execute() throws SQLException { m_returnValue = -1; m_resultSet = null; try { m_returnValue = executeUpdate(); return false; } catch(SQLException e) { m_resultSet = executeQuery(); return true; } } public java.sql.ResultSet getResultSet() { return m_resultSet; } public int getUpdateCount() { return m_returnValue; } public java.sql.ResultSet executeQuery() throws SQLException { return connection.getRegisteredResult(sql, getArguments()); } public int executeUpdate() throws SQLException { return connection.getRegisteredUpdate(sql, getArguments()); } public void setInt(int parameterIndex, int x) { setArg(parameterIndex, new Integer(x)); } public void setString(int parameterIndex, String x) { setArg(parameterIndex, x); } public void setBigDecimal(int parameterIndex, BigDecimal x) { setArg(parameterIndex, x); } public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int c = 0; while(((c = x.read()) != -1)) { baos.write(c); } setArg(parameterIndex, baos.toByteArray()); } catch(IOException e) { throw new SQLException("IOException reading stream"); } } public void setNull(int parameterIndex, int sqlType) { setArg(parameterIndex, null); } private int m_returnValue; private java.sql.ResultSet m_resultSet; // be afraid, be very afraid, for below this line // all methods throw the dreaded NotImplementedException ... public java.sql.ResultSetMetaData getMetaData() { throw new NotImplementedException(); } public void setArray(int i, java.sql.Array x) { throw new NotImplementedException(); } public void setAsciiStream(int parameterIndex, InputStream x, int length) { throw new NotImplementedException(); } public void setBlob(int i, java.sql.Blob x) { throw new NotImplementedException(); } public void setBoolean(int parameterIndex, boolean x) { throw new NotImplementedException(); } public void setByte(int parameterIndex, byte x) { throw new NotImplementedException(); } public void setBytes(int parameterIndex, byte[] x) { throw new NotImplementedException(); } public void setCharacterStream(int parameterIndex, Reader reader, int length) { throw new NotImplementedException(); } public void setClob(int i, java.sql.Clob x) { throw new NotImplementedException(); } public void setDate(int parameterIndex, java.sql.Date x) { throw new NotImplementedException(); } public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) { throw new NotImplementedException(); } public void setDouble(int parameterIndex, double x) { throw new NotImplementedException(); } public void setFloat(int parameterIndex, float x) { throw new NotImplementedException(); } public void setLong(int parameterIndex, long x) { throw new NotImplementedException(); } public void setNull(int paramIndex, int sqlType, String typeName) { throw new NotImplementedException(); } public void setObject(int parameterIndex, Object x) { throw new NotImplementedException(); } public void setObject(int parameterIndex, Object x, int targetSqlType) { throw new NotImplementedException(); } public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) { throw new NotImplementedException(); } public void setRef(int i, java.sql.Ref x) { throw new NotImplementedException(); } public void setShort(int parameterIndex, short x) { throw new NotImplementedException(); } public void setTime(int parameterIndex, java.sql.Time x) { throw new NotImplementedException(); } public void setTime(int parameterIndex, java.sql.Time x, Calendar cal) { throw new NotImplementedException(); } public void setTimestamp(int parameterIndex, java.sql.Timestamp x) { throw new NotImplementedException(); } public void setTimestamp(int parameterIndex, java.sql.Timestamp x, Calendar cal) { throw new NotImplementedException(); } /** * @deprecated */ public void setUnicodeStream(int parameterIndex, InputStream x, int length) { throw new NotImplementedException(); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/ReflectiveResultSetRowGenerator.java0000644000175000017500000000717607331064401034513 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.sql.SQLException; import java.util.Vector; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException;public class ReflectiveResultSetRowGenerator implements ResultSetRowGenerator { public ReflectiveResultSetRowGenerator(String [] p_propertyNames) { m_propertyNames = p_propertyNames; } private final String [] m_propertyNames; public Object [] createRow(Object p_sourceObj) throws SQLException { Vector result = new Vector(); for (int i = 0; i < m_propertyNames.length; ++i) { result.add(getColumnData(p_sourceObj, m_propertyNames[i])); } return result.toArray(); } private Object getColumnData(Object p_obj, String p_colName) throws SQLException { try { Method m = p_obj.getClass().getMethod("get" + p_colName, new Class[0]); if (m.getReturnType().equals(Void.TYPE)) { throw new SQLException( "Column-mapped method " + m + " returns void while looking for " + p_colName + " on " + p_obj.getClass() ); } return m.invoke(p_obj,new Object[0]); } catch (NoSuchMethodException e) { choke(e,p_obj,p_colName); } catch (InvocationTargetException e) { choke(e,p_obj,p_colName); } catch (IllegalAccessException e) { choke(e,p_obj,p_colName); } // never get here, but compiler needs it return null; } private void choke(Throwable p_throwable, Object p_obj, String p_colName) throws SQLException { throw new SQLException("while looking for " + p_colName + " on " + p_obj.getClass() + " got " + p_throwable.toString()); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/ResultSet.java0000644000175000017500000006172307331064401030141 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.sql.SQLException; import java.math.BigDecimal; import java.util.Calendar; import java.util.Map; import java.util.HashMap;public class ResultSet implements java.sql.ResultSet { public static final ResultSet EMPTY_SET = new ResultSet(); private ResultSet() { this (null, new Object[0], null); } private int m_current; private boolean m_wasNull = false; public ResultSet(Object [] p_data, String [] p_names) { this(p_data, p_names, p_names); } /** * Factor these validations out since you can't insert assertions * before a call to super() or this(). */ private static Object [] validateConstructorArgs(Object [] p_data, String [] p_columnNames, String [] p_propNames) { if (p_data == null) { throw new IllegalArgumentException("Object array can't be null"); } if (p_columnNames == null) { throw new IllegalArgumentException("Column names can't be null"); } if (p_propNames == null) { throw new IllegalArgumentException("Property names can't be null"); } if (p_columnNames.length != p_propNames.length) { throw new IllegalArgumentException("Number of column names (" + p_columnNames.length + ")" + " does not match " + " number of property names (" + p_propNames.length + ")"); } return p_data; } public ResultSet(Object [] p_data, String [] p_columnNames, String [] p_propNames) { this (new ReflectiveResultSetRowGenerator(p_propNames), validateConstructorArgs(p_data, p_columnNames, p_propNames), createMapFromStringArray(p_columnNames)); } private static Map createMapFromStringArray(String [] p_columnNames) { Map map = new HashMap(); for (int i = 0; i < p_columnNames.length; ++i) { map.put(p_columnNames[i],new Integer(i)); } return map; } public ResultSet(ResultSetRowGenerator p_generator, Object [] p_data, Map p_columnNameMap) { m_generator = p_generator; m_data = p_data; m_columnNameMap = p_columnNameMap; m_current = -1; } private final ResultSetRowGenerator m_generator; private final Object [] m_data; private final Map m_columnNameMap; private Object [] getCurrentRow() throws SQLException { Object [] result = m_generator.createRow(m_data[m_current]); // FIXME: // assert result != null // assert result.length == m_columnNameMap.size() return result; } private Object getColumnData(int p_columnNum) throws SQLException { Object [] row = getCurrentRow(); if (p_columnNum < 0 || p_columnNum >= row.length) { throw new SQLException("Illegal column number " + p_columnNum); } // FIXME: assert that p_columnNum is one of the values in // m_columnNameMap Object result = row[p_columnNum]; m_wasNull = (result == null); return result; } public int findColumn(String p_columnName) throws SQLException { Integer i = (Integer) m_columnNameMap.get(p_columnName); if (i != null) { return i.intValue(); } else { throw new SQLException("No such column " + p_columnName); } } public boolean next() throws SQLException { m_current++; return m_current < m_data.length; } public void close() throws SQLException { // noop } public boolean wasNull() throws SQLException { return m_wasNull; } public String getString(int columnIndex) throws SQLException { return (String) getColumnData(columnIndex); } public boolean getBoolean(int columnIndex) throws SQLException { return ((Boolean) getColumnData(columnIndex)).booleanValue(); } public byte getByte(int columnIndex) throws SQLException { return ((Byte) getColumnData(columnIndex)).byteValue(); } public short getShort(int columnIndex) throws SQLException { return ((Short) getColumnData(columnIndex)).shortValue(); } public int getInt(int columnIndex) throws SQLException { Integer i = (Integer) getColumnData(columnIndex); return i == null ? 0 : i.intValue(); } public long getLong(int columnIndex) throws SQLException { return ((Long) getColumnData(columnIndex)).longValue(); } public float getFloat(int columnIndex) throws SQLException { return ((Float) getColumnData(columnIndex)).floatValue(); } public double getDouble(int columnIndex) throws SQLException { return ((Double) getColumnData(columnIndex)).doubleValue(); } /** * @deprecated */ public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return (BigDecimal) getColumnData(columnIndex); } public byte[] getBytes(int columnIndex) throws SQLException { return (byte []) getColumnData(columnIndex); } public java.sql.Date getDate(int columnIndex) throws SQLException { // be forgiving about java.util vs java.sql Dates Object o = getColumnData(columnIndex); if (o == null) { return null; } else if (o instanceof java.sql.Date) { return (java.sql.Date) o; } else if (o instanceof java.util.Date) { return new java.sql.Date(((java.util.Date)o).getTime()); } else { throw new SQLException("Expected date type, got " + o.getClass()); } } public java.sql.Time getTime(int columnIndex) throws SQLException { return (java.sql.Time) getColumnData(columnIndex); } public java.sql.Timestamp getTimestamp(int columnIndex) throws SQLException { return (java.sql.Timestamp) getColumnData(columnIndex); } public java.io.InputStream getAsciiStream(int columnIndex) throws SQLException { return (java.io.InputStream) getColumnData(columnIndex); } /** * @deprecated */ public java.io.InputStream getUnicodeStream(int columnIndex) throws SQLException { return (java.io.InputStream) getColumnData(columnIndex); } public java.io.InputStream getBinaryStream(int columnIndex) throws SQLException { return (java.io.InputStream) getColumnData(columnIndex); } //====================================================================== // Methods for accessing results by column name //====================================================================== public String getString(String columnName) throws SQLException { return getString(findColumn(columnName)); } public boolean getBoolean(String columnName) throws SQLException { return getBoolean(findColumn(columnName)); } public byte getByte(String columnName) throws SQLException { return getByte(findColumn(columnName)); } public short getShort(String columnName) throws SQLException { return getShort(findColumn(columnName)); } public int getInt(String columnName) throws SQLException { return getInt(findColumn(columnName)); } public long getLong(String columnName) throws SQLException { return getLong(findColumn(columnName)); } public float getFloat(String columnName) throws SQLException { return getFloat(findColumn(columnName)); } public double getDouble(String columnName) throws SQLException { return getDouble(findColumn(columnName)); } /** * @deprecated */ public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { throw new NotImplementedException(); } public byte[] getBytes(String columnName) throws SQLException { return getBytes(findColumn(columnName)); } public java.sql.Date getDate(String columnName) throws SQLException { return getDate(findColumn(columnName)); } public java.sql.Time getTime(String columnName) throws SQLException { return getTime(findColumn(columnName)); } public java.sql.Timestamp getTimestamp(String columnName) throws SQLException { return getTimestamp(findColumn(columnName)); } public java.io.InputStream getAsciiStream(String columnName) throws SQLException { return getAsciiStream(findColumn(columnName)); } /** * @deprecated */ public java.io.InputStream getUnicodeStream(String columnName) throws SQLException { return getUnicodeStream(findColumn(columnName)); } public java.io.InputStream getBinaryStream(String columnName) throws SQLException { return getBinaryStream(findColumn(columnName)); } public BigDecimal getBigDecimal(String columnName) throws SQLException { return (BigDecimal) getColumnData(findColumn(columnName)); } public boolean first() throws SQLException { m_current = -1; return m_data.length > 0; } //===================================================================== // Advanced features: //===================================================================== public java.sql.SQLWarning getWarnings() throws SQLException { throw new NotImplementedException(); } public void clearWarnings() throws SQLException { throw new NotImplementedException(); } public String getCursorName() throws SQLException { throw new NotImplementedException(); } public java.sql.ResultSetMetaData getMetaData() throws SQLException { throw new NotImplementedException(); } public Object getObject(int columnIndex) throws SQLException { throw new NotImplementedException(); } public Object getObject(String columnName) throws SQLException { throw new NotImplementedException(); } //---------------------------------------------------------------- //--------------------------JDBC 2.0----------------------------------- //--------------------------------------------------------------------- // Getter's and Setter's //--------------------------------------------------------------------- public java.io.Reader getCharacterStream(int columnIndex) throws SQLException { throw new NotImplementedException(); } public java.io.Reader getCharacterStream(String columnName) throws SQLException { throw new NotImplementedException(); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { throw new NotImplementedException(); } //--------------------------------------------------------------------- // Traversal/Positioning //--------------------------------------------------------------------- public boolean isBeforeFirst() throws SQLException { throw new NotImplementedException(); } public boolean isAfterLast() throws SQLException { throw new NotImplementedException(); } public boolean isFirst() throws SQLException { throw new NotImplementedException(); } public boolean isLast() throws SQLException { throw new NotImplementedException(); } public void beforeFirst() throws SQLException { throw new NotImplementedException(); } public void afterLast() throws SQLException { throw new NotImplementedException(); } public boolean last() throws SQLException { throw new NotImplementedException(); } public int getRow() throws SQLException { throw new NotImplementedException(); } public boolean absolute( int row ) throws SQLException { throw new NotImplementedException(); } public boolean relative( int rows ) throws SQLException { throw new NotImplementedException(); } public boolean previous() throws SQLException { throw new NotImplementedException(); } //--------------------------------------------------------------------- // Properties //--------------------------------------------------------------------- public void setFetchDirection(int direction) throws SQLException { throw new NotImplementedException(); } public int getFetchDirection() throws SQLException { return FETCH_FORWARD; } public void setFetchSize(int rows) throws SQLException { throw new NotImplementedException(); } public int getFetchSize() throws SQLException { throw new NotImplementedException(); } public int getType() throws SQLException { return TYPE_FORWARD_ONLY; } public int getConcurrency() throws SQLException { return CONCUR_READ_ONLY; } //--------------------------------------------------------------------- // Updates //--------------------------------------------------------------------- public boolean rowUpdated() throws SQLException { throw new NotImplementedException(); } public boolean rowInserted() throws SQLException { throw new NotImplementedException(); } public boolean rowDeleted() throws SQLException { throw new NotImplementedException(); } public void updateNull(int columnIndex) throws SQLException { throw new NotImplementedException(); } public void updateBoolean(int columnIndex, boolean x) throws SQLException { throw new NotImplementedException(); } public void updateByte(int columnIndex, byte x) throws SQLException { throw new NotImplementedException(); } public void updateShort(int columnIndex, short x) throws SQLException { throw new NotImplementedException(); } public void updateInt(int columnIndex, int x) throws SQLException { throw new NotImplementedException(); } public void updateLong(int columnIndex, long x) throws SQLException { throw new NotImplementedException(); } public void updateFloat(int columnIndex, float x) throws SQLException { throw new NotImplementedException(); } public void updateDouble(int columnIndex, double x) throws SQLException { throw new NotImplementedException(); } public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { throw new NotImplementedException(); } public void updateString(int columnIndex, String x) throws SQLException { throw new NotImplementedException(); } public void updateBytes(int columnIndex, byte x[]) throws SQLException { throw new NotImplementedException(); } public void updateDate(int columnIndex, java.sql.Date x) throws SQLException { throw new NotImplementedException(); } public void updateTime(int columnIndex, java.sql.Time x) throws SQLException { throw new NotImplementedException(); } public void updateTimestamp(int columnIndex, java.sql.Timestamp x) throws SQLException { throw new NotImplementedException(); } public void updateAsciiStream(int columnIndex, java.io.InputStream x, int length) throws SQLException { throw new NotImplementedException(); } public void updateBinaryStream(int columnIndex, java.io.InputStream x, int length) throws SQLException { throw new NotImplementedException(); } public void updateCharacterStream(int columnIndex, java.io.Reader x, int length) throws SQLException { throw new NotImplementedException(); } public void updateObject(int columnIndex, Object x, int scale) throws SQLException { throw new NotImplementedException(); } public void updateObject(int columnIndex, Object x) throws SQLException { throw new NotImplementedException(); } public void updateNull(String columnName) throws SQLException { throw new NotImplementedException(); } public void updateBoolean(String columnName, boolean x) throws SQLException { throw new NotImplementedException(); } public void updateByte(String columnName, byte x) throws SQLException { throw new NotImplementedException(); } public void updateShort(String columnName, short x) throws SQLException { throw new NotImplementedException(); } public void updateInt(String columnName, int x) throws SQLException { throw new NotImplementedException(); } public void updateLong(String columnName, long x) throws SQLException { throw new NotImplementedException(); } public void updateFloat(String columnName, float x) throws SQLException { throw new NotImplementedException(); } public void updateDouble(String columnName, double x) throws SQLException { throw new NotImplementedException(); } public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { throw new NotImplementedException(); } public void updateString(String columnName, String x) throws SQLException { throw new NotImplementedException(); } public void updateBytes(String columnName, byte x[]) throws SQLException { throw new NotImplementedException(); } public void updateDate(String columnName, java.sql.Date x) throws SQLException { throw new NotImplementedException(); } public void updateTime(String columnName, java.sql.Time x) throws SQLException { throw new NotImplementedException(); } public void updateTimestamp(String columnName, java.sql.Timestamp x) throws SQLException { throw new NotImplementedException(); } public void updateAsciiStream(String columnName, java.io.InputStream x, int length) throws SQLException { throw new NotImplementedException(); } public void updateBinaryStream(String columnName, java.io.InputStream x, int length) throws SQLException { throw new NotImplementedException(); } public void updateCharacterStream(String columnName, java.io.Reader reader, int length) throws SQLException { throw new NotImplementedException(); } public void updateObject(String columnName, Object x, int scale) throws SQLException { throw new NotImplementedException(); } public void updateObject(String columnName, Object x) throws SQLException { throw new NotImplementedException(); } public void insertRow() throws SQLException { throw new NotImplementedException(); } public void updateRow() throws SQLException { throw new NotImplementedException(); } public void deleteRow() throws SQLException { throw new NotImplementedException(); } public void refreshRow() throws SQLException { throw new NotImplementedException(); } public void cancelRowUpdates() throws SQLException { throw new NotImplementedException(); } public void moveToInsertRow() throws SQLException { throw new NotImplementedException(); } public void moveToCurrentRow() throws SQLException { throw new NotImplementedException(); } public java.sql.Statement getStatement() throws SQLException { throw new NotImplementedException(); } public Object getObject(int i, java.util.Map map) throws SQLException { throw new NotImplementedException(); } public java.sql.Ref getRef(int i) throws SQLException { throw new NotImplementedException(); } public java.sql.Blob getBlob(int i) throws SQLException { throw new NotImplementedException(); } public java.sql.Clob getClob(int i) throws SQLException { throw new NotImplementedException(); } public java.sql.Array getArray(int i) throws SQLException { throw new NotImplementedException(); } public Object getObject(String colName, java.util.Map map) throws SQLException { throw new NotImplementedException(); } public java.sql.Ref getRef(String colName) throws SQLException { throw new NotImplementedException(); } public java.sql.Blob getBlob(String colName) throws SQLException { throw new NotImplementedException(); } public java.sql.Clob getClob(String colName) throws SQLException { throw new NotImplementedException(); } public java.sql.Array getArray(String colName) throws SQLException { throw new NotImplementedException(); } public java.sql.Date getDate(int columnIndex, Calendar cal) throws SQLException { throw new NotImplementedException(); } public java.sql.Date getDate(String columnName, Calendar cal) throws SQLException { throw new NotImplementedException(); } public java.sql.Time getTime(int columnIndex, Calendar cal) throws SQLException { throw new NotImplementedException(); } public java.sql.Time getTime(String columnName, Calendar cal) throws SQLException { throw new NotImplementedException(); } public java.sql.Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { throw new NotImplementedException(); } public java.sql.Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { throw new NotImplementedException(); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/ResultSetRowGenerator.java0000644000175000017500000000330207331064401032465 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql;public interface ResultSetRowGenerator { Object [] createRow(Object p_sourceObj) throws java.sql.SQLException; }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/SingleObjectResultSetRowGenerator.java0000644000175000017500000000341207331064401034760 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql;public class SingleObjectResultSetRowGenerator implements ResultSetRowGenerator { public Object [] createRow(Object p_sourceObj) { return new Object [] { p_sourceObj }; } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/Statement.java0000644000175000017500000001110407331064401030137 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql; import java.sql.SQLException;public class Statement implements java.sql.Statement { protected final Connection connection; protected final String sql; Statement(Connection p_connection, String p_sql) { connection = p_connection; sql = p_sql; } public void close() { // noop } public java.sql.Connection getConnection() { return connection; } // be afraid, be very afraid, for below this line // all methods throw the dreaded NotImplementedException ... public void addBatch(String sql) { throw new NotImplementedException(); } public void cancel() { throw new NotImplementedException(); } public void clearBatch() { throw new NotImplementedException(); } public void clearWarnings() { throw new NotImplementedException(); } public boolean execute(String sql) throws SQLException { throw new NotImplementedException(); } public int[] executeBatch() { throw new NotImplementedException(); } public java.sql.ResultSet executeQuery(String sql) { throw new NotImplementedException(); } public int executeUpdate(String sql) { throw new NotImplementedException(); } public int getFetchDirection() { throw new NotImplementedException(); } public int getFetchSize() { throw new NotImplementedException(); } public int getMaxFieldSize() { throw new NotImplementedException(); } public int getMaxRows() { throw new NotImplementedException(); } public boolean getMoreResults() { throw new NotImplementedException(); } public int getQueryTimeout() { throw new NotImplementedException(); } public java.sql.ResultSet getResultSet() { throw new NotImplementedException(); } public int getResultSetConcurrency() { throw new NotImplementedException(); } public int getResultSetType() { throw new NotImplementedException(); } public int getUpdateCount() { throw new NotImplementedException(); } public java.sql.SQLWarning getWarnings() { throw new NotImplementedException(); } public void setCursorName(String name) { throw new NotImplementedException(); } public void setEscapeProcessing(boolean enable) { throw new NotImplementedException(); } public void setFetchDirection(int direction) { throw new NotImplementedException(); } public void setFetchSize(int rows) { throw new NotImplementedException(); } public void setMaxFieldSize(int max) { throw new NotImplementedException(); } public void setMaxRows(int max) { throw new NotImplementedException(); } public void setQueryTimeout(int seconds) { throw new NotImplementedException(); } }mockobjects-0.09/src/extensions/com/mockobjects/eziba/sql/Wildcard.java0000644000175000017500000000340307331064401027727 0ustar craftermcrafterm00000000000000/* * Copyright (C) 2001 eZiba.com, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. Neither the name of eZiba.com nor the * names of the contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * eZiba.com OR any CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mockobjects.eziba.sql;class Wildcard { public final static Object WILDCARD = new Wildcard(); private Wildcard() { } public String toString() { return "*SQLWILDCARD*"; } }mockobjects-0.09/src/extensions/com/mockobjects/vaj/0000755000175000017500000000000010117310266024221 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockBuilderFactory.java0000644000175000017500000000332107331064401030614 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import java.util.*; import com.ibm.ivj.util.builders.*; import com.ibm.ivj.util.base.Package; import com.mockobjects.*; public class MockBuilderFactory implements BuilderFactory { private ArrayList myTypeBuilders = new ArrayList(); private SourceVerifier mySourceVerifier; public MockBuilderFactory(SourceVerifier verifier) { super(); mySourceVerifier = verifier; } /** * createMethodBuilder method comment. */ public MethodBuilder createMethodBuilder(String builderName) throws java.lang.IllegalArgumentException { return new MockMethodBuilder(mySourceVerifier,builderName); } /** * createTypeBuilder method comment. */ public com.ibm.ivj.util.builders.TypeBuilder createTypeBuilder(com.ibm.ivj.util.base.Type aType) throws java.lang.IllegalArgumentException, com.ibm.ivj.util.base.IvjException { return createTypeBuilder(aType.getName(),null); } /** * createTypeBuilder method comment. */ public com.ibm.ivj.util.builders.TypeBuilder createTypeBuilder(String typeName, Package pkg) throws java.lang.IllegalArgumentException, com.ibm.ivj.util.base.IvjException { MockTypeBuilder builder = new MockTypeBuilder(mySourceVerifier,typeName); myTypeBuilders.add(builder); return builder; } /** * createUserCodeBlock method comment. */ public java.lang.String createUserCodeBlock(java.lang.String arg1, java.lang.String arg2) { return null; } /** * Mock method */ public void verify() { for(Iterator it = myTypeBuilders.iterator();it.hasNext();) { ((MockTypeBuilder)it.next()).verify(); } } } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockMethodBuilder.java0000644000175000017500000000463207331064401030433 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import junit.framework.*; import java.util.*; import com.mockobjects.*; public class MockMethodBuilder extends MockObject implements MethodBuilder { private SourceVerifier mySourceVerifier; private String myBuilderName; public MockMethodBuilder(SourceVerifier verfier, String builderName) { super(); mySourceVerifier = verfier; myBuilderName = builderName; } /** * addMethodBuilder method comment. */ public void addMethodBuilder(MethodBuilder arg1) {} /** * checkMethodExists method comment. */ public boolean checkMethodExists(MethodBuilder arg1) throws IvjException { return false; } /** * getBuilderName method comment. */ public String getBuilderName() { return myBuilderName; } /** * getExistingMethods method comment. */ public com.ibm.ivj.util.builders.MethodBuilder[] getExistingMethods() throws IvjException { return null; } /** * getExistingMethodSource method comment. */ public String getExistingMethodSource(MethodBuilder arg1) throws IvjException { return null; } /** * getExistingSource method comment. */ public String getExistingSource() throws IvjException { return null; } /** * getMethodBuilders method comment. */ public java.util.Enumeration getMethodBuilders() { return null; } /** * getSource method comment. */ public String getSource() { return null; } /** * isMarkedForDeletion method comment. */ public boolean isMarkedForDeletion() { return false; } /** * markForDeletion method comment. */ public void markForDeletion(boolean arg1) {} /** * removeAllMethodBuilders method comment. */ public void removeAllMethodBuilders() {} /** * removeMethodBuilder method comment. */ public void removeMethodBuilder(MethodBuilder arg1) {} /** * saveMerge method comment. */ public void saveMerge() throws IvjException {} /** * setSource method comment. */ public void setSource(String source) { mySourceVerifier.setSource(myBuilderName,source); } /** * verify method comment. */ public void verify() {} } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockPackage.java0000644000175000017500000001361307331064401027236 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import java.util.*; import com.mockobjects.*; public class MockPackage extends MockObject implements com.ibm.ivj.util.base.Package { private String _pkgName; private ArrayList _types = new ArrayList(); private MockWorkspace _workspace; private Project _project; public MockPackage(String name, MockWorkspace workspace) { super(); _pkgName = name; _workspace = workspace; _workspace.setupAddPackage(this); } /** * @deprectated use setupAddContainedType */ public void addContainedType(Type aType) { setupAddType(aType); } /** * @deprecated */ public void addContainedType(MockType aType) { setupAddType(aType); } /** * clearToolRepositoryData method comment. */ public void clearToolRepositoryData(String arg1) throws IvjException {} /** * clearToolWorkspaceData method comment. */ public void clearToolWorkspaceData(String arg1) throws IvjException {} /** * createNewEdition method comment. */ public void createNewEdition() throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1) throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1, boolean arg2) throws IvjException {} /** * delete method comment. */ public void delete() throws IvjException {} /** * getAllEditions method comment. */ public com.ibm.ivj.util.base.PackageEdition[] getAllEditions() throws IvjException { return null; } /** * getComment method comment. */ public String getComment() throws IvjException { return null; } /** * getEdition method comment. */ public PackageEdition getEdition() throws IvjException { return null; } /** * getName method comment. */ public String getName() { return _pkgName; } /** * getOwnerName method comment. */ public String getOwnerName() throws IvjException { return null; } public Project getProject() throws IvjException { return _project; } /** * getToolRepositoryData method comment. */ public ToolData getToolRepositoryData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getToolWorkspaceData method comment. */ public ToolData getToolWorkspaceData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getTypes method comment. */ public com.ibm.ivj.util.base.Type[] getTypes() throws IvjException { Type[] result = new Type[_types.size()]; _types.toArray(result); return result; } /** * getVersionName method comment. */ public String getVersionName() throws IvjException { return null; } /** * getVersionStamp method comment. */ public java.util.Date getVersionStamp() throws IvjException { return null; } /** * isDefaultPackage method comment. */ public boolean isDefaultPackage() { return false; } /** * isEdition method comment. */ public boolean isEdition() throws IvjException { return true; } /** * isPackage method comment. */ public boolean isPackage() { return true; } /** * isProject method comment. */ public boolean isProject() { return false; } /** * isReleased method comment. */ public boolean isReleased() throws IvjException { return false; } /** * isScratchEdition method comment. */ public boolean isScratchEdition() throws IvjException { return false; } /** * isType method comment. */ public boolean isType() { return false; } /** * isVersion method comment. */ public boolean isVersion() throws IvjException { return false; } /** * openBrowser method comment. */ public void openBrowser() throws IvjException {} /** * release method comment. */ public void release() throws IvjException {} /** * setComment method comment. */ public void setComment(String arg1) throws IvjException {} /** @deprecated */ public void setProject(Project project) { _project = project; } /** * setToolRepositoryData method comment. */ public void setToolRepositoryData(ToolData arg1) throws java.io.IOException, IvjException {} /** * setToolWorkspaceData method comment. */ public void setToolWorkspaceData(ToolData arg1) throws java.io.IOException, IvjException {} public void setupAddType(Type aType) { _types.add(aType); _workspace.setupAddType(aType); } public void setupAddType(MockType aType) { setupAddType((Type)aType); aType.setPackage(this); } public MockType setupNewType(String name) { MockType aType = new MockType(name); setupAddType(aType); return aType; } public void setupProject(Project project) { _project = project; } /** * testToolRepositoryData method comment. */ public boolean testToolRepositoryData(String arg1) throws IvjException { return false; } /** * testToolWorkspaceData method comment. */ public boolean testToolWorkspaceData(String arg1) throws IvjException { return false; } /** * verify method comment. */ public void verify() {} } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockProject.java0000644000175000017500000001146207331064401027311 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import com.ibm.ivj.util.base.*; import com.mockobjects.*; public class MockProject extends MockObject implements Project { /** * MockProject constructor comment. */ public MockProject() { super(); } /** * clearToolRepositoryData method comment. */ public void clearToolRepositoryData(String arg1) throws IvjException {} /** * clearToolWorkspaceData method comment. */ public void clearToolWorkspaceData(String arg1) throws IvjException {} /** * createDefaultPackage method comment. */ public com.ibm.ivj.util.base.Package createDefaultPackage(boolean arg1) throws IvjException { return null; } /** * createNewEdition method comment. */ public void createNewEdition() throws IvjException {} /** * createPackage method comment. */ public com.ibm.ivj.util.base.Package createPackage(String arg1, boolean arg2) throws IvjException { return null; } /** * createVersion method comment. */ public void createVersion(String arg1) throws IvjException {} /** * delete method comment. */ public void delete() throws IvjException {} /** * getAllEditions method comment. */ public com.ibm.ivj.util.base.ProjectEdition[] getAllEditions() throws IvjException { return null; } /** * getComment method comment. */ public String getComment() throws IvjException { return null; } /** * getDefaultPackage method comment. */ public com.ibm.ivj.util.base.Package getDefaultPackage() throws IvjException { return null; } /** * getEdition method comment. */ public ProjectEdition getEdition() throws IvjException { return null; } /** * getName method comment. */ public String getName() { return null; } /** * getOwnerName method comment. */ public String getOwnerName() throws IvjException { return null; } /** * getPackages method comment. */ public com.ibm.ivj.util.base.Package[] getPackages() throws IvjException { return null; } /** * getToolRepositoryData method comment. */ public ToolData getToolRepositoryData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getToolWorkspaceData method comment. */ public ToolData getToolWorkspaceData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getTypes method comment. */ public com.ibm.ivj.util.base.Type[] getTypes() throws IvjException { return null; } /** * getVersionName method comment. */ public String getVersionName() throws IvjException { return null; } /** * getVersionStamp method comment. */ public java.util.Date getVersionStamp() throws IvjException { return null; } /** * isEdition method comment. */ public boolean isEdition() throws IvjException { return false; } /** * isPackage method comment. */ public boolean isPackage() { return false; } /** * isProject method comment. */ public boolean isProject() { return false; } /** * isScratchEdition method comment. */ public boolean isScratchEdition() throws IvjException { return false; } /** * isType method comment. */ public boolean isType() { return false; } /** * isVersion method comment. */ public boolean isVersion() throws IvjException { return false; } /** * openBrowser method comment. */ public void openBrowser() throws IvjException {} /** * setComment method comment. */ public void setComment(String arg1) throws IvjException {} /** * setToolRepositoryData method comment. */ public void setToolRepositoryData(ToolData arg1) throws java.io.IOException, IvjException {} /** * setToolWorkspaceData method comment. */ public void setToolWorkspaceData(ToolData arg1) throws java.io.IOException, IvjException {} /** * testToolRepositoryData method comment. */ public boolean testToolRepositoryData(String arg1) throws IvjException { return false; } /** * testToolWorkspaceData method comment. */ public boolean testToolWorkspaceData(String arg1) throws IvjException { return false; } /** * verify method comment. */ public void verify() {} } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockType.java0000644000175000017500000001505307331064401026624 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import com.ibm.ivj.util.base.Package; import com.mockobjects.*; import java.util.*; public class MockType extends MockObject implements Type { private String myTypeName; private Package myPkg; private ArrayList myEditions = new ArrayList(); private boolean myHasSourceCode; public MockType(String name) { super(); myTypeName = name; } /** * clearToolRepositoryData method comment. */ public void clearToolRepositoryData(String arg1) throws IvjException {} /** * clearToolWorkspaceData method comment. */ public void clearToolWorkspaceData(String arg1) throws IvjException {} /** * createNewEdition method comment. */ public void createNewEdition() throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1) throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1, boolean arg2) throws IvjException {} /** * delete method comment. */ public void delete() throws IvjException {} public TypeEdition[] getAllEditions() throws IvjException { TypeEdition[] result = new TypeEdition[myEditions.size()]; myEditions.toArray(result); return result; } /** * getAllSubtypes method comment. */ public com.ibm.ivj.util.base.Type[] getAllSubtypes() { return null; } /** * getDeveloperName method comment. */ public String getDeveloperName() throws IvjException { return null; } /** * getEdition method comment. */ public TypeEdition getEdition() throws IvjException { return null; } /** * getName method comment. */ public String getName() { return myTypeName; } /** * getOwnerName method comment. */ public String getOwnerName() throws IvjException { return null; } /** * getPackage method comment. */ public com.ibm.ivj.util.base.Package getPackage() throws IvjException { return myPkg; } /** * getProject method comment. */ public Project getProject() throws IvjException { return myPkg.getProject(); } /** * getQualifiedName method comment. */ public String getQualifiedName() { return myPkg.getName()+"."+myTypeName; } /** * getToolRepositoryData method comment. */ public ToolData getToolRepositoryData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getToolWorkspaceData method comment. */ public ToolData getToolWorkspaceData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getVersionName method comment. */ public String getVersionName() throws IvjException { return null; } /** * getVersionStamp method comment. */ public java.util.Date getVersionStamp() throws IvjException { return null; } public boolean hasError() { notImplemented(); return false; } public boolean hasSourceCode() { return myHasSourceCode; } /** * isApplet method comment. */ public boolean isApplet() throws IvjException { return false; } /** * isApplication method comment. */ public boolean isApplication() throws IvjException { return false; } /** * isClass method comment. */ public boolean isClass() throws IvjException { return true; } /** * isEdition method comment. */ public boolean isEdition() throws IvjException { return true; } /** * isInDefaultPackage method comment. */ public boolean isInDefaultPackage() { return false; } /** * isInterface method comment. */ public boolean isInterface() throws IvjException { return false; } /** * isPackage method comment. */ public boolean isPackage() { return false; } /** * isProject method comment. */ public boolean isProject() { return false; } /** * isReleased method comment. */ public boolean isReleased() throws IvjException { return false; } /** * isType method comment. */ public boolean isType() { return false; } /** * isVersion method comment. */ public boolean isVersion() throws IvjException { return false; } /** * openBrowser method comment. */ public void openBrowser() throws IvjException {} /** * release method comment. */ public void release() throws IvjException {} public void setHasSourceCode(boolean hasSourceCode) { myHasSourceCode = hasSourceCode; } public void setPackage(Package pkg) { myPkg = pkg; } /** * setToolRepositoryData method comment. */ public void setToolRepositoryData(ToolData arg1) throws java.io.IOException, IvjException {} /** * setToolWorkspaceData method comment. */ public void setToolWorkspaceData(ToolData arg1) throws java.io.IOException, IvjException {} public void setupAddTypeEdition(TypeEdition edition) { myEditions.add(edition); } public MockTypeEdition setupNewTypeEdition(String versionName) { MockTypeEdition anEdition = new MockTypeEdition(versionName); setupAddTypeEdition(anEdition); return anEdition; } public MockTypeEdition setupNewTypeEdition(Date edition) { MockTypeEdition anEdition = new MockTypeEdition(null, edition); setupAddTypeEdition(anEdition); return anEdition; } /** * testToolRepositoryData method comment. */ public boolean testToolRepositoryData(String arg1) throws IvjException { return false; } /** * testToolWorkspaceData method comment. */ public boolean testToolWorkspaceData(String arg1) throws IvjException { return false; } /** * Returns a string representation of the test case */ public String toString() { return "MockType: " + getQualifiedName(); } /** * verify method comment. */ public void verify() {} } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockTypeBuilder.java0000644000175000017500000000531207331064401030130 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import junit.framework.*; import java.util.*; import com.mockobjects.*; public class MockTypeBuilder extends MockObject implements TypeBuilder { private String myBuilderName; private SourceVerifier mySourceVerifier; private ExpectationCounter mySaveCounter; public MockTypeBuilder(SourceVerifier verifier, String builderName) { super(); mySourceVerifier = verifier; myBuilderName = builderName; mySaveCounter = new ExpectationCounter(builderName + ".save()"); mySaveCounter.setExpected(1); } /** * addMethodBuilder method comment. */ public void addMethodBuilder(MethodBuilder arg1) {} /** * checkMethodExists method comment. */ public boolean checkMethodExists(MethodBuilder arg1) throws IvjException { return false; } /** * getBuilderName method comment. */ public String getBuilderName() { return myBuilderName; } /** * getExistingMethods method comment. */ public com.ibm.ivj.util.builders.MethodBuilder[] getExistingMethods() throws IvjException { return null; } /** * getExistingMethodSource method comment. */ public String getExistingMethodSource(MethodBuilder arg1) throws IvjException { return null; } /** * getExistingSource method comment. */ public String getExistingSource() throws IvjException { return null; } /** * getMethodBuilders method comment. */ public java.util.Enumeration getMethodBuilders() { return null; } /** * getSource method comment. */ public String getSource() { return null; } /** * isMarkedForDeletion method comment. */ public boolean isMarkedForDeletion() { return false; } /** * markForDeletion method comment. */ public void markForDeletion(boolean arg1) {} /** * removeAllMethodBuilders method comment. */ public void removeAllMethodBuilders() {} /** * removeMethodBuilder method comment. */ public void removeMethodBuilder(MethodBuilder arg1) {} /** * save method comment. */ public void save() throws IvjException { mySaveCounter.inc(); } /** * saveMerge method comment. */ public void saveMerge() throws IvjException {} /** * setSource method comment. */ public void setSource(String source) { mySourceVerifier.setSource(myBuilderName,source); } /** * Mock method */ public void verify() { mySaveCounter.verify(); } } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockTypeEdition.java0000644000175000017500000000656407331064401030147 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import com.ibm.ivj.util.base.*; import java.util.*; import com.mockobjects.*; public class MockTypeEdition extends MockObject implements TypeEdition { public static final Date DEFAULT_EDITION = new Date(); String myVersionName = null; Date myEditionStamp; ExpectationCounter myLoadCalls = new ExpectationCounter("loadIntoWorkspace"); public MockTypeEdition() { setupEditionStamp(DEFAULT_EDITION); setupVersionName(null); } public MockTypeEdition(String versionName) { setupEditionStamp(DEFAULT_EDITION); setupVersionName(versionName); } public MockTypeEdition(String versionName, Date edition) { setupEditionStamp(edition); setupVersionName(versionName); } /** * getAllEditions method comment. */ public com.ibm.ivj.util.base.TypeEdition[] getAllEditions() throws com.ibm.ivj.util.base.IvjException { return null; } /** * getDeveloperName method comment. */ public String getDeveloperName() throws com.ibm.ivj.util.base.IvjException { return null; } /** * getLoaded method comment. */ public com.ibm.ivj.util.base.Type getLoaded() throws com.ibm.ivj.util.base.IvjException { return null; } /** * getName method comment. */ public String getName() { return null; } /** * getOwnerName method comment. */ public String getOwnerName() throws com.ibm.ivj.util.base.IvjException { return null; } /** * getSimpleName method comment. */ public String getSimpleName() { return null; } /** * getVersionName method comment. */ public String getVersionName() { return myVersionName; } /** * getVersionStamp method comment. */ public java.util.Date getVersionStamp() { return myEditionStamp; } /** * isEdition method comment. */ public boolean isEdition() throws com.ibm.ivj.util.base.IvjException { return false; } /** * isLoaded method comment. */ public boolean isLoaded() throws com.ibm.ivj.util.base.IvjException { return false; } /** * isPackage method comment. */ public boolean isPackage() { return false; } /** * isProject method comment. */ public boolean isProject() { return false; } /** * isType method comment. */ public boolean isType() { return false; } /** * isVersion method comment. */ public boolean isVersion() throws com.ibm.ivj.util.base.IvjException { return false; } /** * loadIntoWorkspace method comment. */ public void loadIntoWorkspace() throws com.ibm.ivj.util.base.IvjException { myLoadCalls.inc(); } public void setExpectedLoadIntoWorkspaceCalls(int calls) { myLoadCalls.setExpected(calls); } public void setupEditionStamp(Date edition) { myEditionStamp = edition; } public void setupVersionName(String versionName) { myVersionName = versionName; } public String toString() { return this.getClass() + "V:" + getVersionName() + "E:" + getVersionStamp(); } /** * verify method comment. */ public void verify() { myLoadCalls.verify(); } } mockobjects-0.09/src/extensions/com/mockobjects/vaj/MockWorkspace.java0000644000175000017500000003614507331064401027646 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import java.util.*; import java.io.File; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import com.ibm.ivj.util.base.Package; import junit.framework.*; import com.mockobjects.*; import com.mockobjects.util.*; public class MockWorkspace extends MockObject implements Workspace { public final static String DEFAULT_PKG_PREFIX = "Default package for "; private MockBuilderFactory myBuilderFactory; private ArrayList myLoadedTypes = new ArrayList(); private ArrayList myLoadedPackages = new ArrayList(); private SourceVerifier mySourceVerifier; private ExportCodeSpec myExpectedExport; private ExportCodeSpec myActualExport; private ImportCodeSpec myExpectedImport; private ImportCodeSpec myActualImport; private HashMap myImportableFiles = new HashMap(); public MockWorkspace() { this(new SourceVerifier()); } public MockWorkspace(SourceVerifier verifier) { super(); mySourceVerifier = verifier; myBuilderFactory = new MockBuilderFactory(verifier); } /** * @deprecated use setupAddImportableFile */ public void addImportableFile(String fileName, Type associatedType) { setupAddImportableFile(fileName, associatedType); } /** * @deprecated use setupAddPackage */ public void addLoadedPackage(Package pkg) { setupAddPackage(pkg); } /** * @deprecated use setupAddType */ public void addLoadedType(Type type) { setupAddType(type); } /** * changeOwner method comment. */ public void changeOwner(java.lang.String arg1, java.lang.String arg2) throws com.ibm.ivj.util.base.IvjException {} /** * clearToolOptions method comment. */ public void clearToolOptions(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException {} public BuilderFactory createBuilderFactory() { return myBuilderFactory; } /** * createProject method comment. */ public com.ibm.ivj.util.base.Project createProject(java.lang.String arg1, boolean arg2) throws com.ibm.ivj.util.base.IvjException { return null; } public void exportData(ExportCodeSpec spec) throws IvjException { AssertMo.assertNull(myActualExport); myActualExport = spec; verifyExportSpec(); } /** * exportData method comment. */ public void exportData(com.ibm.ivj.util.base.ExportInterchangeSpec arg1) throws com.ibm.ivj.util.base.IvjException {} /** * getClassPathEntries method comment. */ public java.lang.Object[] getClassPathEntries() { return null; } /** * getCurrentOwnerName method comment. */ public java.lang.String getCurrentOwnerName() { return null; } /** * getDefaultClassPathEntries method comment. */ public java.lang.Object[] getDefaultClassPathEntries() { return null; } public static String getDefaultPackageFor(String projectName) { return DEFAULT_PKG_PREFIX + projectName; } /** * getPackages method comment. */ public com.ibm.ivj.util.base.Package[] getPackages() { return null; } /** * getProjects method comment. */ public com.ibm.ivj.util.base.Project[] getProjects() { return null; } /** * getRepository method comment. */ public com.ibm.ivj.util.base.Repository getRepository() { return null; } /** * getRepository method comment. */ public com.ibm.ivj.util.base.Repository getRepository(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException { return null; } /** * getRepository method comment. */ public com.ibm.ivj.util.base.Repository getRepository(java.lang.String arg1, java.lang.String arg2) throws com.ibm.ivj.util.base.IvjException { return null; } /** * getTempDirectory method comment. */ public java.lang.String getTempDirectory() throws com.ibm.ivj.util.base.IvjException { return null; } /** * getToolDataDirectory method comment. */ public java.lang.String getToolDataDirectory(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException { return null; } /** * getToolOptions method comment. */ public com.ibm.ivj.util.base.ToolData getToolOptions(java.lang.String arg1) throws java.io.IOException, java.io.StreamCorruptedException, com.ibm.ivj.util.base.IvjException, java.lang.ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getTypes method comment. */ public com.ibm.ivj.util.base.Type[] getTypes() { Type[] result = new Type[myLoadedTypes.size()]; myLoadedTypes.toArray(result); return result; } /** * getValidUsers method comment. */ public java.lang.String[] getValidUsers() { return null; } public Type[] importData(ImportCodeSpec importer) throws IllegalArgumentException, IvjException { AssertMo.assertNull(myActualImport); myActualImport = importer; verifyImportSpec(); return matchImportedTypes(importer); } /** * importData method comment. */ public void importData(com.ibm.ivj.util.base.ImportInterchangeSpec arg1) throws com.ibm.ivj.util.base.IvjException {} /** * isTeamMode method comment. */ public boolean isTeamMode() { return false; } /** * loadedDefaultPackageFor method comment. */ public com.ibm.ivj.util.base.Package loadedDefaultPackageFor(String projectName) { return loadedPackageNamed(DEFAULT_PKG_PREFIX + projectName); } /** * loadedDefaultPackagesFor method comment. */ public com.ibm.ivj.util.base.Package[] loadedDefaultPackagesFor(java.lang.String[] arg1) { return null; } /** * loadedPackageNamed method comment. */ public com.ibm.ivj.util.base.Package loadedPackageNamed(String pkgName) { for(Iterator it = myLoadedPackages.iterator(); it.hasNext(); ) { Package aPkg = (Package)it.next(); if(aPkg.getName().equals(pkgName)) return aPkg; } return null; } /** * loadedPackagesNamed method comment. */ public com.ibm.ivj.util.base.Package[] loadedPackagesNamed(java.lang.String[] arg1) { return null; } /** * loadedProjectNamed method comment. */ public com.ibm.ivj.util.base.Project loadedProjectNamed(java.lang.String arg1) { return null; } /** * loadedProjectsNamed method comment. */ public com.ibm.ivj.util.base.Project[] loadedProjectsNamed(java.lang.String[] arg1) { return null; } public Type loadedTypeNamed(String typeName) { for(Iterator it = myLoadedTypes.iterator(); it.hasNext(); ) { Type aType = (Type)it.next(); if(aType.getQualifiedName().equals(typeName)) return aType; } return null; } public Type[] loadedTypesNamed(String[] typeNames) { if (null == typeNames) { return null; } ArrayList loaded = new ArrayList(); for (int i = 0; i < typeNames.length; ++i) { loaded.add(loadedTypeNamed(typeNames[i])); } Type[] result = null; if (!loaded.isEmpty()) { result = new Type[loaded.size()]; loaded.toArray(result); } return result; } /** * logMessage method comment. */ public void logMessage(java.lang.String arg1, boolean arg2) {} private Type[] matchImportedTypes(ImportCodeSpec importer) throws IllegalArgumentException, IvjException { ArrayList types = new ArrayList(); String[] files = importer.getJavaFiles(); for (int i = 0; i < files.length; ++i) { Object type = myImportableFiles.get(files[i]); if (null != type) { types.add(type); } } Type[] result = null; if (!types.isEmpty()) { result = new Type[types.size()]; types.toArray(result); } return result; } /** * promptForApplet method comment. */ public com.ibm.ivj.util.base.Type promptForApplet(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForApplication method comment. */ public com.ibm.ivj.util.base.Type promptForApplication(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForClass method comment. */ public com.ibm.ivj.util.base.Type promptForClass(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForDirectoryName method comment. */ public java.lang.String promptForDirectoryName(java.lang.String arg1, java.lang.String arg2) { return null; } /** * promptForFileName method comment. */ public java.lang.String promptForFileName(java.lang.String arg1, java.lang.String arg2, java.lang.String arg3) { return null; } /** * promptForInterface method comment. */ public com.ibm.ivj.util.base.Type promptForInterface(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForModel method comment. */ public com.ibm.ivj.util.base.WorkspaceModel promptForModel(com.ibm.ivj.util.base.WorkspaceModel[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForPackage method comment. */ public com.ibm.ivj.util.base.Package promptForPackage(com.ibm.ivj.util.base.Package[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForPackage method comment. */ public com.ibm.ivj.util.base.Package promptForPackage(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.Project arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForProject method comment. */ public com.ibm.ivj.util.base.Project promptForProject(com.ibm.ivj.util.base.Project[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForProject method comment. */ public com.ibm.ivj.util.base.Project promptForProject(java.lang.String arg1, java.lang.String arg2, java.lang.String arg3) { return null; } /** * promptForType method comment. */ public com.ibm.ivj.util.base.Type promptForType(com.ibm.ivj.util.base.Type[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForType method comment. */ public com.ibm.ivj.util.base.Type promptForType(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * removeClassPathEntries method comment. */ public void removeClassPathEntries(java.lang.Object[] arg1) throws com.ibm.ivj.util.base.IvjException {} /** * runMain method comment. */ public void runMain(java.lang.Class arg1, java.lang.String[] arg2) throws java.lang.reflect.InvocationTargetException, java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.NoSuchMethodException, com.ibm.ivj.util.base.IvjException {} /** * setClassPath method comment. */ public void setClassPath(java.lang.Object[] arg1) throws com.ibm.ivj.util.base.IvjException {} public void setExpectedExport(ExportCodeSpec export) { myExpectedExport = export; } public void setExpectedImport(ImportCodeSpec importer) { myExpectedImport = importer; } /** * setToolOptions method comment. */ public void setToolOptions(com.ibm.ivj.util.base.ToolData arg1) throws java.io.IOException, com.ibm.ivj.util.base.IvjException {} /** * Mock method */ public void setupAddImportableFile(String fileName, Type associatedType) { myImportableFiles.put(fileName, associatedType); } /** * Mock method */ public void setupAddPackage(Package pkg) { myLoadedPackages.add(pkg); } public void setupAddType(Type type) { myLoadedTypes.add(type); } /** * Mock method */ public MockPackage setupNewDefaltPackage(String projectName) { return new MockPackage(getDefaultPackageFor(projectName), this); } /** * Mock method */ public MockPackage setupNewPackage(String pkgName) { return new MockPackage(pkgName, this); } /** * shutdown method comment. */ public void shutdown() {} /** * testToolOptions method comment. */ public boolean testToolOptions(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException { return false; } /** * Mock method */ public void verify() { mySourceVerifier.verify(); myBuilderFactory.verify(); } /** * Mock method */ private void verifyExportSpec() { if (null == myExpectedExport) { return; } AssertMo.assertNotNull("Should set export spec", myActualExport); AssertMo.assert("Use subdirectories", myExpectedExport.useSubdirectories() == myActualExport.useSubdirectories()); AssertMo.assert("include class", myExpectedExport.includeClass() == myActualExport.includeClass()); AssertMo.assertEquals("directory", myExpectedExport.getExportDirectory(), myActualExport.getExportDirectory()); ExpectationSet types = new ExpectationSet("Matching types"); types.addActualMany(myActualExport.getTypes()); types.addExpectedMany(myExpectedExport.getTypes()); types.verify(); } /** * Mock method */ private void verifyImportSpec() { if (null == myExpectedImport) { return; } AssertMo.assertNotNull("Should set export spec", myActualImport); AssertMo.assertEquals("Verify default project", myExpectedImport.getDefaultProject(), myActualImport.getDefaultProject()); ExpectationSet javaFiles = new ExpectationSet("Matching import types"); javaFiles.addActualMany(myActualImport.getJavaFiles()); javaFiles.addExpectedMany(myExpectedImport.getJavaFiles()); javaFiles.verify(); } } mockobjects-0.09/src/extensions/com/mockobjects/vaj/Readme.txt0000644000175000017500000000014007331064401026153 0ustar craftermcrafterm00000000000000One version of mock implementation of the VisualAge IDE library. Not sure which one to use yet. mockobjects-0.09/src/extensions/com/mockobjects/vaj/SourceVerifier.java0000644000175000017500000000404007331064401030017 0ustar craftermcrafterm00000000000000package com.mockobjects.vaj; import java.util.*; import com.mockobjects.*; import junit.framework.Assert;/** * Test Object to verify method source fragments */ public class SourceVerifier implements Verifiable { private ExpectationSet myClassMethods = new ExpectationSet("Expected methods to save"); private HashMap myClassAndMethods = new HashMap(); public SourceVerifier() { super(); } private void addClassAndMethod(String className, String methodName) { getClassMethods(className).add(methodName); } public void addExpectedClass(String className) { addExpectedMethod(className, " class " + className); } private void addExpectedMethod(String className, String methodName) { addClassAndMethod(className, methodName); myClassMethods.addExpected(makeUniqueName(className, methodName)); } public void addExpectedMethods(String className, String[] methodNames) { for (int i = 0; i < methodNames.length; i++) { addExpectedMethod(className, methodNames[i]); } } private Set getClassMethods(String className) { Set methodSet = (Set)myClassAndMethods.get(className); if (null == methodSet) { methodSet = new HashSet(); myClassAndMethods.put(className, methodSet); } return methodSet; } private String makeUniqueName(String className, String methodName) { return className + "/" + methodName; } public void setSource(String sourceClass, String source) { Iterator methodNames = getClassMethods(sourceClass).iterator(); while (methodNames.hasNext()) { String methodName = (String)methodNames.next(); if (source.indexOf(methodName) != -1) { myClassMethods.addActual(makeUniqueName(sourceClass, methodName)); return; } } Assert.fail("Did not find method matching source:\n " + source); } public void verify() { myClassMethods.verify(); } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/0000755000175000017500000000000010117310266025421 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/com/mockobjects/visualage/MockBuilderFactory.java0000644000175000017500000000311607331064401032016 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import java.util.*; import com.ibm.ivj.util.builders.BuilderFactory; import com.ibm.ivj.util.builders.MethodBuilder; import com.ibm.ivj.util.builders.TypeBuilder; import com.ibm.ivj.util.base.Package; import com.ibm.ivj.util.base.Type; import com.ibm.ivj.util.base.IvjException;public class MockBuilderFactory implements BuilderFactory { private ArrayList myTypeBuilders = new ArrayList(); private SourceVerifier mySourceVerifier; private MockTypeBuilder mySingleTypeBuilder; public MockBuilderFactory(MockTypeBuilder builder) { mySingleTypeBuilder = builder; } public MockBuilderFactory(SourceVerifier verifier) { super(); mySourceVerifier = verifier; } public MethodBuilder createMethodBuilder(String builderName) throws java.lang.IllegalArgumentException { return new MockMethodBuilder(mySourceVerifier,builderName); } public TypeBuilder createTypeBuilder(Type aType) throws IllegalArgumentException, IvjException { return mySingleTypeBuilder; } public TypeBuilder createTypeBuilder(String typeName, Package pkg) throws IllegalArgumentException, IvjException { MockTypeBuilder builder = new MockTypeBuilder(mySourceVerifier,typeName); myTypeBuilders.add(builder); return builder; } public String createUserCodeBlock(String arg1, String arg2) { return null; } public void verify() { for(Iterator it = myTypeBuilders.iterator();it.hasNext();) { ((MockTypeBuilder)it.next()).verify(); } } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/MockMethodBuilder.java0000644000175000017500000000474307331064401031636 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import junit.framework.*; import java.util.*;public class MockMethodBuilder implements MethodBuilder { private SourceVerifier mySourceVerifier; private String myBuilderName; String myExistingSource; public MockMethodBuilder(SourceVerifier verfier, String builderName) { super(); mySourceVerifier = verfier; myBuilderName = builderName; } public MockMethodBuilder(String source) { myExistingSource = source; } /** * addMethodBuilder method comment. */ public void addMethodBuilder(MethodBuilder arg1) {} /** * checkMethodExists method comment. */ public boolean checkMethodExists(MethodBuilder arg1) throws IvjException { return false; } /** * getBuilderName method comment. */ public String getBuilderName() { return myBuilderName; } /** * getExistingMethods method comment. */ public com.ibm.ivj.util.builders.MethodBuilder[] getExistingMethods() throws IvjException { return null; } /** * getExistingMethodSource method comment. */ public String getExistingMethodSource(MethodBuilder builder) throws IvjException { return ((MockMethodBuilder)builder).myExistingSource; } /** * getExistingSource method comment. */ public String getExistingSource() throws IvjException { return null; } /** * getMethodBuilders method comment. */ public java.util.Enumeration getMethodBuilders() { return null; } /** * getSource method comment. */ public String getSource() { return null; } /** * isMarkedForDeletion method comment. */ public boolean isMarkedForDeletion() { return false; } /** * markForDeletion method comment. */ public void markForDeletion(boolean arg1) {} /** * removeAllMethodBuilders method comment. */ public void removeAllMethodBuilders() {} /** * removeMethodBuilder method comment. */ public void removeMethodBuilder(MethodBuilder arg1) {} /** * saveMerge method comment. */ public void saveMerge() throws IvjException {} /** * setSource method comment. */ public void setSource(String source) { mySourceVerifier.setSource(myBuilderName,source); } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/MockPackage.java0000644000175000017500000001301607331064401030433 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import java.util.*;public class MockPackage implements com.ibm.ivj.util.base.Package { private String _pkgName; private ArrayList _types = new ArrayList(); private MockWorkspace _workspace; private boolean _isDefaultPackage = false; public MockPackage(String name, MockWorkspace workspace) { super(); _pkgName = name; _workspace = workspace; _workspace.addLoadedPackage(this); } /** * Mock Method */ public void addContainedType(Type aType) { _types.add(aType); _workspace.addLoadedType(aType); } /** * Mock Method */ public void addContainedType(MockType aType) { _types.add(aType); aType.setupPackage(this); _workspace.addLoadedType(aType); } /** * clearToolRepositoryData method comment. */ public void clearToolRepositoryData(String arg1) throws IvjException {} /** * clearToolWorkspaceData method comment. */ public void clearToolWorkspaceData(String arg1) throws IvjException {} /** * createNewEdition method comment. */ public void createNewEdition() throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1) throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1, boolean arg2) throws IvjException {} /** * delete method comment. */ public void delete() throws IvjException {} /** * getAllEditions method comment. */ public com.ibm.ivj.util.base.PackageEdition[] getAllEditions() throws IvjException { return null; } /** * getComment method comment. */ public String getComment() throws IvjException { return null; } /** * getEdition method comment. */ public PackageEdition getEdition() throws IvjException { return null; } /** * getName method comment. */ public String getName() { return _pkgName; } /** * getOwnerName method comment. */ public String getOwnerName() throws IvjException { return null; } /** * getProject method comment. */ public Project getProject() throws IvjException { return null; } /** * getToolRepositoryData method comment. */ public ToolData getToolRepositoryData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getToolWorkspaceData method comment. */ public ToolData getToolWorkspaceData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getTypes method comment. */ public com.ibm.ivj.util.base.Type[] getTypes() throws IvjException { Type[] result = new Type[_types.size()]; _types.toArray(result); return result; } /** * getVersionName method comment. */ public String getVersionName() throws IvjException { return null; } /** * getVersionStamp method comment. */ public java.util.Date getVersionStamp() throws IvjException { return null; } /** * isDefaultPackage method comment. */ public boolean isDefaultPackage() { return _isDefaultPackage; } /** * isEdition method comment. */ public boolean isEdition() throws IvjException { return true; } /** * isPackage method comment. */ public boolean isPackage() { return true; } /** * isProject method comment. */ public boolean isProject() { return false; } /** * isReleased method comment. */ public boolean isReleased() throws IvjException { return false; } /** * isScratchEdition method comment. */ public boolean isScratchEdition() throws IvjException { return false; } /** * isType method comment. */ public boolean isType() { return false; } /** * isVersion method comment. */ public boolean isVersion() throws IvjException { return false; } /** * openBrowser method comment. */ public void openBrowser() throws IvjException {} /** * release method comment. */ public void release() throws IvjException {} /** * setComment method comment. */ public void setComment(String arg1) throws IvjException {} /** * setToolRepositoryData method comment. */ public void setToolRepositoryData(ToolData arg1) throws java.io.IOException, IvjException {} /** * setToolWorkspaceData method comment. */ public void setToolWorkspaceData(ToolData arg1) throws java.io.IOException, IvjException {} public void setupIsDefaultPackage() { _isDefaultPackage = true; } /** * testToolRepositoryData method comment. */ public boolean testToolRepositoryData(String arg1) throws IvjException { return false; } /** * testToolWorkspaceData method comment. */ public boolean testToolWorkspaceData(String arg1) throws IvjException { return false; } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/MockType.java0000644000175000017500000001360607331064401030026 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import com.ibm.ivj.util.base.Package;public class MockType implements Type { private String myTypeName; private Package myPkg; private String mySource; public MockType(String name) { super(); myTypeName = name; } /** * clearToolRepositoryData method comment. */ public void clearToolRepositoryData(String arg1) throws IvjException {} /** * clearToolWorkspaceData method comment. */ public void clearToolWorkspaceData(String arg1) throws IvjException {} /** * createNewEdition method comment. */ public void createNewEdition() throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1) throws IvjException {} /** * createVersion method comment. */ public void createVersion(String arg1, boolean arg2) throws IvjException {} /** * delete method comment. */ public void delete() throws IvjException {} /** * getAllEditions method comment. */ public com.ibm.ivj.util.base.TypeEdition[] getAllEditions() throws IvjException { return null; } /** * getAllSubtypes method comment. */ public com.ibm.ivj.util.base.Type[] getAllSubtypes() { return null; } /** * getDeveloperName method comment. */ public String getDeveloperName() throws IvjException { return null; } /** * getEdition method comment. */ public TypeEdition getEdition() throws IvjException { return null; } /** * getName method comment. */ public String getName() { return myTypeName; } /** * getOwnerName method comment. */ public String getOwnerName() throws IvjException { return null; } /** * getPackage method comment. */ public com.ibm.ivj.util.base.Package getPackage() throws IvjException { return myPkg; } /** * getProject method comment. */ public Project getProject() throws IvjException { return myPkg.getProject(); } /** * getQualifiedName method comment. */ public String getQualifiedName() { return myPkg.getName()+"."+myTypeName; } /** * getToolRepositoryData method comment. */ public ToolData getToolRepositoryData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getToolWorkspaceData method comment. */ public ToolData getToolWorkspaceData(String arg1) throws java.io.IOException, java.io.StreamCorruptedException, IvjException, ClassNotFoundException, java.io.OptionalDataException { return null; } public String getupSource() { return mySource; } /** * getVersionName method comment. */ public String getVersionName() throws IvjException { return null; } /** * getVersionStamp method comment. */ public java.util.Date getVersionStamp() throws IvjException { return null; } /** * hasError method comment. */ public boolean hasError() { return false; } /** * hasSourceCode method comment. */ public boolean hasSourceCode() { return false; } /** * isApplet method comment. */ public boolean isApplet() throws IvjException { return false; } /** * isApplication method comment. */ public boolean isApplication() throws IvjException { return false; } /** * isClass method comment. */ public boolean isClass() throws IvjException { return true; } /** * isEdition method comment. */ public boolean isEdition() throws IvjException { return true; } /** * isInDefaultPackage method comment. */ public boolean isInDefaultPackage() { return (myPkg == null ? true : myPkg.isDefaultPackage()); } /** * isInterface method comment. */ public boolean isInterface() throws IvjException { return false; } /** * isPackage method comment. */ public boolean isPackage() { return false; } /** * isProject method comment. */ public boolean isProject() { return false; } /** * isReleased method comment. */ public boolean isReleased() throws IvjException { return false; } /** * isType method comment. */ public boolean isType() { return false; } /** * isVersion method comment. */ public boolean isVersion() throws IvjException { return false; } /** * openBrowser method comment. */ public void openBrowser() throws IvjException {} /** * release method comment. */ public void release() throws IvjException {} /** * setToolRepositoryData method comment. */ public void setToolRepositoryData(ToolData arg1) throws java.io.IOException, IvjException {} /** * setToolWorkspaceData method comment. */ public void setToolWorkspaceData(ToolData arg1) throws java.io.IOException, IvjException {} public void setupPackage(Package pkg) { myPkg = pkg; } public void setupSource(String source) { mySource = source; } /** * testToolRepositoryData method comment. */ public boolean testToolRepositoryData(String arg1) throws IvjException { return false; } /** * testToolWorkspaceData method comment. */ public boolean testToolWorkspaceData(String arg1) throws IvjException { return false; } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/MockTypeBuilder.java0000644000175000017500000000561407331064401031335 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import java.util.*; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import junit.framework.*; import com.mockobjects.ExpectationCounter; import com.mockobjects.Verifiable;public class MockTypeBuilder implements TypeBuilder, Verifiable { private String myBuilderName; private SourceVerifier mySourceVerifier; private ExpectationCounter mySaveCounter; private MockType myType; public MockTypeBuilder(MockType aType) { myType = aType; } public MockTypeBuilder(SourceVerifier verifier, String builderName) { super(); mySourceVerifier = verifier; myBuilderName = builderName; mySaveCounter = new ExpectationCounter(builderName + ".save()"); mySaveCounter.setExpected(1); } /** * addMethodBuilder method comment. */ public void addMethodBuilder(MethodBuilder arg1) { } /** * checkMethodExists method comment. */ public boolean checkMethodExists(MethodBuilder arg1) throws IvjException { return false; } /** * getBuilderName method comment. */ public String getBuilderName() { return myBuilderName; } /** * getExistingMethods method comment. */ public com.ibm.ivj.util.builders.MethodBuilder[] getExistingMethods() throws IvjException { return null; } public String getExistingMethodSource(MethodBuilder builder) throws IvjException { return ((MockMethodBuilder) builder).myExistingSource; } public String getExistingSource() throws IvjException { return myType.getupSource(); } /** * getMethodBuilders method comment. */ public java.util.Enumeration getMethodBuilders() { return null; } /** * getSource method comment. */ public String getSource() { return null; } /** * isMarkedForDeletion method comment. */ public boolean isMarkedForDeletion() { return false; } /** * markForDeletion method comment. */ public void markForDeletion(boolean arg1) { } /** * removeAllMethodBuilders method comment. */ public void removeAllMethodBuilders() { } /** * removeMethodBuilder method comment. */ public void removeMethodBuilder(MethodBuilder arg1) { } /** * save method comment. */ public void save() throws IvjException { mySaveCounter.inc(); } /** * saveMerge method comment. */ public void saveMerge() throws IvjException { } /** * setSource method comment. */ public void setSource(String source) { mySourceVerifier.setSource(myBuilderName, source); } public void setupExistingSource(String source) { myType.setupSource(source); } public void verify() { mySaveCounter.verify(); } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/MockWorkspace.java0000644000175000017500000002723607331064401031047 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import com.ibm.ivj.util.base.*; import com.ibm.ivj.util.builders.*; import com.ibm.ivj.util.base.Package; import junit.framework.*; import java.util.*; import com.mockobjects.Verifiable;public class MockWorkspace implements Workspace, Verifiable { private MockBuilderFactory myBuilderFactory; private ArrayList myLoadedTypes = new ArrayList(); private ArrayList myLoadedPackages = new ArrayList(); private SourceVerifier mySourceVerifier; public MockWorkspace() { } public MockWorkspace(MockType aType) { myBuilderFactory = new MockBuilderFactory(new MockTypeBuilder(aType)); } public MockWorkspace(SourceVerifier verifier) { this(verifier, new MockBuilderFactory(verifier)); } public MockWorkspace(SourceVerifier verifier, MockBuilderFactory builderFactory) { super(); mySourceVerifier = verifier; myBuilderFactory = builderFactory; } /** * Mock method */ public void addLoadedPackage(Package pkg) { myLoadedPackages.add(pkg); } /** * Mock method */ public void addLoadedType(Type type) { myLoadedTypes.add(type); } /** * changeOwner method comment. */ public void changeOwner(java.lang.String arg1, java.lang.String arg2) throws com.ibm.ivj.util.base.IvjException {} /** * clearToolOptions method comment. */ public void clearToolOptions(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException {} /** * createBuilderFactory method comment. */ public com.ibm.ivj.util.builders.BuilderFactory createBuilderFactory() { return myBuilderFactory; } /** * createProject method comment. */ public com.ibm.ivj.util.base.Project createProject(java.lang.String arg1, boolean arg2) throws com.ibm.ivj.util.base.IvjException { return null; } /** * exportData method comment. */ public void exportData(com.ibm.ivj.util.base.ExportCodeSpec arg1) throws com.ibm.ivj.util.base.IvjException {} /** * exportData method comment. */ public void exportData(com.ibm.ivj.util.base.ExportInterchangeSpec arg1) throws com.ibm.ivj.util.base.IvjException {} /** * getClassPathEntries method comment. */ public java.lang.Object[] getClassPathEntries() { return null; } /** * getCurrentOwnerName method comment. */ public java.lang.String getCurrentOwnerName() { return null; } /** * getDefaultClassPathEntries method comment. */ public java.lang.Object[] getDefaultClassPathEntries() { return null; } /** * getPackages method comment. */ public com.ibm.ivj.util.base.Package[] getPackages() { return null; } /** * getProjects method comment. */ public com.ibm.ivj.util.base.Project[] getProjects() { return null; } /** * getRepository method comment. */ public com.ibm.ivj.util.base.Repository getRepository() { return null; } /** * getRepository method comment. */ public com.ibm.ivj.util.base.Repository getRepository(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException { return null; } /** * getRepository method comment. */ public com.ibm.ivj.util.base.Repository getRepository(java.lang.String arg1, java.lang.String arg2) throws com.ibm.ivj.util.base.IvjException { return null; } /** * getTempDirectory method comment. */ public java.lang.String getTempDirectory() throws com.ibm.ivj.util.base.IvjException { return null; } /** * getToolDataDirectory method comment. */ public java.lang.String getToolDataDirectory(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException { return null; } /** * getToolOptions method comment. */ public com.ibm.ivj.util.base.ToolData getToolOptions(java.lang.String arg1) throws java.io.IOException, java.io.StreamCorruptedException, com.ibm.ivj.util.base.IvjException, java.lang.ClassNotFoundException, java.io.OptionalDataException { return null; } /** * getTypes method comment. */ public com.ibm.ivj.util.base.Type[] getTypes() { Type[] result = new Type[myLoadedTypes.size()]; myLoadedTypes.toArray(result); return result; } /** * getValidUsers method comment. */ public java.lang.String[] getValidUsers() { return null; } /** * importData method comment. */ public com.ibm.ivj.util.base.Type[] importData(com.ibm.ivj.util.base.ImportCodeSpec arg1) throws java.lang.IllegalArgumentException, com.ibm.ivj.util.base.IvjException { return null; } /** * importData method comment. */ public void importData(com.ibm.ivj.util.base.ImportInterchangeSpec arg1) throws com.ibm.ivj.util.base.IvjException {} /** * isTeamMode method comment. */ public boolean isTeamMode() { return false; } /** * loadedDefaultPackageFor method comment. */ public com.ibm.ivj.util.base.Package loadedDefaultPackageFor(java.lang.String arg1) { return null; } /** * loadedDefaultPackagesFor method comment. */ public com.ibm.ivj.util.base.Package[] loadedDefaultPackagesFor(java.lang.String[] arg1) { return null; } /** * loadedPackageNamed method comment. */ public com.ibm.ivj.util.base.Package loadedPackageNamed(String pkgName) { for(Iterator it = myLoadedPackages.iterator(); it.hasNext(); ) { Package aPkg = (Package)it.next(); if(aPkg.getName().equals(pkgName)) return aPkg; } return null; } /** * loadedPackagesNamed method comment. */ public com.ibm.ivj.util.base.Package[] loadedPackagesNamed(java.lang.String[] arg1) { return null; } /** * loadedProjectNamed method comment. */ public com.ibm.ivj.util.base.Project loadedProjectNamed(java.lang.String arg1) { return null; } /** * loadedProjectsNamed method comment. */ public com.ibm.ivj.util.base.Project[] loadedProjectsNamed(java.lang.String[] arg1) { return null; } /** * loadedTypeNamed method comment. */ public com.ibm.ivj.util.base.Type loadedTypeNamed(java.lang.String typeName) { for(Iterator it = myLoadedTypes.iterator(); it.hasNext(); ) { Type aType = (Type)it.next(); if(aType.getQualifiedName().equals(typeName)) return aType; } return null; } /** * loadedTypesNamed method comment. */ public com.ibm.ivj.util.base.Type[] loadedTypesNamed(java.lang.String[] arg1) { return null; } /** * logMessage method comment. */ public void logMessage(java.lang.String arg1, boolean arg2) {} /** * promptForApplet method comment. */ public com.ibm.ivj.util.base.Type promptForApplet(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForApplication method comment. */ public com.ibm.ivj.util.base.Type promptForApplication(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForClass method comment. */ public com.ibm.ivj.util.base.Type promptForClass(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForDirectoryName method comment. */ public java.lang.String promptForDirectoryName(java.lang.String arg1, java.lang.String arg2) { return null; } /** * promptForFileName method comment. */ public java.lang.String promptForFileName(java.lang.String arg1, java.lang.String arg2, java.lang.String arg3) { return null; } /** * promptForInterface method comment. */ public com.ibm.ivj.util.base.Type promptForInterface(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForModel method comment. */ public com.ibm.ivj.util.base.WorkspaceModel promptForModel(com.ibm.ivj.util.base.WorkspaceModel[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForPackage method comment. */ public com.ibm.ivj.util.base.Package promptForPackage(com.ibm.ivj.util.base.Package[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForPackage method comment. */ public com.ibm.ivj.util.base.Package promptForPackage(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.Project arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForProject method comment. */ public com.ibm.ivj.util.base.Project promptForProject(com.ibm.ivj.util.base.Project[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForProject method comment. */ public com.ibm.ivj.util.base.Project promptForProject(java.lang.String arg1, java.lang.String arg2, java.lang.String arg3) { return null; } /** * promptForType method comment. */ public com.ibm.ivj.util.base.Type promptForType(com.ibm.ivj.util.base.Type[] arg1, java.lang.String arg2, java.lang.String arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * promptForType method comment. */ public com.ibm.ivj.util.base.Type promptForType(java.lang.String arg1, java.lang.String arg2, com.ibm.ivj.util.base.WorkspaceModel arg3, java.lang.String arg4) throws com.ibm.ivj.util.base.IvjException { return null; } /** * removeClassPathEntries method comment. */ public void removeClassPathEntries(java.lang.Object[] arg1) throws com.ibm.ivj.util.base.IvjException {} /** * runMain method comment. */ public void runMain(java.lang.Class arg1, java.lang.String[] arg2) throws java.lang.reflect.InvocationTargetException, java.lang.IllegalAccessException, java.lang.IllegalArgumentException, java.lang.NoSuchMethodException, com.ibm.ivj.util.base.IvjException {} /** * setClassPath method comment. */ public void setClassPath(java.lang.Object[] arg1) throws com.ibm.ivj.util.base.IvjException {} /** * setToolOptions method comment. */ public void setToolOptions(com.ibm.ivj.util.base.ToolData arg1) throws java.io.IOException, com.ibm.ivj.util.base.IvjException {} /** * shutdown method comment. */ public void shutdown() {} /** * testToolOptions method comment. */ public boolean testToolOptions(java.lang.String arg1) throws com.ibm.ivj.util.base.IvjException { return false; } public void verify() { mySourceVerifier.verify(); myBuilderFactory.verify(); } }mockobjects-0.09/src/extensions/com/mockobjects/visualage/Readme.txt0000644000175000017500000000014007331064401027353 0ustar craftermcrafterm00000000000000One version of mock implementation of the VisualAge IDE library. Not sure which one to use yet. mockobjects-0.09/src/extensions/com/mockobjects/visualage/SourceVerifier.java0000644000175000017500000000404607331064401031225 0ustar craftermcrafterm00000000000000package com.mockobjects.visualage; import java.util.*; import com.mockobjects.*; import junit.framework.Assert;/** * Test Object to verify method source fragments */ public class SourceVerifier implements Verifiable { private ExpectationSet myClassMethods = new ExpectationSet("Expected methods to save"); private HashMap myClassAndMethods = new HashMap(); public SourceVerifier() { super(); } private void addClassAndMethod(String className, String methodName) { getClassMethods(className).add(methodName); } public void addExpectedClass(String className) { addExpectedMethod(className, " class " + className); } private void addExpectedMethod(String className, String methodName) { addClassAndMethod(className, methodName); myClassMethods.addExpected(makeUniqueName(className, methodName)); } public void addExpectedMethods(String className, String[] methodNames) { for (int i = 0; i < methodNames.length; i++) { addExpectedMethod(className, methodNames[i]); } } private Set getClassMethods(String className) { Set methodSet = (Set)myClassAndMethods.get(className); if (null == methodSet) { methodSet = new HashSet(); myClassAndMethods.put(className, methodSet); } return methodSet; } private String makeUniqueName(String className, String methodName) { return className + "/" + methodName; } public void setSource(String sourceClass, String source) { Iterator methodNames = getClassMethods(sourceClass).iterator(); while (methodNames.hasNext()) { String methodName = (String)methodNames.next(); if (source.indexOf(methodName) != -1) { myClassMethods.addActual(makeUniqueName(sourceClass, methodName)); return; } } Assert.fail("Did not find method matching source:\n " + source); } public void verify() { myClassMethods.verify(); } }mockobjects-0.09/src/extensions/test/0000755000175000017500000000000010117310266021337 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/test/connextra/0000755000175000017500000000000010117310266023340 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/test/connextra/util/0000755000175000017500000000000010117310266024315 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/extensions/test/connextra/util/ClockTest.java0000644000175000017500000000146107644131563027071 0ustar craftermcrafterm00000000000000package test.connextra.util; import junit.framework.*; import com.connextra.util.*; public class ClockTest extends TestCase { private static final Class THIS = ClockTest.class; public ClockTest(String name) { super(name); } public static Test suite() { return new TestSuite(THIS); } public void testRunning() throws InterruptedException { Clock aClock = new RealClock(); long start = aClock.getTime(); Thread.currentThread().sleep(10); long stop = aClock.getTime(); assertTrue("Should keep running", stop > start); } public void testStop() throws InterruptedException { Clock aClock = new RealClock(); aClock.stop(); long start = aClock.getTime(); Thread.currentThread().sleep(10); long stop = aClock.getTime(); assertEquals("Should not advance time", start, stop); } }mockobjects-0.09/src/extensions/test/connextra/util/TestVector.java0000644000175000017500000000345407644131563027304 0ustar craftermcrafterm00000000000000package test.connextra.util; import java.util.Enumeration; import java.util.Vector; public class TestVector extends Vector { public TestVector() { super(); } public TestVector(Object[] defaultValues) { super(); for (int i = 0; i < defaultValues.length; i++) { addElement(defaultValues[i]); } } public TestVector(Object defaultValue) { this(new Object[] {defaultValue}); } public TestVector(Object defaultValue1, Object defaultValue2) { this(new Object[] {defaultValue1, defaultValue2}); } public TestVector(Object defaultValue1, Object defaultValue2, Object defaultValue3) { this(new Object[] {defaultValue1, defaultValue2, defaultValue3}); } public TestVector(Object defaultValue1, Object defaultValue2, Object defaultValue3, Object defaultValue4) { this(new Object[] {defaultValue1, defaultValue2, defaultValue3, defaultValue4}); } public TestVector(Object defaultValue1, Object defaultValue2, Object defaultValue3, Object defaultValue4, Object defaultValue5) { this(new Object[] {defaultValue1, defaultValue2, defaultValue3, defaultValue4, defaultValue5}); } public TestVector(Object defaultValue1, Object defaultValue2, Object defaultValue3, Object defaultValue4, Object defaultValue5, Object defaultValue6) { this(new Object[] {defaultValue1, defaultValue2, defaultValue3, defaultValue4, defaultValue5, defaultValue6}); } public TestVector(Object defaultValue1, Object defaultValue2, Object defaultValue3, Object defaultValue4, Object defaultValue5, Object defaultValue6, Object defaultValue7) { this(new Object[] {defaultValue1, defaultValue2, defaultValue3, defaultValue4, defaultValue5, defaultValue6, defaultValue7}); } public TestVector(Enumeration defaultValues) { while (defaultValues.hasMoreElements()) { addElement(defaultValues.nextElement()); } } }mockobjects-0.09/src/j2ee/0000755000175000017500000000000010117310266017006 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.2/0000755000175000017500000000000010117310266017306 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.2/com/0000755000175000017500000000000010117310266020064 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.2/com/mockobjects/0000755000175000017500000000000010117310266022367 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.2/com/mockobjects/servlet/0000755000175000017500000000000010117310266024053 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.2/com/mockobjects/servlet/MockHttpServletRequest.java0000644000175000017500000001137307435762172031412 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import java.util.*; import javax.servlet.http.*; import com.mockobjects.*; public class MockHttpServletRequest implements HttpServletRequest { private Dictionary myParameters = new Hashtable(); private String myPathInfo; public MockHttpServletRequest() { super(); } /** * @deprecated */ public void addActualParameter(String paramName, String[] values) { setupAddParameter(paramName, values); } /** * @deprecated */ public void addActualParameter(String paramName, String value) { setupAddParameter(paramName, value); } public Object getAttribute(String arg1) { return null; } public java.util.Enumeration getAttributeNames() { return null; } public String getAuthType() { return null; } public String getCharacterEncoding() { return null; } public int getContentLength() { return 0; } public String getContentType() { return null; } public java.lang.String getContextPath() { return null; } public javax.servlet.http.Cookie[] getCookies() { return null; } public long getDateHeader(String arg1) { return 0; } public String getHeader(String arg1) { return null; } public java.util.Enumeration getHeaderNames() { return null; } public java.util.Enumeration getHeaders(java.lang.String arg1) { return null; } public javax.servlet.ServletInputStream getInputStream() throws java.io.IOException { return null; } public int getIntHeader(String arg1) { return 0; } public java.util.Locale getLocale() { return null; } public java.util.Enumeration getLocales() { return null; } public String getMethod() { return null; } public String getParameter(String paramName) { String[] values = getParameterValues(paramName); return (values == null ? null : values[0]); } public java.util.Enumeration getParameterNames() { return myParameters.keys(); } public String[] getParameterValues(String key) { return (String[]) myParameters.get(key); } public String getPathInfo() { return myPathInfo; } public String getPathTranslated() { return null; } public String getProtocol() { return null; } public String getQueryString() { return null; } public java.io.BufferedReader getReader() throws java.io.IOException { return null; } public String getRealPath(String arg1) { return null; } public String getRemoteAddr() { return null; } public String getRemoteHost() { return null; } public String getRemoteUser() { return null; } public javax.servlet.RequestDispatcher getRequestDispatcher( java.lang.String arg1) { return null; } public String getRequestedSessionId() { return null; } public String getRequestURI() { return null; } public String getScheme() { return null; } public String getServerName() { return null; } public int getServerPort() { return 0; } public String getServletPath() { return null; } public javax.servlet.http.HttpSession getSession() { return null; } public javax.servlet.http.HttpSession getSession(boolean arg1) { return null; } public java.security.Principal getUserPrincipal() { return null; } public boolean isRequestedSessionIdFromCookie() { return false; } public boolean isRequestedSessionIdFromUrl() { return false; } public boolean isRequestedSessionIdFromURL() { return false; } public boolean isRequestedSessionIdValid() { return false; } public boolean isSecure() { return false; } public boolean isUserInRole(java.lang.String arg1) { return false; } public void removeAttribute(java.lang.String arg1) { } public void setAttribute(String arg1, Object arg2) { } /** * @deprecated */ public void setNoActualParameters() { setupNoParameters(); } public void setupAddParameter(String paramName, String[] values) { myParameters.put(paramName, values); } public void setupAddParameter(String paramName, String value) { setupAddParameter(paramName, new String[] { value }); } public void setupNoParameters() { myParameters = new Hashtable(); } public void setupPathInfo(String pathInfo) { myPathInfo = pathInfo; } } mockobjects-0.09/src/j2ee/1.2/com/mockobjects/servlet/MockHttpServletResponse.java0000644000175000017500000001125707435762173031562 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import junit.framework.Assert; import com.mockobjects.*; public class MockHttpServletResponse extends MockObject implements HttpServletResponse, Verifiable { private ExpectationList myContentTypes = new ExpectationList("MockHttpServletResponse.setContentType"); private ExpectationList myHeaders = new ExpectationList("MockHttpServletResponse.setHeader"); private ExpectationCounter mySetStatusCalls = new ExpectationCounter("MockHttpServletResponse.setStatus"); private ExpectationList myRedirects = new ExpectationList("MockHttpServletResponse.sendRedirect"); private ServletOutputStream myOutputStream = new MockServletOutputStream(); /** * MockHttpServletResponse constructor comment. */ public MockHttpServletResponse() { super(); } public void addCookie(javax.servlet.http.Cookie arg1) { fail("Not implemented"); } /** * addDateHeader method comment. */ public void addDateHeader(java.lang.String arg1, long arg2) { } /** * addHeader method comment. */ public void addHeader(java.lang.String arg1, java.lang.String arg2) { } /** * addIntHeader method comment. */ public void addIntHeader(java.lang.String arg1, int arg2) { } public boolean containsHeader(String arg1) { fail("Not implemented"); return false; } public String encodeRedirectUrl(String arg1) { fail("Not implemented"); return null; } public String encodeRedirectURL(String arg1) { fail("Not implemented"); return null; } public String encodeUrl(String arg1) { fail("Not implemented"); return null; } public String encodeURL(String arg1) { fail("Not implemented"); return null; } /** * flushBuffer method comment. */ public void flushBuffer() throws java.io.IOException { } /** * getBufferSize method comment. */ public int getBufferSize() { return 0; } public String getCharacterEncoding() { fail("Not implemented"); return null; } /** * getLocale method comment. */ public java.util.Locale getLocale() { return null; } public javax.servlet.ServletOutputStream getOutputStream() throws java.io.IOException { return myOutputStream; } public String getOutputStreamContents() { return ((MockServletOutputStream) myOutputStream).getContents(); } public java.io.PrintWriter getWriter() throws java.io.IOException { return new PrintWriter(myOutputStream, true); } /** * isCommitted method comment. */ public boolean isCommitted() { return false; } /** * reset method comment. */ public void reset() { } public void sendError(int arg1) throws java.io.IOException { fail("Not implemented"); } public void sendError(int arg1, String arg2) throws java.io.IOException { fail("Not implemented"); } public void sendRedirect(String aURL) throws java.io.IOException { myRedirects.addActual(aURL); } /** * setBufferSize method comment. */ public void setBufferSize(int arg1) { } public void setContentLength(int arg1) { fail("Not implemented"); } public void setContentType(String contentType) { myContentTypes.addActual(contentType); } public void setDateHeader(String arg1, long arg2) { fail("Not implemented"); } public void setExpectedContentType(String contentType) { myContentTypes.addExpected(contentType); } public void setExpectedHeader(String key, String value) { myHeaders.addExpected(new MapEntry(key, value)); } public void setExpectedRedirect(String aURL) throws IOException { myRedirects.addExpected(aURL); } public void setExpectedSetStatusCalls(int callCount) { mySetStatusCalls.setExpected(callCount); } public void setHeader(String key, String value) { myHeaders.addActual(new MapEntry(key, value)); } public void setIntHeader(String arg1, int arg2) { Assert.fail("Not implemented"); } /** * setLocale method comment. */ public void setLocale(java.util.Locale arg1) { } public void setStatus(int status) { mySetStatusCalls.inc(); } public void setStatus(int arg1, String arg2) { Assert.fail("Not implemented"); } public void setupOutputStream(ServletOutputStream anOutputStream) { myOutputStream = anOutputStream; } } mockobjects-0.09/src/j2ee/1.2/com/mockobjects/servlet/MockHttpSession.java0000644000175000017500000000342707435762173030042 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import java.util.*; import javax.servlet.http.HttpSessionContext; import javax.servlet.http.HttpSession; import com.mockobjects.*; public class MockHttpSession extends MockObject implements HttpSession, Verifiable { public ExpectationSet myAttributes = new ExpectationSet("session attributes"); public MockHttpSession() { super(); } public Object getAttribute(String arg1) { notImplemented(); return null; } public Enumeration getAttributeNames() { return null; } public long getCreationTime() { notImplemented(); return 0; } public String getId() { notImplemented(); return null; } public long getLastAccessedTime() { notImplemented(); return 0; } public int getMaxInactiveInterval() { return 0; } public HttpSessionContext getSessionContext() { return null; } public Object getValue(String arg1) { notImplemented(); return null; } public java.lang.String[] getValueNames() { notImplemented(); return null; } public void invalidate() { } public boolean isNew() { return false; } public void putValue(String arg1, Object arg2) { } public void removeAttribute(String arg1) { } public void removeValue(String arg1) { } public void setAttribute(String aKey, Object aValue) { myAttributes.addActual(new MapEntry(aKey, aValue)); } public void setExpectedAttribute(String aKey, Object aValue) { myAttributes.addExpected(new MapEntry(aKey, aValue)); } public void setMaxInactiveInterval(int arg1) { } public void verify() { myAttributes.verify(); } } mockobjects-0.09/src/j2ee/1.3/0000755000175000017500000000000010117310266017307 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/alt/0000755000175000017500000000000010117310266020067 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/alt/javax/0000755000175000017500000000000010117310266021200 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/0000755000175000017500000000000010117310266022122 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/internet/0000755000175000017500000000000010117310266023752 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/internet/MimeMessageFactoryImpl.java0000644000175000017500000000044207552646024031200 0ustar craftermcrafterm00000000000000package alt.javax.mail.internet; import alt.javax.mail.internet.MimeMessage; import alt.javax.mail.Session; public class MimeMessageFactoryImpl implements MimeMessageFactory { public MimeMessage createMimeMessage(Session session){ return new MimeMessageImpl(session); } } mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/internet/MimeMessageImpl.java0000644000175000017500000001065407552646024027656 0ustar craftermcrafterm00000000000000package alt.javax.mail.internet; import alt.javax.mail.Message; import alt.javax.mail.MessageImpl; import alt.javax.mail.Session; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.MessagingException; import javax.mail.search.SearchTerm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; public class MimeMessageImpl extends MessageImpl implements MimeMessage { private final javax.mail.internet.MimeMessage message; public MimeMessageImpl(Session session) { super(new javax.mail.internet.MimeMessage(session.getWrappedSession())); message = (javax.mail.internet.MimeMessage)getRealMessage(); } public void setRecipient(javax.mail.Message.RecipientType type, Address address) throws MessagingException { message.setRecipient(type, address); } public void addRecipient(javax.mail.Message.RecipientType type, Address address) throws MessagingException { message.addRecipient(type, address); } public void setFlag(Flags.Flag flag, boolean b) throws MessagingException { message.setFlag(flag, b); } public int getMessageNumber() { return message.getMessageNumber(); } public Folder getFolder() { return message.getFolder(); } public boolean isExpunged() { return message.isExpunged(); } public boolean match(SearchTerm term) throws MessagingException { return message.match(term); } public Address[] getAllRecipients() throws MessagingException { return message.getAllRecipients(); } public void setRecipients(javax.mail.Message.RecipientType type, String s) throws MessagingException { message.setRecipients(type, s); } public void addRecipients(javax.mail.Message.RecipientType type, String s) throws MessagingException { message.addRecipients(type, s); } public Address[] getReplyTo() throws MessagingException { return message.getReplyTo(); } public void setReplyTo(Address[] addresses) throws MessagingException { message.setReplyTo(addresses); } public void setSubject(String s, String s1) throws MessagingException { message.setSubject(s, s1); } public String getEncoding() throws MessagingException { return message.getEncoding(); } public String getContentID() throws MessagingException { return message.getContentID(); } public void setContentID(String s) throws MessagingException { message.setContentID(s); } public String getContentMD5() throws MessagingException { return message.getContentMD5(); } public void setContentMD5(String s) throws MessagingException { message.setContentMD5(s); } public void setDescription(String s, String s1) throws MessagingException { message.setDescription(s, s1); } public String[] getContentLanguage() throws MessagingException { return message.getContentLanguage(); } public void setContentLanguage(String[] strings) throws MessagingException { message.setContentLanguage(strings); } public String getMessageID() throws MessagingException { return message.getMessageID(); } public InputStream getRawInputStream() throws MessagingException { return message.getRawInputStream(); } public void setText(String s, String s1) throws MessagingException { message.setText(s, s1); } public void writeTo(OutputStream stream, String[] strings) throws IOException, MessagingException { message.writeTo(stream, strings); } public String getHeader(String s, String s1) throws MessagingException { return message.getHeader(s, s1); } public void addHeaderLine(String s) throws MessagingException { message.addHeaderLine(s); } public Enumeration getAllHeaderLines() throws MessagingException { return message.getAllHeaderLines(); } public Enumeration getMatchingHeaderLines(String[] strings) throws MessagingException { return message.getMatchingHeaderLines(strings); } public Enumeration getNonMatchingHeaderLines(String[] strings) throws MessagingException { return message.getNonMatchingHeaderLines(strings); } public synchronized boolean isSet(Flags.Flag flag) throws MessagingException { return message.isSet(flag); } } mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/MessageImpl.java0000644000175000017500000001276507552646024025223 0ustar craftermcrafterm00000000000000package alt.javax.mail; import com.mockobjects.MockObject; import javax.mail.MessagingException; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Multipart; import java.util.Date; import java.util.Enumeration; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; public class MessageImpl implements Message { private final javax.mail.Message message; public MessageImpl(javax.mail.Message message) { this.message = message; } public javax.mail.Message getRealMessage() { return message; } public final Address[] getFrom() throws MessagingException { return message.getFrom(); } public final void setFrom() throws MessagingException { message.setFrom(); } public final void setFrom(Address address) throws MessagingException { message.setFrom(address); } public final void addFrom(Address[] addresses) throws MessagingException { message.addFrom(addresses); } public final Address[] getRecipients(javax.mail.Message.RecipientType type) throws MessagingException { return message.getRecipients(type); } public final void setRecipients(javax.mail.Message.RecipientType type, Address[] addresses) throws MessagingException { message.setRecipients(type, addresses); } public final void addRecipients(javax.mail.Message.RecipientType type, Address[] addresses) throws MessagingException { message.addRecipients(type, addresses); } public final String getSubject() throws MessagingException { return message.getSubject(); } public final void setSubject(String s) throws MessagingException { message.setSubject(s); } public final Date getSentDate() throws MessagingException { return message.getSentDate(); } public final void setSentDate(Date date) throws MessagingException { message.setSentDate(date); } public final Date getReceivedDate() throws MessagingException { return message.getReceivedDate(); } public final Flags getFlags() throws MessagingException { return message.getFlags(); } public final void setFlags(Flags flags, boolean b) throws MessagingException { message.setFlags(flags, b); } public final Message reply(boolean b) throws MessagingException { return new MessageImpl(message.reply(b)); } public final void saveChanges() throws MessagingException { message.saveChanges(); } public final int getSize() throws MessagingException { return message.getSize(); } public final int getLineCount() throws MessagingException { return message.getLineCount(); } public final String getContentType() throws MessagingException { return message.getContentType(); } public final boolean isMimeType(String s) throws MessagingException { return message.isMimeType(s); } public final String getDisposition() throws MessagingException { return message.getDisposition(); } public final void setDisposition(String s) throws MessagingException { message.setDisposition(s); } public final String getDescription() throws MessagingException { return message.getDescription(); } public final void setDescription(String s) throws MessagingException { message.setDescription(s); } public final String getFileName() throws MessagingException { return message.getFileName(); } public final void setFileName(String s) throws MessagingException { message.setFileName(s); } public final InputStream getInputStream() throws IOException, MessagingException { return message.getInputStream(); } public final javax.activation.DataHandler getDataHandler() throws MessagingException { return message.getDataHandler(); } public final Object getContent() throws IOException, MessagingException { return message.getContent(); } public final void setDataHandler(javax.activation.DataHandler handler) throws MessagingException { message.setDataHandler(handler); } public final void setContent(Object o, String s) throws MessagingException { message.setContent(o, s); } public final void setText(String s) throws MessagingException { message.setText(s); } public final void setContent(Multipart multipart) throws MessagingException { message.setContent(multipart); } public final void writeTo(OutputStream stream) throws IOException, MessagingException { message.writeTo(stream); } public final String[] getHeader(String s) throws MessagingException { return message.getHeader(s); } public final void setHeader(String s, String s1) throws MessagingException { message.setHeader(s, s1); } public final void addHeader(String s, String s1) throws MessagingException { message.addHeader(s, s1); } public final void removeHeader(String s) throws MessagingException { message.removeHeader(s); } public final Enumeration getAllHeaders() throws MessagingException { return message.getAllHeaders(); } public final Enumeration getMatchingHeaders(String[] strings) throws MessagingException { return message.getAllHeaders(); } public final Enumeration getNonMatchingHeaders(String[] strings) throws MessagingException { return message.getNonMatchingHeaders(strings); } } mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/ServiceImpl.java0000644000175000017500000000251507552646024025227 0ustar craftermcrafterm00000000000000package alt.javax.mail; import javax.mail.MessagingException; import javax.mail.URLName; import javax.mail.event.ConnectionListener; public class ServiceImpl implements Service { private final javax.mail.Service service; public ServiceImpl(javax.mail.Service service){ this.service = service; } public void connect() throws MessagingException{ service.connect(); } public void connect(String host, String user, String password) throws MessagingException{ service.connect(host, user, password); } public void connect(String host, int port, String user, String password) throws MessagingException{ service.connect(host, port, user, password); } public boolean isConnected(){ return service.isConnected(); } public void close() throws MessagingException{ service.close(); } public URLName getURLName(){ return service.getURLName(); } public void addConnectionListener(ConnectionListener connectionListener){ service.addConnectionListener(connectionListener); } public void removeConnectionListener(ConnectionListener connectionListener){ service.removeConnectionListener(connectionListener); } public String toString(){ return service.toString(); } } mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/SessionImpl.java0000644000175000017500000000667407552646024025264 0ustar craftermcrafterm00000000000000package alt.javax.mail; import javax.mail.*; import java.util.Properties; public class SessionImpl implements Session { private final javax.mail.Session session; public SessionImpl(javax.mail.Session session) { this.session = session; } public Session getInstance(Properties props, Authenticator authenticator) { return new SessionImpl(session.getInstance(props, authenticator)); } public Session getInstance(Properties props) { return new SessionImpl(session.getInstance(props)); } public Session getDefaultInstance(Properties props, Authenticator authenticator) { return new SessionImpl(session.getDefaultInstance( props, authenticator)); } public Session getDefaultInstance(Properties props) { return new SessionImpl(session.getDefaultInstance(props)); } public void setDebug(boolean debug) { } public boolean getDebug() { return session.getDebug(); } public Provider getProviders()[] { return session.getProviders(); } public Provider getProvider(String protocol) throws NoSuchProviderException { return session.getProvider(protocol); } public void setProvider(Provider provider) throws NoSuchProviderException { session.setProvider(provider); } public Store getStore() throws NoSuchProviderException { return session.getStore(); } public Store getStore(String protocol) throws NoSuchProviderException { return session.getStore(protocol); } public Store getStore(URLName url) throws NoSuchProviderException { return session.getStore(url); } public Store getStore(Provider provider) throws NoSuchProviderException { return session.getStore(provider); } public Folder getFolder(URLName url) throws MessagingException { return session.getFolder(url); } public Transport getTransport() throws NoSuchProviderException { return new TransportImpl(session.getTransport()); } public Transport getTransport(String protocol) throws NoSuchProviderException { return new TransportImpl(session.getTransport(protocol)); } public Transport getTransport(URLName url) throws NoSuchProviderException { return new TransportImpl(session.getTransport(url)); } public Transport getTransport(Provider provider) throws NoSuchProviderException { return new TransportImpl(session.getTransport(provider)); } public Transport getTransport(Address address) throws NoSuchProviderException { return new TransportImpl(session.getTransport(address)); } public void setPasswordAuthentication(URLName url, PasswordAuthentication pw) { session.setPasswordAuthentication(url, pw); } public PasswordAuthentication getPasswordAuthentication(URLName url) { return session.getPasswordAuthentication(url); } public PasswordAuthentication requestPasswordAuthentication(java.net.InetAddress addr, int port, String protocol, String prompt, String defaultUserName) { return session.requestPasswordAuthentication(addr, port, protocol, prompt, defaultUserName); } public Properties getProperties() { return session.getProperties(); } public String getProperty(String name) { return session.getProperty(name); } public javax.mail.Session getWrappedSession() { return session; } } mockobjects-0.09/src/j2ee/1.3/alt/javax/mail/TransportImpl.java0000644000175000017500000000220407552646024025616 0ustar craftermcrafterm00000000000000package alt.javax.mail; import alt.javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Address; import javax.mail.event.TransportListener; public class TransportImpl extends ServiceImpl implements Transport { private final javax.mail.Transport transport; public TransportImpl(javax.mail.Transport transport){ super(transport); this.transport = transport; } public void send(Message message) throws MessagingException{ transport.send(message.getRealMessage()); } public void send(Message message, Address[] addresses) throws MessagingException{ transport.send(message.getRealMessage(), addresses); } public void sendMessage(Message message, Address[] addresses) throws MessagingException{ transport.sendMessage(message.getRealMessage(), addresses); } public void addTransportListener(TransportListener transportListener){ transport.addTransportListener(transportListener); } public void removeTransportListener(TransportListener transportListener){ transport.removeTransportListener(transportListener); } } mockobjects-0.09/src/j2ee/1.3/com/0000755000175000017500000000000010117310266020065 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/com/mockobjects/0000755000175000017500000000000010117310266022370 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/com/mockobjects/helpers/0000755000175000017500000000000010117310266024032 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/com/mockobjects/helpers/AbstractServletTestHelper.java0000644000175000017500000000273107660457014032024 0ustar craftermcrafterm00000000000000package com.mockobjects.helpers; import com.mockobjects.servlet.*; /** * $Revision: 1.1 $ */ public abstract class AbstractServletTestHelper { protected final MockHttpServletRequest request = new MockHttpServletRequest(); protected final MockHttpServletResponse response = new MockHttpServletResponse(); protected final MockHttpSession httpSession = new MockHttpSession(); protected final MockRequestDispatcher requestDispatcher = new MockRequestDispatcher(); protected final MockServletContext servletContext = new MockServletContext(); protected final MockServletConfig servletConfig = new MockServletConfig(); public AbstractServletTestHelper() { request.setSession(httpSession); servletContext.setupGetRequestDispatcher(requestDispatcher); request.setupGetRequestDispatcher(requestDispatcher); httpSession.setupServletContext(servletContext); servletConfig.setServletContext(servletContext); } public MockHttpServletRequest getRequest() { return request; } public MockHttpSession getHttpSession() { return httpSession; } public MockRequestDispatcher getRequestDispatcher() { return requestDispatcher; } public MockHttpServletResponse getResponse() { return response; } public MockServletContext getServletContext() { return servletContext; } public MockServletConfig getServletConfig() { return servletConfig; } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/helpers/FilterTestHelper.java0000644000175000017500000000202007604317014030121 0ustar craftermcrafterm00000000000000package com.mockobjects.helpers; import com.mockobjects.servlet.MockFilterChain; import com.mockobjects.servlet.MockFilterConfig; import javax.servlet.Filter; import javax.servlet.ServletException; import java.io.IOException; /** * $Revision: 1.1 $ */ public class FilterTestHelper extends AbstractServletTestHelper { private final Filter filter; private final MockFilterChain filterChain = new MockFilterChain(); private final MockFilterConfig filterConfig = new MockFilterConfig(); public FilterTestHelper(Filter filter) { this.filter = filter; filterConfig.setupGetServletContext(servletContext); } public MockFilterChain getFilterChain() { return filterChain; } public MockFilterConfig getFilterConfig() { return filterConfig; } public void testInit() throws ServletException { filter.init(filterConfig); } public void testDoFilter() throws ServletException, IOException { filter.doFilter(request, response, filterChain); } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/helpers/ServletTestHelper.java0000644000175000017500000000252707660457045030347 0ustar craftermcrafterm00000000000000package com.mockobjects.helpers; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import java.io.IOException; /** * Sets up mock servlet objects in a common configuration. * HttpSession is attached to request, RequestDispatcher is connected to HttpSession * @see com.mockobjects.servlet.MockHttpServletRequest#setSession * @see com.mockobjects.servlet.MockServletContext#setupGetRequestDispatcher */ public class ServletTestHelper extends AbstractServletTestHelper { private final HttpServlet testSubject; public ServletTestHelper(HttpServlet testSubject) { super(); this.testSubject = testSubject; } /** * Calls HttpServlet.init passing it the MockServletConfig */ public void testServletInit() throws ServletException { testSubject.init(servletConfig); } /** * Calls HttpServlet.service passing it the MockHttpServletRequest & MockHttpServletResponse */ public void testServlet() throws ServletException, IOException { testSubject.service(request, response); } public void testDoPost() throws ServletException, IOException { request.setupGetMethod("POST"); testServlet(); } public void testDoGet() throws ServletException, IOException { request.setupGetMethod("GET"); testServlet(); } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/helpers/TagTestHelper.java0000644000175000017500000001036107660456577027442 0ustar craftermcrafterm00000000000000package com.mockobjects.helpers; import com.mockobjects.servlet.MockBodyContent; import com.mockobjects.servlet.MockJspWriter; import com.mockobjects.servlet.MockPageContext; import junit.framework.Assert; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.IterationTag; import javax.servlet.jsp.tagext.Tag; /** * Sets up mock tag objects in a common configuration. * MockHttpServletRequest, MockServletContext and MockHttpSession are attached to MockPageContext * @see com.mockobjects.servlet.MockPageContext#setRequest(); * @see com.mockobjects.servlet.MockPageContext#setServletContext(); * @see com.mockobjects.servlet.MockPageContext#setSession(); */ public class TagTestHelper extends AbstractServletTestHelper { private final MockPageContext pageContext = new MockPageContext(); private final MockBodyContent bodyContent = new MockBodyContent(); private final MockJspWriter outWriter = new MockJspWriter(); private final MockJspWriter enclosingWriter = new MockJspWriter(); private final Tag testSubject; private final String getReturnValueName(int returnValue) { switch (returnValue) { case BodyTag.EVAL_BODY_INCLUDE: return "EVAL_BODY_INCLUDE"; case BodyTag.EVAL_PAGE: return "EVAL_PAGE"; case BodyTag.SKIP_BODY: return "SKIP_BODY"; case BodyTag.SKIP_PAGE: return "SKIP_PAGE"; case BodyTag.EVAL_BODY_BUFFERED: return "EVAL_BODY_BUFFERED|EVAL_BODY_AGAIN"; default: return "Unknown return value (" + returnValue + ")"; } } /** * @param testSubject The Tag to be tested */ public TagTestHelper(Tag testSubject) { this.testSubject = testSubject; pageContext.setRequest(getRequest()); pageContext.setServletContext(getServletContext()); pageContext.setSession(getHttpSession()); pageContext.setJspWriter(outWriter); bodyContent.setupGetEnclosingWriter(enclosingWriter); } /** * @return The writer use when making calls to PageContext.getOut */ public MockJspWriter getOutWriter() { return outWriter; } public MockPageContext getPageContext() { return pageContext; } /** * Assert that the return value of doStartTag is equal to an expectedValue * @param expectedValue value to check against doStartTag */ public void assertDoStartTag(final int expectedValue) throws JspException { testSubject.setPageContext(pageContext); checkReturnValue("doStartTag", expectedValue, testSubject.doStartTag()); } private final void checkReturnValue(final String methodName, final int expectedValue, final int returnValue) { Assert.assertEquals(methodName + " expected value " + getReturnValueName(expectedValue) + " but was " + getReturnValueName(returnValue), expectedValue, returnValue); } /** * Invoke doInitBody on the test subject */ public void testDoInitBody() throws JspException { Assert.assertTrue("doInitBody should not be called as test subject not an instance of BodyTag", testSubject instanceof BodyTag); ((BodyTag) testSubject).setBodyContent(bodyContent); ((BodyTag) testSubject).doInitBody(); } /** * Assert that the return value of doAfterBody is equal to an expectedValue * @param expectedValue value to check against doAfterBody */ public void assertDoAfterBody(int expectedValue) throws JspException { Assert.assertTrue("doAfterTag should not be called as test subject not an instance of IterationTag", testSubject instanceof IterationTag); checkReturnValue("doAfterTag", expectedValue, ((IterationTag) testSubject).doAfterBody()); } /** * Assert that the return value of doEndTag is equal to an expectedValue * @param expectedValue value to check against doEndTag */ public void assertDoEndTag(int expectedValue) throws JspException { Assert.assertEquals("doEndTag returned unexpected value" + getReturnValueName(expectedValue), expectedValue, testSubject.doEndTag()); } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/servlet/0000755000175000017500000000000010117310266024054 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/com/mockobjects/servlet/MockFilterChain.java0000644000175000017500000000047007435762173027743 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.*; import javax.servlet.*; import java.io.IOException; public class MockFilterChain extends MockObject implements FilterChain { public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException{ } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/servlet/MockFilterConfig.java0000644000175000017500000000121407435762173030123 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.*; import java.util.*; import javax.servlet.*; public class MockFilterConfig extends MockObject implements FilterConfig { private ServletContext servletContext; public String getFilterName(){ return null; } public void setupGetServletContext(ServletContext servletContext){ this.servletContext = servletContext; } public ServletContext getServletContext(){ return servletContext; } public String getInitParameter(String name){ return null; } public Enumeration getInitParameterNames(){ return null; } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/servlet/MockHttpServletRequest.java0000644000175000017500000002674707654164134031423 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.*; import javax.servlet.ServletInputStream; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.Cookie; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.security.Principal; import com.mockobjects.ReturnValue; /** * @version $Revision: 1.16 $ */ public class MockHttpServletRequest extends MockObject implements HttpServletRequest { private final ReturnObjectBag myParameters = new ReturnObjectBag("parameters"); private final ReturnObjectBag myHeaders = new ReturnObjectBag("headers"); private final ReturnValue myHttpSession = new ReturnValue("session"); private final ReturnValue myContentTypeToReturn = new ReturnValue("content type"); private final ReturnValue myContextPath = new ReturnValue("context path"); private final ReturnValue myPathInfo = new ReturnValue("path info"); private final ReturnValue myRemoteAddress = new ReturnValue("remote address"); private final ReturnValue myRequestURI = new ReturnValue("request uri"); private final ReturnValue method = new ReturnValue("method"); private final ReturnValue protocol = new ReturnValue("protocol"); private final ReturnValue inputStream = new ReturnValue("input stream"); private final ReturnValue myUserPrincipal = new ReturnValue("user principal"); private final ReturnValue myAttributesNames = new ReturnValue("attribute names"); private final ReturnValue queryString = new ReturnValue("query string"); private final ReturnValue scheme = new ReturnValue("scheme"); private final ReturnValue serverName = new ReturnValue("server name"); private final ReturnValue reader = new ReturnValue("reader"); private final ExpectationSet mySetAttributes = new ExpectationSet("HttpServletRequest.setAttribute"); private final ExpectationSet myRemoveAttributes = new ExpectationSet("HttpServletRequest.removeAttribute"); private final ReturnObjectList myAttributesToReturn = new ReturnObjectList("attributes"); private final ExpectationValue myContentType = new ExpectationValue("content type"); private final ExpectationList myGetAttributeNames = new ExpectationList("get attribute names"); private final ReturnValue servletPath = new ReturnValue("servlet path"); private final ReturnValue parameterMap = new ReturnValue("parameter map"); private final ReturnValue myParameterNames = new ReturnValue("parameter names"); private final ReturnValue requestDispatcher = new ReturnValue("request dispatcher"); private final ExpectationValue requestDispatcherURI = new ExpectationValue("request dispatcher uri"); private final ExpectationValue createSession = new ExpectationValue("create session"); public void setupGetAttribute(Object anAttributeToReturn) { myAttributesToReturn.addObjectToReturn(anAttributeToReturn); } public void addExpectedGetAttributeName(String anAttributeName) { myGetAttributeNames.addExpected(anAttributeName); } public Object getAttribute(String anAttributeName) { myGetAttributeNames.addActual(anAttributeName); return myAttributesToReturn.nextReturnObject(); } public void setupGetAttrubuteNames(Enumeration attributeNames) { myAttributesNames.setValue(attributeNames); } public Enumeration getAttributeNames() { return (Enumeration) myAttributesNames.getValue(); } public String getAuthType() { notImplemented(); return null; } public String getCharacterEncoding() { notImplemented(); return null; } public int getContentLength() { notImplemented(); return 0; } public String getContentType() { return (String) myContentTypeToReturn.getValue(); } public void setupGetContentType(String aContentType) { myContentTypeToReturn.setValue(aContentType); } public void setExpectedContentType(String aContentType) { this.myContentType.setExpected(aContentType); } public void setContentType(String contentType) { this.myContentType.setActual(contentType); } public String getContextPath() { return (String) myContextPath.getValue(); } public void setupGetContextPath(String contextPath) { myContextPath.setValue(contextPath); } public Cookie[] getCookies() { notImplemented(); return null; } public long getDateHeader(String arg1) { notImplemented(); return 0; } public String getHeader(String key) { return (String) myHeaders.getNextReturnObject(key); } public Enumeration getHeaderNames() { notImplemented(); return null; } public Enumeration getHeaders(String arg1) { notImplemented(); return null; } public void setupGetInputStream(ServletInputStream inputStream) { this.inputStream.setValue(inputStream); } public ServletInputStream getInputStream() throws IOException { return (ServletInputStream) inputStream.getValue(); } public int getIntHeader(String arg1) { notImplemented(); return 0; } public Locale getLocale() { notImplemented(); return null; } public Enumeration getLocales() { notImplemented(); return null; } public void setupGetMethod(String aMethod) { this.method.setValue(aMethod); } public String getMethod() { return (String) method.getValue(); } public String getParameter(String paramName) { String[] values = getParameterValues(paramName); if (values == null) return null; return values[0]; } public void setupGetParameterNames(Enumeration names) { this.myParameterNames.setValue(names); } public Enumeration getParameterNames() { return (Enumeration) myParameterNames.getValue(); } public String[] getParameterValues(String key) { return (String[]) myParameters.getNextReturnObject(key); } public String getPathInfo() { return (String) myPathInfo.getValue(); } public String getPathTranslated() { notImplemented(); return null; } public String getProtocol() { return (String) protocol.getValue(); } public void setupGetProtocol(String protocol) { this.protocol.setValue(protocol); } public String getQueryString() { return (String) queryString.getValue(); } public BufferedReader getReader() { return (BufferedReader) reader.getValue(); } public void setupGetReader(BufferedReader reader) throws IOException { this.reader.setValue(reader); } public String getRealPath(String arg1) { notImplemented(); return null; } public void setupGetRemoteAddr(String remoteAddress) { this.myRemoteAddress.setValue(remoteAddress); } public String getRemoteAddr() { return (String) myRemoteAddress.getValue(); } public String getRemoteHost() { notImplemented(); return null; } public String getRemoteUser() { notImplemented(); return null; } public void setupGetRequestDispatcher(RequestDispatcher requestDispatcher) { this.requestDispatcher.setValue(requestDispatcher); } public RequestDispatcher getRequestDispatcher(String uri) { this.requestDispatcherURI.setActual(uri); return (RequestDispatcher) requestDispatcher.getValue(); } public void setExpectedRequestDispatcherURI(String uri) { this.requestDispatcherURI.setExpected(uri); } public String getRequestedSessionId() { notImplemented(); return null; } public void setupGetRequestURI(String aRequestURI) { myRequestURI.setValue(aRequestURI); } public String getRequestURI() { return (String) myRequestURI.getValue(); } public String getScheme() { return (String) scheme.getValue(); } public String getServerName() { return (String) serverName.getValue(); } public int getServerPort() { notImplemented(); return 0; } public void setupGetServletPath(String path) { this.servletPath.setValue(path); } public String getServletPath() { return (String) servletPath.getValue(); } public HttpSession getSession() { return (HttpSession) myHttpSession.getValue(); } public void setSession(HttpSession httpSession) { this.myHttpSession.setValue(httpSession); } public void setExpectedCreateSession(boolean createSession) { this.createSession.setExpected(createSession); } public HttpSession getSession(boolean createSession) { this.createSession.setActual(createSession); return getSession(); } public void setupGetUserPrincipal(Principal userPrincipal) { this.myUserPrincipal.setValue(userPrincipal); } public Principal getUserPrincipal() { return (Principal) myUserPrincipal.getValue(); } public boolean isRequestedSessionIdFromCookie() { notImplemented(); return false; } public boolean isRequestedSessionIdFromUrl() { notImplemented(); return false; } public boolean isRequestedSessionIdFromURL() { notImplemented(); return false; } public boolean isRequestedSessionIdValid() { notImplemented(); return false; } public boolean isSecure() { notImplemented(); return false; } public boolean isUserInRole(java.lang.String arg1) { notImplemented(); return false; } public void setupRemoveAttribute(String anAttributeToRemove) { myRemoveAttributes.addExpected(anAttributeToRemove); } public void removeAttribute(String anAttributeToRemove) { myRemoveAttributes.addActual(anAttributeToRemove); } public void addExpectedSetAttribute(String attributeName, Object attributeValue) { mySetAttributes.addExpected( new MapEntry(attributeName, attributeValue)); } public void setAttribute(String attributeName, Object attributeValue) { mySetAttributes.addActual( new MapEntry(attributeName, attributeValue)); } public void setupAddParameter(String paramName, String[] values) { myParameters.putObjectToReturn(paramName, values); } public void setupAddParameter(String paramName, String value) { setupAddParameter(paramName, new String[]{value}); } public void setupAddHeader(String headerName, String value) { myHeaders.putObjectToReturn(headerName, value); } public void setupPathInfo(String pathInfo) { myPathInfo.setValue(pathInfo); } public void setupQueryString(String aQueryString) { queryString.setValue(aQueryString); } public void setupScheme(String aScheme) { scheme.setValue(aScheme); } public void setupServerName(String aServerName) { serverName.setValue(aServerName); } public StringBuffer getRequestURL() { notImplemented(); return null; } public void setCharacterEncoding(String s) { notImplemented(); } public void setupGetParameterMap(Map map) { this.parameterMap.setValue(map); } public Map getParameterMap() { return (Map) parameterMap.getValue(); } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/servlet/MockHttpServletResponse.java0000644000175000017500000001403307566756712031565 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.*; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; public class MockHttpServletResponse extends MockObject implements HttpServletResponse { private final ExpectationList myContentTypes = new ExpectationList("MockHttpServletResponse.setContentType"); private final ExpectationList myHeaders = new ExpectationList("MockHttpServletResponse.setHeader"); private final ExpectationCounter mySetStatusCalls = new ExpectationCounter("MockHttpServletResponse.setStatus"); private final ExpectationList myRedirects = new ExpectationList("MockHttpServletResponse.sendRedirect"); private MockServletOutputStream myOutputStream = new MockServletOutputStream(); private final ExpectationValue myErrorCode = new ExpectationValue("MockHttpServletResponse.sendError"); private final ExpectationValue myErrorMessage = new ExpectationValue("MockHttpServletResponse.sendError"); private final ExpectationValue length = new ExpectationValue("MockHttpServletResponse.length"); /** * Not Implemented */ public void addCookie(Cookie arg1) { notImplemented(); } /** * Not Implemented */ public void addDateHeader(String arg1, long arg2) { notImplemented(); } /** * Not Implemented */ public void addHeader(String arg1, String arg2) { notImplemented(); } /** * Not Implemented */ public void addIntHeader(String arg1, int arg2) { notImplemented(); } /** * Not Implemented */ public boolean containsHeader(String arg1) { notImplemented(); return false; } /** * Not Implemented */ public String encodeRedirectUrl(String arg1) { notImplemented(); return null; } /** * Not Implemented */ public String encodeRedirectURL(String arg1) { notImplemented(); return null; } /** * Not Implemented */ public String encodeUrl(String arg1) { notImplemented(); return null; } /** * Not Implemented */ public String encodeURL(String arg1) { notImplemented(); return null; } /** * Not Implemented */ public void flushBuffer() throws java.io.IOException { notImplemented(); } /** * Not Implemented */ public int getBufferSize() { notImplemented(); return 0; } /** * Not Implemented */ public String getCharacterEncoding() { notImplemented(); return null; } /** * Not Implemented */ public Locale getLocale() { notImplemented(); return null; } public ServletOutputStream getOutputStream() throws IOException { return myOutputStream; } public String getOutputStreamContents() { return myOutputStream.getContents(); } public PrintWriter getWriter() throws IOException { return new PrintWriter(myOutputStream, true); } /** * Not Implemented */ public boolean isCommitted() { notImplemented(); return false; } /** * Not Implemented */ public void reset() { notImplemented(); } /** * Not Implemented */ public void resetBuffer() { notImplemented(); } public void setExpectedError(int anErrorCode) { myErrorCode.setExpected(anErrorCode); } public void setExpectedError(int anErrorCode, String anErrorMessage) { setExpectedError(anErrorCode); myErrorMessage.setExpected(anErrorMessage); } public void setExpectedErrorNothing() { myErrorCode.setExpectNothing(); myErrorMessage.setExpectNothing(); } public void sendError(int anErrorCode) throws java.io.IOException { myErrorCode.setActual(anErrorCode); } public void sendError(int anErrorCode, String anErrorMessage) throws IOException { sendError(anErrorCode); myErrorMessage.setActual(anErrorMessage); } public void sendRedirect(String aURL) throws java.io.IOException { myRedirects.addActual(aURL); } /** * Not Implemented */ public void setBufferSize(int arg1) { notImplemented(); } public void setContentLength(int length) { this.length.setActual(length); } public void setExpectedContentLength(int length){ this.length.setExpected(length); } public void setContentType(String contentType) { myContentTypes.addActual(contentType); } /** * Not Implemented */ public void setDateHeader(String arg1, long arg2) { notImplemented(); } public void setExpectedContentType(String contentType) { myContentTypes.addExpected(contentType); } public void setExpectedHeader(String key, String value) { myHeaders.addExpected(new MapEntry(key, value)); } public void setExpectedRedirect(String aURL) throws IOException { myRedirects.addExpected(aURL); } public void setExpectedSetStatusCalls(int callCount) { mySetStatusCalls.setExpected(callCount); } public void setHeader(String key, String value) { myHeaders.addActual(new MapEntry(key, value)); } /** * Not Implemented */ public void setIntHeader(String arg1, int arg2) { notImplemented(); } /** * Not Implemented */ public void setLocale(Locale arg1) { notImplemented(); } public void setStatus(int status) { mySetStatusCalls.inc(); } /** * Not Implemented */ public void setStatus(int arg1, String arg2) { notImplemented(); } public void setupOutputStream(MockServletOutputStream anOutputStream) { myOutputStream = anOutputStream; } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/servlet/MockHttpSession.java0000644000175000017500000000550107654163235030033 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.*; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; import java.util.Enumeration; public class MockHttpSession extends MockObject implements HttpSession, Verifiable { private ExpectationSet myAttributes = new ExpectationSet("session attributes"); private ExpectationSet myRemovedAttributes = new ExpectationSet("removed session attributes"); private ReturnObjectBag myAttributeValues = new ReturnObjectBag("attributes"); private Enumeration attributeNames; private ServletContext servletContext; public Object getAttribute(String anAttributeName) { return myAttributeValues.getNextReturnObject(anAttributeName); } public void setupGetAttributeNames(Enumeration attributeNames) { this.attributeNames = attributeNames; } public Enumeration getAttributeNames() { return attributeNames; } public long getCreationTime() { notImplemented(); return 0; } public String getId() { notImplemented(); return null; } public long getLastAccessedTime() { notImplemented(); return 0; } public int getMaxInactiveInterval() { notImplemented(); return 0; } public HttpSessionContext getSessionContext() { notImplemented(); return null; } public void setupServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public ServletContext getServletContext() { return servletContext; } public Object getValue(String arg1) { notImplemented(); return null; } public String[] getValueNames() { notImplemented(); return null; } public void invalidate() { notImplemented(); } public boolean isNew() { notImplemented(); return false; } public void putValue(String arg1, Object arg2) { notImplemented(); } public void setExpectedRemoveAttribute(String anAttributeName){ myRemovedAttributes.addExpected(anAttributeName); } public void removeAttribute(String anAttributeName) { myRemovedAttributes.addActual(anAttributeName); } public void removeValue(String arg1) { notImplemented(); } public void setupGetAttribute(String key, Object value){ myAttributeValues.putObjectToReturn(key, value); } public void setAttribute(String aKey, Object aValue) { myAttributes.addActual(new MapEntry(aKey, aValue)); } public void setExpectedAttribute(String aKey, Object aValue) { myAttributes.addExpected(new MapEntry(aKey, aValue)); } public void setMaxInactiveInterval(int arg1) { notImplemented(); } } mockobjects-0.09/src/j2ee/1.3/com/mockobjects/sql/0000755000175000017500000000000010117310266023167 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.3/com/mockobjects/sql/MockDataSource.java0000644000175000017500000000071307532724773026722 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; /** * Empty implementation of CommonMockDataSource. * Implementations for later releases of Java (e.g. 1.4) * may include additional members. * @see javax.sql.DataSource * @author Ted Husted * @version $Revision: 1.1 $ $Date: 2002/08/27 16:34:03 $ */ public class MockDataSource extends CommonMockDataSource{ } mockobjects-0.09/src/j2ee/1.4/0000755000175000017500000000000010117310266017310 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.4/com/0000755000175000017500000000000010117310266020066 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.4/com/mockobjects/0000755000175000017500000000000010117310266022371 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.4/com/mockobjects/sql/0000755000175000017500000000000010117310266023170 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/1.4/com/mockobjects/sql/MockDataSource.java0000644000175000017500000000067207532724774026730 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; /** * Empty implementation of CommonMockDataSource. * Implementations for later releases of Java * may include additional members. * @see javax.sql.DataSource * @author Ted Husted * @version $Revision: 1.1 $ $Date: 2002/08/27 16:34:04 $ */ public class MockDataSource extends CommonMockDataSource{ } mockobjects-0.09/src/j2ee/common/0000755000175000017500000000000010117310266020276 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/alt/0000755000175000017500000000000010117310266021056 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/alt/javax/0000755000175000017500000000000010117310266022167 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/alt/javax/mail/0000755000175000017500000000000010117310266023111 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/alt/javax/mail/internet/0000755000175000017500000000000010117310266024741 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/alt/javax/mail/internet/MimeMessage.java0000755000175000017500000000464607504121234030016 0ustar craftermcrafterm00000000000000package alt.javax.mail.internet; import alt.javax.mail.Message; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.search.SearchTerm; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Enumeration; public interface MimeMessage extends Message { void setRecipient(javax.mail.Message.RecipientType type, Address address) throws MessagingException; void addRecipient(javax.mail.Message.RecipientType type, Address address) throws MessagingException; void setFlag(Flags.Flag flag, boolean b) throws MessagingException; int getMessageNumber(); Folder getFolder(); boolean isExpunged(); boolean match(SearchTerm term) throws MessagingException; Address[] getAllRecipients() throws MessagingException; void setRecipients(javax.mail.Message.RecipientType type, String s) throws MessagingException; void addRecipients(javax.mail.Message.RecipientType type, String s) throws MessagingException; Address[] getReplyTo() throws MessagingException; void setReplyTo(Address[] addresses) throws MessagingException; void setSubject(String s, String s1) throws MessagingException; String getEncoding() throws MessagingException; String getContentID() throws MessagingException; void setContentID(String s) throws MessagingException; String getContentMD5() throws MessagingException; void setContentMD5(String s) throws MessagingException; void setDescription(String s, String s1) throws MessagingException; String[] getContentLanguage() throws MessagingException; void setContentLanguage(String[] strings) throws MessagingException; String getMessageID() throws MessagingException; InputStream getRawInputStream() throws MessagingException; void setText(String s, String s1) throws MessagingException; void writeTo(OutputStream stream, String[] strings) throws IOException, MessagingException; String getHeader(String s, String s1) throws MessagingException; void addHeaderLine(String s) throws MessagingException; Enumeration getAllHeaderLines() throws MessagingException; Enumeration getMatchingHeaderLines(String[] strings) throws MessagingException; Enumeration getNonMatchingHeaderLines(String[] strings) throws MessagingException; boolean isSet(Flags.Flag flag) throws MessagingException; } mockobjects-0.09/src/j2ee/common/alt/javax/mail/internet/MimeMessageFactory.java0000644000175000017500000000032107504121235031326 0ustar craftermcrafterm00000000000000package alt.javax.mail.internet; import alt.javax.mail.internet.MimeMessage; import alt.javax.mail.Session; public interface MimeMessageFactory { public MimeMessage createMimeMessage(Session session); } mockobjects-0.09/src/j2ee/common/alt/javax/mail/Message.java0000755000175000017500000000576407504121231025355 0ustar craftermcrafterm00000000000000package alt.javax.mail; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Flags; import javax.mail.Multipart; import java.util.Date; import java.util.Enumeration; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.ObjectStreamException; public interface Message { javax.mail.Message getRealMessage(); Address[] getFrom() throws MessagingException; void setFrom() throws MessagingException; void setFrom(Address address) throws MessagingException; void addFrom(Address[] addresses) throws MessagingException; Address[] getRecipients(javax.mail.Message.RecipientType type) throws MessagingException; void setRecipients(javax.mail.Message.RecipientType type, Address[] addresses) throws MessagingException; void addRecipients(javax.mail.Message.RecipientType type, Address[] addresses) throws MessagingException; String getSubject() throws MessagingException; void setSubject(String s) throws MessagingException; Date getSentDate() throws MessagingException; void setSentDate(Date date) throws MessagingException; Date getReceivedDate() throws MessagingException; Flags getFlags() throws MessagingException; void setFlags(Flags flags, boolean b) throws MessagingException; Message reply(boolean b) throws MessagingException; void saveChanges() throws MessagingException; int getSize() throws MessagingException; int getLineCount() throws MessagingException; String getContentType() throws MessagingException; boolean isMimeType(String s) throws MessagingException; String getDisposition() throws MessagingException; void setDisposition(String s) throws MessagingException; String getDescription() throws MessagingException; void setDescription(String s) throws MessagingException; String getFileName() throws MessagingException; void setFileName(String s) throws MessagingException; InputStream getInputStream() throws IOException, MessagingException; javax.activation.DataHandler getDataHandler() throws MessagingException; Object getContent() throws IOException, MessagingException; void setDataHandler(javax.activation.DataHandler handler) throws MessagingException; void setContent(Object o, String s) throws MessagingException; void setText(String s) throws MessagingException; void setContent(Multipart multipart) throws MessagingException; void writeTo(OutputStream stream) throws IOException, MessagingException; String[] getHeader(String s) throws MessagingException; void setHeader(String s, String s1) throws MessagingException; void addHeader(String s, String s1) throws MessagingException; void removeHeader(String s) throws MessagingException; Enumeration getAllHeaders() throws MessagingException; Enumeration getMatchingHeaders(String[] strings) throws MessagingException; Enumeration getNonMatchingHeaders(String[] strings) throws MessagingException; } mockobjects-0.09/src/j2ee/common/alt/javax/mail/Service.java0000644000175000017500000000132207463547116025372 0ustar craftermcrafterm00000000000000package alt.javax.mail; import javax.mail.URLName; import javax.mail.MessagingException; import javax.mail.event.ConnectionListener; public interface Service { public void connect() throws MessagingException; public void connect(String host, String user, String password) throws MessagingException; public void connect(String host, int port, String user, String password) throws MessagingException; public boolean isConnected(); public void close() throws MessagingException; public URLName getURLName(); public void addConnectionListener(ConnectionListener connectionListener); public void removeConnectionListener(ConnectionListener connectionListener); public String toString(); } mockobjects-0.09/src/j2ee/common/alt/javax/mail/Session.java0000644000175000017500000000416207463547116025422 0ustar craftermcrafterm00000000000000package alt.javax.mail; import java.util.Properties; import javax.mail.NoSuchProviderException; import javax.mail.MessagingException; import javax.mail.Authenticator; import javax.mail.Provider; import javax.mail.Store; import javax.mail.URLName; import javax.mail.Folder; import alt.javax.mail.Transport; import javax.mail.Address; import javax.mail.PasswordAuthentication; public interface Session { public Session getInstance(Properties props, Authenticator authenticator); public Session getInstance(Properties props); public Session getDefaultInstance(Properties props, Authenticator authenticator); public Session getDefaultInstance(Properties props); public void setDebug(boolean debug); public boolean getDebug(); public Provider getProviders()[]; public Provider getProvider(String protocol) throws NoSuchProviderException; public void setProvider(Provider provider) throws NoSuchProviderException; public Store getStore() throws NoSuchProviderException; public Store getStore(String protocol) throws NoSuchProviderException; public Store getStore(URLName url) throws NoSuchProviderException; public Store getStore(Provider provider) throws NoSuchProviderException; public Folder getFolder(URLName url) throws MessagingException; public Transport getTransport() throws NoSuchProviderException; public Transport getTransport(String protocol) throws NoSuchProviderException; public Transport getTransport(URLName url) throws NoSuchProviderException; public Transport getTransport(Provider provider) throws NoSuchProviderException; public Transport getTransport(Address address) throws NoSuchProviderException; public void setPasswordAuthentication(URLName url, PasswordAuthentication pw); public PasswordAuthentication getPasswordAuthentication(URLName url); public PasswordAuthentication requestPasswordAuthentication(java.net.InetAddress addr, int port, String protocol, String prompt, String defaultUserName); public Properties getProperties(); public String getProperty(String name); public javax.mail.Session getWrappedSession(); } mockobjects-0.09/src/j2ee/common/alt/javax/mail/Transport.java0000644000175000017500000000116107504121233025747 0ustar craftermcrafterm00000000000000package alt.javax.mail; import alt.javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Address; import javax.mail.event.TransportListener; public interface Transport extends Service { public void send(Message message) throws MessagingException; public void send(Message message, Address[] addresses) throws MessagingException; public void sendMessage(Message message, Address[] addresses) throws MessagingException; public void addTransportListener(TransportListener transportListener); public void removeTransportListener(TransportListener transportListener); } mockobjects-0.09/src/j2ee/common/com/0000755000175000017500000000000010117310266021054 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/0000755000175000017500000000000010117310266023357 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/0000755000175000017500000000000010117310266024150 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockConnection.java0000644000175000017500000000410507635626434027746 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import javax.jms.Connection; import javax.jms.ConnectionMetaData; import javax.jms.ExceptionListener; import javax.jms.JMSException; import com.mockobjects.ExpectationCounter; import com.mockobjects.MockObject; public class MockConnection extends MockObject implements Connection { protected ExpectationCounter myCloseCalls = new ExpectationCounter("CommonMockConnection.close"); protected ExpectationCounter myStartCalls = new ExpectationCounter("CommonMockConnection.start"); protected ExpectationCounter myStopCalls = new ExpectationCounter("CommonMockConnection.stop"); private JMSException myException; public void close() throws JMSException { myCloseCalls.inc(); throwExceptionIfAny(); } public String getClientID() throws JMSException { notImplemented(); return null; } public ExceptionListener getExceptionListener() throws JMSException { notImplemented(); return null; } public ConnectionMetaData getMetaData() throws JMSException { notImplemented(); return null; } public void setClientID(String clientID) throws JMSException { notImplemented(); } public void setExceptionListener(ExceptionListener listener) throws JMSException { //does nothing } public void start() throws JMSException { myStartCalls.inc(); throwExceptionIfAny(); } public void stop() throws JMSException { myStopCalls.inc(); throwExceptionIfAny(); } public void setExpectedCloseCalls(int callCount) { myCloseCalls.setExpected(callCount); } public void setExpectedStartCalls(int callCount) { myStartCalls.setExpected(callCount); } public void setExpectedStopCalls(int callCount) { myStopCalls.setExpected(callCount); } public void setupThrowException(JMSException e) { myException = e; } protected void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockMapMessage.java0000644000175000017500000000666407463536020027673 0ustar craftermcrafterm00000000000000 package com.mockobjects.jms; import com.mockobjects.ExpectationMap; import com.mockobjects.ExpectationSet; import com.mockobjects.MapEntry; import javax.jms.JMSException; import javax.jms.MapMessage; import java.util.Enumeration; /** * MockMapMessage * * @author ggalli@e-tree.com * @version $Revision: 1.1 $ */ public class MockMapMessage extends MockMessage implements MapMessage { private ExpectationSet myObjectProperties = new ExpectationSet("objectProperty"); public boolean getBoolean(String aKey) throws JMSException { notImplemented(); return false; } public byte getByte(String aKey) throws JMSException { notImplemented(); return 0; } public byte[] getBytes(String aKey) throws JMSException { notImplemented(); return new byte[]{}; } public char getChar(String aKey) throws JMSException { notImplemented(); return 0; } public double getDouble(String aKey) throws JMSException { notImplemented(); return 0; } public float getFloat(String aKey) throws JMSException { notImplemented(); return 0; } public int getInt(String aKey) throws JMSException { notImplemented(); return 0; } public long getLong(String aKey) throws JMSException { notImplemented(); return 0; } public Enumeration getMapNames() throws JMSException { notImplemented(); return null; } public Object getObject(String aKey) throws JMSException { notImplemented(); return null; } public short getShort(String aKey) throws JMSException { notImplemented(); return 0; } public String getString(String aKey) throws JMSException { notImplemented(); return null; } public boolean itemExists(String aKey) throws JMSException { notImplemented(); return false; } public void setBoolean(String aKey, boolean p) throws JMSException { notImplemented(); } public void setByte(String aKey, byte p) throws JMSException { notImplemented(); } public void setBytes(String aKey, byte[] p) throws JMSException { notImplemented(); } public void setBytes(String aKey, byte[] p, int n, int n1) throws JMSException { notImplemented(); } public void setChar(String aKey, char p) throws JMSException { notImplemented(); } public void setDouble(String aKey, double p) throws JMSException { notImplemented(); } public void setFloat(String aKey, float p) throws JMSException { notImplemented(); } public void setInt(String aKey, int p) throws JMSException { notImplemented(); } public void setLong(String aKey, long p) throws JMSException { notImplemented(); } public void setObject(String aKey, Object p) throws JMSException { notImplemented(); } public void setObjectProperty(String aKey, Object anObject) { myObjectProperties.addActual(new MapEntry(aKey, anObject)); } public void setShort(String aKey, short p) throws JMSException { notImplemented(); } public void setString(String aKey, String aKey1) throws JMSException { notImplemented(); } public void setExpectedObjectProperty(String aKey, Object anObject) { myObjectProperties.addExpected(new MapEntry(aKey, anObject)); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockMessage.java0000644000175000017500000001304007635626434027231 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public abstract class MockMessage extends MockObject implements Message { protected ExpectationCounter myAcknowledgeCount = new ExpectationCounter("MockMessage.acknowledge"); protected ExpectationValue myJMSReplyTo = new ExpectationValue("MockMessage.setJMSReplyTo"); protected ExpectationCounter mySetJMSCorrelationIDCalls = new ExpectationCounter("MockMessage.setJMSCorrelationID"); private JMSException myException; /** * Used for both messageID and correlationID */ private final ReturnValue myJMSMessageID = new ReturnValue("messageID / correlationID"); public void acknowledge() throws JMSException { myAcknowledgeCount.inc(); } public void setExpectedAcknowledgeCalls(int calls) { myAcknowledgeCount.setExpected(calls); } public void clearBody() { notImplemented(); } public void clearProperties() { notImplemented(); } public boolean getBooleanProperty(String name) { notImplemented(); return false; } public byte getByteProperty(String name) { notImplemented(); return 0; } public double getDoubleProperty(String name) { notImplemented(); return 0; } public float getFloatProperty(String name) { notImplemented(); return 0; } public int getIntProperty(String name) { notImplemented(); return 0; } public String getJMSCorrelationID() { return (String)myJMSMessageID.getValue(); } public byte[] getJMSCorrelationIDAsBytes() { notImplemented(); return null; } public int getJMSDeliveryMode() { notImplemented(); return 0; } public Destination getJMSDestination() { notImplemented(); return null; } public long getJMSExpiration() { notImplemented(); return 0; } public String getJMSMessageID() { return (String)myJMSMessageID.getValue(); } public int getJMSPriority() { notImplemented(); return 0; } public boolean getJMSRedelivered() { notImplemented(); return false; } public Destination getJMSReplyTo() { notImplemented(); return null; } public long getJMSTimestamp() { notImplemented(); return 0; } public String getJMSType() { notImplemented(); return null; } public long getLongProperty(String name) { notImplemented(); return 0; } public Object getObjectProperty(String name) { notImplemented(); return null; } public java.util.Enumeration getPropertyNames() { notImplemented(); return null; } public short getShortProperty(String name) { notImplemented(); return 0; } public String getStringProperty(String name) { notImplemented(); return null; } public boolean propertyExists(String name) { notImplemented(); return false; } public void setBooleanProperty(String name, boolean value) { notImplemented(); } public void setByteProperty(String name, byte value) { notImplemented(); } public void setDoubleProperty(String name, double value) { notImplemented(); } public void setFloatProperty(String name, float value) { notImplemented(); } public void setIntProperty(String name, int value) { notImplemented(); } public void setJMSCorrelationID(String jmsCorrelationID) { mySetJMSCorrelationIDCalls.inc(); } public void setJMSCorrelationIDAsBytes(byte[] correlationID) { notImplemented(); } public void setJMSDeliveryMode(int deliveryMode) { notImplemented(); } public void setJMSDestination(Destination destination) { notImplemented(); } public void setJMSExpiration(long expiration) { notImplemented(); } public void setJMSMessageID(String id) { notImplemented(); } public void setJMSPriority(int priority) { notImplemented(); } public void setJMSRedelivered(boolean redelivered) { notImplemented(); } public void setJMSReplyTo(Destination replyTo) throws JMSException { throwExceptionIfAny(); myJMSReplyTo.setActual(replyTo); } public void setJMSTimestamp(long timestamp) { notImplemented(); } public void setJMSType(String type) { notImplemented(); } public void setLongProperty(String name, long value) { notImplemented(); } public void setObjectProperty(String name, Object value) { notImplemented(); } public void setShortProperty(String name, short value) { notImplemented(); } public void setStringProperty(String name, String value) { notImplemented(); } public void setExpectedJMSReplyTo(Destination expectedJMSReplyTo) { myJMSReplyTo.setExpected(expectedJMSReplyTo); } public void setExpectedSetJMSCorrelationIDCalls(int callCount) { mySetJMSCorrelationIDCalls.setExpected(callCount); } public void setupJMSMessageID(String jmsMessageID) { myJMSMessageID.setValue(jmsMessageID); } public void setupThrowException(JMSException e) { myException = e; } protected void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockMessageConsumer.java0000644000175000017500000000603507635626434030753 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockMessageConsumer extends MockObject implements MessageConsumer{ private final ReturnValue myMessage = new ReturnValue("message"); private boolean myExpiresOnTimeout = false; private JMSException myException; protected ExpectationCounter myCloseCalls = new ExpectationCounter("MockMessageConsumer.close"); protected ExpectationCounter myReceiveCalls = new ExpectationCounter("MockMessageConsumer.receive"); private ExpectationValue messageListener = new ExpectationValue("messageListener"); private final ExpectationValue timeout = new ExpectationValue("timeout"); public void setExpectedMessageListener(MessageListener messageListener){ this.messageListener.setExpected(messageListener); } public void close() throws JMSException { throwExceptionIfAny(); myCloseCalls.inc(); } public MessageListener getMessageListener() throws JMSException { notImplemented(); return null; } public String getMessageSelector() throws JMSException { notImplemented(); return null; } public Message receive() throws JMSException { throwExceptionIfAny(); myReceiveCalls.inc(); if (myExpiresOnTimeout) { synchronized(this) { try { wait(); } catch (InterruptedException e) { throw new junit.framework.AssertionFailedError( "Thread interrupted"); } } } return (Message)myMessage.getValue(); } public Message receive(long timeout) throws JMSException { this.timeout.setActual(timeout); throwExceptionIfAny(); myReceiveCalls.inc(); if (myExpiresOnTimeout) { return null; } else { return (Message)myMessage.getValue(); } } public void setExpectedTimeout(long timeout){ this.timeout.setExpected(timeout); } public Message receiveNoWait() throws JMSException { throwExceptionIfAny(); myReceiveCalls.inc(); return (Message)myMessage.getValue(); } public void setExpectedCloseCalls(int callCount) { myCloseCalls.setExpected(callCount); } public void setExpectedReceiveCalls(int callCount) { myReceiveCalls.setExpected(callCount); } public void setupReceivedMessage(Message message) { myMessage.setValue(message); } public void setupExpiresOnTimeout(boolean expiresOnTimeout) { myExpiresOnTimeout = expiresOnTimeout; } public void setupThrowException(JMSException e) { myException = e; } public void setMessageListener(MessageListener messageListener) throws JMSException{ this.messageListener.setActual(messageListener); } protected void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockMessageProducer.java0000644000175000017500000000321407635626434030737 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public abstract class MockMessageProducer extends MockObject implements MessageProducer { protected final ExpectationCounter myCloseCalls = new ExpectationCounter("MockMessageConsumer.close"); private JMSException myException; public void close() throws JMSException { myCloseCalls.inc(); } public int getDeliveryMode() throws JMSException { notImplemented(); return 0; } public boolean getDisableMessageID() throws JMSException { notImplemented(); return false; } public boolean getDisableMessageTimestamp() throws JMSException { notImplemented(); return false; } public int getPriority() throws JMSException { notImplemented(); return 0; } public long getTimeToLive() throws JMSException { notImplemented(); return 0l; } public void setDeliveryMode(int deliveryMode) throws JMSException { notImplemented(); } public void setDisableMessageID(boolean value) throws JMSException { notImplemented(); } public void setDisableMessageTimestamp(boolean value) throws JMSException { notImplemented(); } public void setPriority(int defaultPriority) throws JMSException { notImplemented(); } public void setTimeToLive(long timeToLive) throws JMSException { notImplemented(); } public void setExpectedCloseCalls(int callCount) { myCloseCalls.setExpected(callCount); } public void setupThrowException(JMSException e) { myException = e; } protected void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockMessagePublisher.java0000644000175000017500000000250307461037771031106 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockMessagePublisher extends MockObject implements MessageProducer{ public void close() throws JMSException{ notImplemented(); } public int getDeliveryMode() throws JMSException{ notImplemented(); return -1; } public boolean getDisableMessageID() throws JMSException{ notImplemented(); return false; } public boolean getDisableMessageTimestamp() throws JMSException{ notImplemented(); return false; } public int getPriority() throws JMSException{ notImplemented(); return -1; } public long getTimeToLive() throws JMSException{ notImplemented(); return -1; } public void setDeliveryMode(int deliveryMode) throws JMSException{ notImplemented(); } public void setDisableMessageID(boolean disableMessageId) throws JMSException{ notImplemented(); } public void setDisableMessageTimestamp(boolean disableMessageTimeStamp) throws JMSException{ notImplemented(); } public void setPriority(int priority) throws JMSException{ notImplemented(); } public void setTimeToLive(long timeToLive) throws JMSException{ notImplemented(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockObjectMessage.java0000644000175000017500000000111007635626434030353 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.ReturnValue; import java.io.*; import javax.jms.*; public class MockObjectMessage extends MockMessage implements ObjectMessage{ private final ReturnValue objectToReturn = new ReturnValue("object"); public void setupGetObject(Serializable objectToReturn){ this.objectToReturn.setValue(objectToReturn); } public Serializable getObject() throws JMSException{ return (Serializable)objectToReturn.getValue(); } public void setObject(Serializable serialisable) throws JMSException{ } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockQueue.java0000644000175000017500000000157107635626434026737 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.MockObject; import com.mockobjects.ReturnValue; import javax.jms.JMSException; import javax.jms.Queue; public class MockQueue extends MockObject implements Queue { private JMSException myException; private final ReturnValue myName = new ReturnValue("name"); public String getQueueName() throws JMSException { throwExceptionIfAny(); return (String)myName.getValue(); } public void setupGetQueueName(final String name){ myName.setValue(name); } public String toString() { return this.getClass().getName() + ", " + myName.getValue(); } public void setupThrowException(JMSException e) { myException = e; } protected void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockQueueConnection.java0000644000175000017500000000143207635626434030753 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockQueueConnection extends MockConnection implements QueueConnection { private final ReturnValue myQueueSession = new ReturnValue("queue session"); public MockQueueConnection() { } public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool, int mexMessages) throws JMSException { notImplemented(); return null; } public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException { throwExceptionIfAny(); return (QueueSession)myQueueSession.getValue(); } public void setupQueueSession(QueueSession queueSession) { myQueueSession.setValue(queueSession); } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockQueueConnectionFactory.java0000644000175000017500000000306307635626434032305 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockQueueConnectionFactory extends MockObject implements QueueConnectionFactory { private final ExpectationValue myUserName = new ExpectationValue("MockQueueConnectionFactory.createQueueConnection"); private final ExpectationValue myPassword = new ExpectationValue("MockQueueConnectionFactory.createQueueConnection"); private JMSException myException; private final ReturnValue myQueueConnection = new ReturnValue("queue connection"); public QueueConnection createQueueConnection() throws JMSException { throwExceptionIfAny(); return (QueueConnection) myQueueConnection.getValue(); } public QueueConnection createQueueConnection(String userName, String password) throws JMSException { throwExceptionIfAny(); myUserName.setActual(userName); myPassword.setActual(password); return (QueueConnection) myQueueConnection.getValue(); } public void setExpectedUserName(String userName) { myUserName.setExpected(userName); } public void setExpectedPassword(String password) { myPassword.setExpected(password); } public void setupQueueConnection(QueueConnection queueConnection) { myQueueConnection.setValue(queueConnection); } public void setupThrowException(JMSException e) { myException = e; } private void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockQueueReceiver.java0000644000175000017500000000035407625431235030412 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockQueueReceiver extends MockMessageConsumer implements QueueReceiver { public Queue getQueue() { notImplemented(); return null; } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockQueueSender.java0000644000175000017500000000172107435470341030065 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockQueueSender extends MockMessageProducer implements QueueSender { protected ExpectationCounter mySendCalls = new ExpectationCounter("MockQueueSender.send"); public MockQueueSender() { } public Queue getQueue() throws JMSException { notImplemented(); return null; } public void send(Message message) throws JMSException { mySendCalls.inc(); throwExceptionIfAny(); } public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException { notImplemented(); } public void send(Queue queue, Message message) throws JMSException { notImplemented(); } public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException { notImplemented(); } public void setExpectedSendCalls(int callCount) { mySendCalls.setExpected(callCount); } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockQueueSession.java0000644000175000017500000000626107635626434030304 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockQueueSession extends MockSession implements QueueSession { private final ExpectationValue mySendingQueue = new ExpectationValue("MockQueueSession.createSender"); private final ExpectationValue myReceivingQueue = new ExpectationValue("MockQueueSession.createReceiver"); private final ExpectationValue messageSelector = new ExpectationValue("message selector"); private final ExpectationValue queue = new ExpectationValue("queue"); private final ReturnValue queueToReturn = new ReturnValue("queue"); private final ReturnValue myReceiver = new ReturnValue("reciever"); private final ReturnValue mySender = new ReturnValue("reciever"); private final ReturnValue myTemporaryQueue = new ReturnValue("reciever"); private final ReturnValue queueBrowser = new ReturnValue("queue browser"); public QueueBrowser createBrowser(Queue queue) throws JMSException { this.queue.setActual(queue); return (QueueBrowser) queueBrowser.getValue(); } public void setExpectedQueue(Queue queue) { this.queue.setExpected(queue); } public void setupCreateQueueBrowser(QueueBrowser browser) { this.queueBrowser.setValue(browser); } public QueueBrowser createBrowser(Queue queue, String messageSelector) throws JMSException { notImplemented(); return null; } public void setupCreateQueue(Queue queue) { this.queueToReturn.setValue(queue); } public Queue createQueue(String queueName) throws JMSException { throwExceptionIfAny(); return (Queue) queueToReturn.getValue(); } public QueueReceiver createReceiver(Queue queue) throws JMSException { throwExceptionIfAny(); myReceivingQueue.setActual(queue); return (QueueReceiver) myReceiver.getValue(); } public QueueReceiver createReceiver(Queue queue, String messageSelector) throws JMSException { this.messageSelector.setActual(messageSelector); myReceivingQueue.setActual(queue); throwExceptionIfAny(); return (QueueReceiver) myReceiver.getValue(); } public QueueSender createSender(Queue queue) throws JMSException { mySendingQueue.setActual(queue); throwExceptionIfAny(); return (QueueSender) mySender.getValue(); } public TemporaryQueue createTemporaryQueue() throws JMSException { throwExceptionIfAny(); return (TemporaryQueue) myTemporaryQueue.getValue(); } public void setExpectedSendingQueue(Queue queue) { mySendingQueue.setExpected(queue); } public void setExpectedReceivingQueue(Queue queue) { myReceivingQueue.setExpected(queue); } public void setupReceiver(QueueReceiver receiver) { myReceiver.setValue(receiver); } public void setupSender(QueueSender sender) { mySender.setValue(sender); } public void setupTemporaryQueue(MockTemporaryQueue temporaryQueue) { myTemporaryQueue.setValue(temporaryQueue); } public void setExpectedMessageSelector(String messageSelector) { this.messageSelector.setExpected(messageSelector); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockSession.java0000644000175000017500000000575607435762173027306 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import java.io.Serializable; import javax.jms.*; public class MockSession extends MockObject implements Session { protected ExpectationCounter myCloseCalls = new ExpectationCounter("MockSession.close"); protected ExpectationCounter myCreateTextMessageCalls = new ExpectationCounter("MockSession.createTextMessage"); private TextMessage myTextMessage = new MockTextMessage(); private JMSException myException; private ObjectMessage objectMessageToReturn; public void setupCreateObjectMessage(ObjectMessage objectMessageToReturn){ this.objectMessageToReturn = objectMessageToReturn; } public ObjectMessage createObjectMessage() throws JMSException { return objectMessageToReturn; } public ObjectMessage createObjectMessage(Serializable object) throws JMSException { return objectMessageToReturn; } public void rollback() throws JMSException { notImplemented(); } public void setupTextMessage(TextMessage textMessage) { myTextMessage = textMessage; } public BytesMessage createBytesMessage() throws JMSException { notImplemented(); return null; } public MapMessage createMapMessage() throws JMSException { notImplemented(); return null; } public Message createMessage() throws JMSException { notImplemented(); return null; } public boolean getTransacted() throws JMSException { notImplemented(); return false; } public void recover() throws JMSException { notImplemented(); } public void close() throws JMSException { throwExceptionIfAny(); myCloseCalls.inc(); } public void commit() throws JMSException { notImplemented(); } public void setMessageListener(MessageListener listener) throws JMSException { notImplemented(); } public void setExpectedCloseCalls(int callCount) { myCloseCalls.setExpected(callCount); } public void setExpectedCreateTextMessageCalls(int callCount) { myCreateTextMessageCalls.setExpected(callCount); } public StreamMessage createStreamMessage() throws JMSException { notImplemented(); return null; } public TextMessage createTextMessage() throws JMSException { myCreateTextMessageCalls.inc(); return myTextMessage; } public TextMessage createTextMessage(String text) throws JMSException { myTextMessage.setText(text); return myTextMessage; } public MessageListener getMessageListener() throws JMSException { notImplemented(); return null; } public void run() { notImplemented(); } public void setupThrowException(JMSException e) { myException = e; } protected void throwExceptionIfAny() throws JMSException { if (null != myException) { throw myException; } } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTemporaryQueue.java0000644000175000017500000000104407635626434030635 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import javax.jms.JMSException; import javax.jms.TemporaryQueue; import com.mockobjects.ExpectationCounter; public class MockTemporaryQueue extends MockQueue implements TemporaryQueue { private final ExpectationCounter myDeleteCalls = new ExpectationCounter("MockTemporaryQueue.delete"); public void delete() throws JMSException { myDeleteCalls.inc(); throwExceptionIfAny(); } public void setExpectedDeleteCalls(int callCount) { myDeleteCalls.setExpected(callCount); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTextMessage.java0000644000175000017500000000122607635626434030101 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockTextMessage extends MockMessage implements TextMessage { private final ExpectationValue myExpectedText = new ExpectationValue("MockTextMessage.setText"); private final ReturnValue myText = new ReturnValue("text"); public void setText(String text) { myExpectedText.setActual(text); } public String getText() { return (String)myText.getValue(); } public void setupGetText(String text) { myText.setValue(text); } public void setExpectedText(String text) { myExpectedText.setExpected(text); } }mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTopic.java0000644000175000017500000000037007461037771026722 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockTopic extends MockObject implements Topic{ public String getTopicName() throws JMSException{ notImplemented(); return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTopicConnection.java0000644000175000017500000000207507635626434030751 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockTopicConnection extends MockConnection implements TopicConnection { private final ReturnValue topicSessionToReturn = new ReturnValue("topic session"); public void setupCreateTopicSession(TopicSession topicSessionToReturn) { this.topicSessionToReturn.setValue(topicSessionToReturn); } public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { notImplemented(); return null; } public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException { notImplemented(); return null; } public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException { return (TopicSession)topicSessionToReturn.getValue(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTopicConnectionFactory.java0000644000175000017500000000141007635626434032271 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockTopicConnectionFactory extends MockObject implements TopicConnectionFactory{ private final ReturnValue topicConnectionToReturn = new ReturnValue("topic connection"); public void setupCreateTopicConnection( TopicConnection topicConnectionToReturn){ this.topicConnectionToReturn.setValue(topicConnectionToReturn); } public TopicConnection createTopicConnection() throws JMSException{ return (TopicConnection)topicConnectionToReturn.getValue(); } public TopicConnection createTopicConnection(String userName, String password) throws JMSException{ return (TopicConnection)topicConnectionToReturn.getValue(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTopicPublisher.java0000644000175000017500000000177307461037771030610 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import javax.jms.*; import com.mockobjects.*; public class MockTopicPublisher extends MockMessagePublisher implements TopicPublisher{ private ExpectationValue message = new ExpectationValue("message"); public void setExpectedMessage(Message message){ this.message.setExpected(message); } public Topic getTopic() throws JMSException{ notImplemented(); return null; } public void publish(Message message) throws JMSException{ this.message.setActual(message); } public void publish(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException{ this.message.setActual(message); } public void publish(Topic topic, Message message) throws JMSException{ this.message.setActual(message); } public void publish(Topic topic, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException{ this.message.setActual(message); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTopicSession.java0000644000175000017500000000502407635626434030272 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import com.mockobjects.*; import javax.jms.*; public class MockTopicSession extends MockSession implements TopicSession{ private final ReturnValue topicToReturn = new ReturnValue("topic"); private ExpectationValue topicName = new ExpectationValue("topicName"); private ExpectationCounter createTopicCalls = new ExpectationCounter("createTopicCalls"); private final ReturnValue topicPublisherToReturn = new ReturnValue("topic publisher"); private final ReturnValue topicSubscriberToReturn = new ReturnValue("topic subscriber"); public void setupCreateTopic(Topic topicToReturn){ this.topicToReturn.setValue(topicToReturn); } public void setExpectedTopicName(String topicName){ this.topicName.setExpected(topicName); } public void setupCreateTopicCalls(int createTopicCalls){ this.createTopicCalls.setExpected(createTopicCalls); } public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException{ return (TopicSubscriber)topicSubscriberToReturn.getValue(); } public TopicSubscriber createDurableSubscriber(Topic topic, String name, String messsageSelecter, boolean noLocal) throws JMSException{ return (TopicSubscriber)topicSubscriberToReturn.getValue(); } public void setupCreatePublisher(TopicPublisher topicPublisherToReturn){ this.topicPublisherToReturn.setValue(topicPublisherToReturn); } public TopicPublisher createPublisher(Topic topic) throws JMSException{ return (TopicPublisher)topicPublisherToReturn.getValue(); } public void setupTopicSubscriber(TopicSubscriber topicSubscriberToReturn){ this.topicSubscriberToReturn.setValue(topicSubscriberToReturn); } public TopicSubscriber createSubscriber(Topic topic) throws JMSException{ return (TopicSubscriber)topicSubscriberToReturn.getValue(); } public TopicSubscriber createSubscriber(Topic topic, String messsageSelecter, boolean noLocal) throws JMSException{ return (TopicSubscriber)topicSubscriberToReturn.getValue(); } public TemporaryTopic createTemporaryTopic() throws JMSException{ notImplemented(); return null; } public Topic createTopic(String topicName) throws JMSException{ this.topicName.setActual(topicName); this.createTopicCalls.inc(); return (Topic)topicToReturn.getValue(); } public void unsubscribe(String topicName) throws JMSException{ notImplemented(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/jms/MockTopicSubscriber.java0000644000175000017500000000057407461037771030754 0ustar craftermcrafterm00000000000000package com.mockobjects.jms; import javax.jms.*; import com.mockobjects.*; public class MockTopicSubscriber extends MockMessageConsumer implements TopicSubscriber{ public boolean getNoLocal() throws JMSException{ notImplemented(); return false; } public Topic getTopic() throws JMSException{ notImplemented(); return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/0000755000175000017500000000000010117310266024301 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/internet/0000755000175000017500000000000010117310266026131 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/internet/MockMimeMessage.java0000755000175000017500000001136607504121236032017 0ustar craftermcrafterm00000000000000package com.mockobjects.mail.internet; import alt.javax.mail.internet.MimeMessage; import com.mockobjects.ExpectationList; import com.mockobjects.mail.MockMessage; import javax.mail.Address; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.MessagingException; import javax.mail.search.SearchTerm; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; public class MockMimeMessage extends MockMessage implements MimeMessage { private final ExpectationList myAddresses = new ExpectationList("addresses"); private final ExpectationList myRecipientTypes = new ExpectationList("recipient types"); public void setRecipient(javax.mail.Message.RecipientType type, Address address) throws MessagingException { notImplemented(); } public void setExpectedAddRecipient(javax.mail.Message.RecipientType aType, Address anAddress) { myAddresses.addExpected(anAddress); myRecipientTypes.addExpected(aType); } public void addRecipient(javax.mail.Message.RecipientType aType, Address anAddress) throws MessagingException { myAddresses.addActual(anAddress); myRecipientTypes.addActual(aType); } public void setFlag(Flags.Flag flag, boolean b) throws MessagingException { notImplemented(); } public int getMessageNumber() { notImplemented(); return 0; } public String getBody() { notImplemented(); return null; } public Folder getFolder() { notImplemented(); return null; } public void setBody(String messageText) { notImplemented(); } public boolean isExpunged() { notImplemented(); return false; } public boolean match(SearchTerm term) throws MessagingException { notImplemented(); return false; } public Address[] getAllRecipients() throws MessagingException { notImplemented(); return new Address[0]; } public void setRecipients(javax.mail.Message.RecipientType type, String s) throws MessagingException { notImplemented(); } public void addRecipients(javax.mail.Message.RecipientType type, String s) throws MessagingException { notImplemented(); } public Address[] getReplyTo() throws MessagingException { notImplemented(); return new Address[0]; } public void setReplyTo(Address[] addresses) throws MessagingException { notImplemented(); } public void setSubject(String s, String s1) throws MessagingException { notImplemented(); } public String getEncoding() throws MessagingException { notImplemented(); return null; } public String getContentID() throws MessagingException { notImplemented(); return null; } public void setContentID(String s) throws MessagingException { notImplemented(); } public String getContentMD5() throws MessagingException { notImplemented(); return null; } public void setContentMD5(String s) throws MessagingException { notImplemented(); } public void setDescription(String s, String s1) throws MessagingException { notImplemented(); } public String[] getContentLanguage() throws MessagingException { notImplemented(); return new String[0]; } public void setContentLanguage(String[] strings) throws MessagingException { notImplemented(); } public String getMessageID() throws MessagingException { notImplemented(); return null; } public InputStream getRawInputStream() throws MessagingException { notImplemented(); return null; } public void setText(String s, String s1) throws MessagingException { notImplemented(); } public void writeTo(OutputStream stream, String[] strings) throws IOException, MessagingException { notImplemented(); } public String getHeader(String s, String s1) throws MessagingException { notImplemented(); return null; } public void addHeaderLine(String s) throws MessagingException { notImplemented(); } public Enumeration getAllHeaderLines() throws MessagingException { notImplemented(); return null; } public Enumeration getMatchingHeaderLines(String[] strings) throws MessagingException { notImplemented(); return null; } public Enumeration getNonMatchingHeaderLines(String[] strings) throws MessagingException { notImplemented(); return null; } public boolean isSet(Flags.Flag flag) throws MessagingException { notImplemented(); return false; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/internet/MockMimeMessageFactory.java0000644000175000017500000000150007635626434033350 0ustar craftermcrafterm00000000000000package com.mockobjects.mail.internet; import com.mockobjects.*; import alt.javax.mail.Session; import alt.javax.mail.internet.MimeMessageFactory; import alt.javax.mail.internet.MimeMessage; public class MockMimeMessageFactory extends MockObject implements MimeMessageFactory { private final ExpectationValue mySession = new ExpectationValue("session"); private final ReturnValue myMimeMessage = new ReturnValue("mime message"); public void setExpectedSession(Session aSession) { mySession.setExpected(aSession); } public void setupCreateMimeMessage(MimeMessage aMimeMessage) { myMimeMessage.setValue(aMimeMessage); } public MimeMessage createMimeMessage(Session aSession) { mySession.setActual(aSession); return (MimeMessage)myMimeMessage.getValue(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/MockMessage.java0000755000175000017500000001504507566757037027403 0ustar craftermcrafterm00000000000000package com.mockobjects.mail; import alt.javax.mail.Message; import javax.mail.Address; import javax.mail.MessagingException; import javax.mail.Flags; import javax.mail.Multipart; import javax.activation.DataHandler; import java.util.Date; import java.util.Enumeration; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import com.mockobjects.MockObject; import com.mockobjects.ExpectationValue; public class MockMessage extends MockObject implements Message { private final ExpectationValue myFrom = new ExpectationValue("from"); private final ExpectationValue myRecipients = new ExpectationValue("recipients"); private final ExpectationValue mySubject = new ExpectationValue("subject"); private final ExpectationValue mySentDate = new ExpectationValue("sent date"); private final ExpectationValue myText = new ExpectationValue("text"); private final ExpectationValue myContent = new ExpectationValue("content"); private final ExpectationValue myMimeType = new ExpectationValue("mime type"); public Address[] getFrom() throws MessagingException { notImplemented(); return new Address[0]; } public void setFrom() throws MessagingException { notImplemented(); } public void setExpectedFrom(Address anAddress){ myFrom.setExpected(anAddress); } public void setFrom(Address anAddress) throws MessagingException { myFrom.setActual(anAddress); } public void addFrom(Address[] addresses) throws MessagingException { notImplemented(); } public Address[] getRecipients(javax.mail.Message.RecipientType type) throws MessagingException { notImplemented(); return new Address[0]; } public void setExpectedRecipients(Address[] addresses){ myRecipients.setExpected(addresses); } public void setRecipients(javax.mail.Message.RecipientType type, Address[] addresses) throws MessagingException { myRecipients.setActual(addresses); } public void addRecipients(javax.mail.Message.RecipientType type, Address[] addresses) throws MessagingException { notImplemented(); } public String getSubject() throws MessagingException { notImplemented(); return null; } public void setSubject(String aSubject) throws MessagingException { mySubject.setActual(aSubject); } public void setExpectedSubject(String aSubject){ mySubject.setExpected(aSubject); } public Date getSentDate() throws MessagingException { notImplemented(); return null; } public void setExpectedSentDate(Date aDate){ mySentDate.setExpected(aDate); } public void setSentDate(Date aDate) throws MessagingException { mySentDate.setActual(aDate); } public Date getReceivedDate() throws MessagingException { notImplemented(); return null; } public Flags getFlags() throws MessagingException { notImplemented(); return null; } public void setFlags(Flags flags, boolean b) throws MessagingException { notImplemented(); } public Message reply(boolean b) throws MessagingException { notImplemented(); return null; } public void saveChanges() throws MessagingException { notImplemented(); } public int getSize() throws MessagingException { notImplemented(); return 0; } public int getLineCount() throws MessagingException { notImplemented(); return 0; } public String getContentType() throws MessagingException { notImplemented(); return null; } public boolean isMimeType(String s) throws MessagingException { notImplemented(); return false; } public String getDisposition() throws MessagingException { notImplemented(); return null; } public void setDisposition(String s) throws MessagingException { notImplemented(); } public String getDescription() throws MessagingException { notImplemented(); return null; } public void setDescription(String s) throws MessagingException { notImplemented(); } public String getFileName() throws MessagingException { notImplemented(); return null; } public void setFileName(String s) throws MessagingException { notImplemented(); } public InputStream getInputStream() throws IOException, MessagingException { notImplemented(); return null; } public DataHandler getDataHandler() throws MessagingException { notImplemented(); return null; } public Object getContent() throws IOException, MessagingException { notImplemented(); return null; } public void setDataHandler(DataHandler handler) throws MessagingException { notImplemented(); } public void setExpectedContent(Object aContent, String aMimeType){ myContent.setExpected(aContent); myMimeType.setExpected(aMimeType); } public void setContent(Object aContent, String aMimeType) throws MessagingException { myContent.setActual(aContent); myMimeType.setActual(aMimeType); } public void setExpectedText(String aText){ myText.setExpected(aText); } public void setText(String aText) throws MessagingException { myText.setActual(aText); } public void setContent(Multipart multipart) throws MessagingException { myContent.setActual(multipart); } public void writeTo(OutputStream stream) throws IOException, MessagingException { notImplemented(); } public javax.mail.Message getRealMessage() { return null; } public String[] getHeader(String s) throws MessagingException { notImplemented(); return new String[0]; } public void setHeader(String s, String s1) throws MessagingException { notImplemented(); } public void addHeader(String s, String s1) throws MessagingException { notImplemented(); } public void removeHeader(String s) throws MessagingException { notImplemented(); } public Enumeration getAllHeaders() throws MessagingException { notImplemented(); return null; } public Enumeration getMatchingHeaders(String[] strings) throws MessagingException { notImplemented(); return null; } public Enumeration getNonMatchingHeaders(String[] strings) throws MessagingException { notImplemented(); return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/MockService.java0000644000175000017500000000302107463547116027372 0ustar craftermcrafterm00000000000000package com.mockobjects.mail; import javax.mail.URLName; import javax.mail.event.ConnectionListener; import com.mockobjects.*; import alt.javax.mail.Service; public class MockService extends MockObject implements Service { private final ExpectationCounter myCloseCalls = new ExpectationCounter("close"); private final ExpectationValue myHost = new ExpectationValue("host"); private final ExpectationValue myPort = new ExpectationValue("port"); private final ExpectationValue myUser = new ExpectationValue("user"); private final ExpectationValue myPassword = new ExpectationValue("password"); public void setExpectedCloseCalls(int aNumberOfCalls){ myCloseCalls.setExpected(aNumberOfCalls); } public void close(){ myCloseCalls.inc(); } public void connect(){ notImplemented(); } public void connect(String aHost, int aPort, String aUser, String aPassword){ myHost.setActual(aHost); myPort.setActual(aPort); myUser.setActual(aUser); myPassword.setActual(aPassword); } public void connect(String aHost, String aUser, String aPassword){ notImplemented(); } public boolean isConnected(){ notImplemented(); return false; } public URLName getURLName(){ notImplemented(); return null; } public void addConnectionListener(ConnectionListener connectionListener){ notImplemented(); } public void removeConnectionListener(ConnectionListener connectionListener){ notImplemented(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/MockSession.java0000644000175000017500000000721307635626434027426 0ustar craftermcrafterm00000000000000package com.mockobjects.mail; import com.mockobjects.*; import javax.mail.Authenticator; import javax.mail.Provider; import javax.mail.URLName; import javax.mail.PasswordAuthentication; import alt.javax.mail.Transport; import alt.javax.mail.Session; import javax.mail.Address; import javax.mail.Store; import javax.mail.Folder; import java.util.*; public class MockSession extends MockObject implements Session { private final ExpectationValue myDebug = new ExpectationValue("debug"); private final ExpectationValue myTransportName = new ExpectationValue("transport name"); private final ReturnValue myTransport = new ReturnValue("transport"); public Session getInstance(Properties props, Authenticator authenticator){ notImplemented(); return null; } public Session getInstance(Properties props){ notImplemented(); return null; } public Session getDefaultInstance(Properties props, Authenticator authenticator){ notImplemented(); return null; } public Session getDefaultInstance(Properties props){ notImplemented(); return null; } public void setExpectedDebug(boolean aDebug){ myDebug.setActual(aDebug); } public void setDebug(boolean aDebug){ myDebug.setActual(aDebug); } public boolean getDebug(){ notImplemented(); return false; } public Provider getProviders()[]{ notImplemented(); return null; } public Provider getProvider(String name){ notImplemented(); return null; } public void setProvider(Provider provider){ notImplemented(); } public Transport getTransport(){ notImplemented(); return null; } public void setExpectedTransport(String aTransportName){ myTransportName.setExpected(aTransportName); } public void setupGetTransport(Transport aTransport){ myTransport.setValue(aTransport); } public Transport getTransport(String aTransportName){ myTransportName.setActual(aTransportName); return (Transport)myTransport.getValue(); } public Transport getTransport(Address address){ notImplemented(); return null; } public Transport getTransport(Provider provider){ notImplemented(); return null; } public Transport getTransport(URLName url){ notImplemented(); return null; } public Store getStore(){ notImplemented(); return null; } public Store getStore(String name){ notImplemented(); return null; } public Store getStore(URLName url){ notImplemented(); return null; } public Store getStore(Provider provider){ notImplemented(); return null; } public Folder getFolder(){ notImplemented(); return null; } public Folder getFolder(Store store){ notImplemented(); return null; } public Folder getFolder(URLName url){ notImplemented(); return null; } public void setPasswordAuthentication(URLName url, PasswordAuthentication passwordAuthentication){ notImplemented(); } public PasswordAuthentication getPasswordAuthentication(URLName url){ notImplemented(); return null; } public PasswordAuthentication requestPasswordAuthentication(java.net.InetAddress address, int port, String protocol, String prompt, String defaultUserName){ notImplemented(); return null; } public Properties getProperties(){ notImplemented(); return null; } public String getProperty(String name){ notImplemented(); return null; } public javax.mail.Session getWrappedSession(){ notImplemented(); return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/mail/MockTransport.java0000644000175000017500000000161007504121235027752 0ustar craftermcrafterm00000000000000package com.mockobjects.mail; import javax.mail.event.TransportListener; import alt.javax.mail.Message; import javax.mail.Address; import com.mockobjects.*; import alt.javax.mail.Transport; public class MockTransport extends MockService implements Transport { private final ExpectationValue myMessage = new ExpectationValue("message"); public void setExpectedMessage(Message aMessage){ myMessage.setExpected(aMessage); } public void send(Message aMessage){ myMessage.setActual(aMessage); } public void send(Message msg, Address[] address){ notImplemented(); } public void sendMessage(Message msg, Address[] address){ notImplemented(); } public void addTransportListener(TransportListener transportListener){ notImplemented(); } public void removeTransportListener(TransportListener transportListener){ notImplemented(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/0000755000175000017500000000000010117310266024630 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/directory/0000755000175000017500000000000010117310266026634 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/directory/MockAttribute.java0000644000175000017500000000404707635626434032303 0ustar craftermcrafterm00000000000000package com.mockobjects.naming.directory; import com.mockobjects.*; import javax.naming.directory.*; import javax.naming.*; public class MockAttribute extends MockObject implements Attribute{ private final ReturnValue myObjectToReturn = new ReturnValue("object"); public NamingEnumeration getAll() throws NamingException{ notImplemented(); return null; } public void setupGet(Object aObjectToReturn){ this.myObjectToReturn.setValue(aObjectToReturn); } public Object get() throws NamingException{ return myObjectToReturn.getValue(); } public int size(){ notImplemented(); return 0; } public String getID(){ notImplemented(); return null; } public boolean contains(Object object){ notImplemented(); return false; } public boolean add(Object object){ notImplemented(); return false; } public boolean remove(Object object){ notImplemented(); return false; } public void clear(){ notImplemented(); } public DirContext getAttributeSyntaxDefinition() throws NamingException{ notImplemented(); return null; } public DirContext getAttributeDefinition() throws NamingException{ notImplemented(); return null; } public Object clone(){ notImplemented(); return null; } public boolean isOrdered(){ notImplemented(); return false; } public Object get(int index) throws NamingException{ notImplemented(); return null; } public Object remove(int index){ notImplemented(); return null; } public void add(int index, Object object){ notImplemented(); } public Object set(int index, Object object){ notImplemented(); return null; } public String toString(){ if(myObjectToReturn==null){ return "null"; }else{ return myObjectToReturn.toString(); } } } mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/directory/MockAttributes.java0000644000175000017500000000303007504121236032436 0ustar craftermcrafterm00000000000000package com.mockobjects.naming.directory; import javax.naming.directory.Attributes; import javax.naming.directory.Attribute; import javax.naming.NamingEnumeration; import com.mockobjects.*; import java.util.*; public class MockAttributes extends MockObject implements Attributes{ private ReturnObjectList myAttributesToReturn = new ReturnObjectList("attributes"); private ExpectationList myAttributes = new ExpectationList("attributes"); public boolean isCaseIgnored(){ notImplemented(); return false; } public int size(){ notImplemented(); return 0; } public void setupAddGet(Attribute attribute){ myAttributesToReturn.addObjectToReturn(attribute); } public void setExpectedName(String aName){ myAttributes.addExpected(aName); } public Attribute get(String aName){ myAttributes.addActual(aName); return (Attribute)myAttributesToReturn.nextReturnObject(); } public NamingEnumeration getAll(){ notImplemented(); return null; } public NamingEnumeration getIDs(){ notImplemented(); return null; } public Attribute put(String name, Object object){ notImplemented(); return null; } public Attribute put(Attribute attribute){ notImplemented(); return null; } public Attribute remove(String attributeName){ notImplemented(); return null; } public Object clone(){ notImplemented(); return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/directory/MockDirContext.java0000644000175000017500000001477107635626434032430 0ustar craftermcrafterm00000000000000package com.mockobjects.naming.directory; import javax.naming.*; import javax.naming.directory.*; import com.mockobjects.*; import com.mockobjects.naming.*; public class MockDirContext extends MockContext implements DirContext { private final ReturnValue myAttributeToReturn = new ReturnValue("attribute"); private final ExpectationValue myName = new ExpectationValue("myName"); private ExpectationValue mySearchName = new ExpectationValue("mySearchName"); private final ExpectationValue myAttributes = new ExpectationValue("myAttributes"); private final ExpectationValue myModificationOperation = new ExpectationValue("myModificationOperation"); private final ExpectationValue myFilter = new ExpectationValue("myFilter"); private final ExpectationValue mySearchControls = new ExpectationValue("mySearchControls"); private final ReturnValue myResults = new ReturnValue("results"); private ExpectationCounter myAttributesCallCount = new ExpectationCounter("getAttributes"); public void setupAttributes(Attributes anAttributeToReturn) { this.myAttributeToReturn.setValue(anAttributeToReturn); } public void setExpectedGetAttributesName(Object aName) { this.myName.setExpected(aName); } public void setExpectedGetAttributesCount(int callCount) { this.myAttributesCallCount.setExpected(callCount); } public Attributes getAttributes(Name aName) throws NamingException { return getAttributes(aName.toString()); } public Attributes getAttributes(String aName) throws NamingException { return getAttributes(aName, null); } public Attributes getAttributes(Name aName, String[] attrIds) throws NamingException { return getAttributes(aName.toString(), attrIds); } public Attributes getAttributes(String aName, String[] attrIds) throws NamingException { this.myName.setActual(aName); this.myAttributesCallCount.inc(); return (Attributes) myAttributeToReturn.getValue(); } public void setExpectedModifyAttributes(String aName, int aModificationOperation, Attributes attributes) { this.myName.setExpected(aName); this.myModificationOperation.setExpected(aModificationOperation); this.myAttributes.setExpected(attributes); } public void modifyAttributes(Name aName, int aModificationOperation, Attributes attributes) throws NamingException { modifyAttributes(aName.toString(), aModificationOperation, attributes); } public void modifyAttributes(String aName, int aModificationOperation, Attributes attributes) throws NamingException { this.myName.setActual(aName); this.myModificationOperation.setActual(aModificationOperation); this.myAttributes.setActual(attributes); } public void modifyAttributes(Name aName, ModificationItem[] mods) throws NamingException { notImplemented(); } public void modifyAttributes(String aName, ModificationItem[] mods) throws NamingException { notImplemented(); } public void bind(Name aName, Object object, Attributes attributes) throws NamingException { notImplemented(); } public void bind(String aName, Object object, Attributes attributes) throws NamingException { notImplemented(); } public void rebind(Name aName, Object object, Attributes attributes) throws NamingException { notImplemented(); } public void rebind(String aName, Object object, Attributes attributes) throws NamingException { notImplemented(); } public DirContext createSubcontext(Name aName, Attributes attributes) throws NamingException { notImplemented(); return null; } public DirContext createSubcontext(String aName, Attributes attributes) throws NamingException { notImplemented(); return null; } public DirContext getSchema(Name aName) throws NamingException { notImplemented(); return null; } public DirContext getSchema(String aName) throws NamingException { notImplemented(); return null; } public DirContext getSchemaClassDefinition(Name aName) throws NamingException { notImplemented(); return null; } public DirContext getSchemaClassDefinition(String aName) throws NamingException { notImplemented(); return null; } public NamingEnumeration search(Name aName, Attributes attributes, String[] anAttributeToReturn) throws NamingException { return (NamingEnumeration) myResults.getValue(); } public NamingEnumeration search(String aName, Attributes attributes, String[] anAttributeToReturn) throws NamingException { return (NamingEnumeration) myResults.getValue(); } public NamingEnumeration search(Name aName, Attributes attributes) throws NamingException { return (NamingEnumeration) myResults.getValue(); } public NamingEnumeration search(String aName, Attributes attributes) throws NamingException { return (NamingEnumeration) myResults.getValue(); } public NamingEnumeration search(Name aName, String aFilter, SearchControls cons) throws NamingException { return (NamingEnumeration) myResults.getValue(); } public void setExpectedSearch(String aSearchName, String aFilter, SearchControls searchControls) { this.mySearchName.setExpected(aSearchName); this.myFilter.setExpected(aFilter); this.mySearchControls.setExpected(searchControls); } public void setupSearchResult(NamingEnumeration results) { this.myResults.setValue(results); } public NamingEnumeration search(String aSearchName, String aFilter, SearchControls searchControls) throws NamingException { this.mySearchName.setActual(aSearchName); this.myFilter.setActual(aFilter); this.mySearchControls.setActual(searchControls); return (NamingEnumeration) myResults.getValue(); } public NamingEnumeration search(Name aName, String aFilter, Object[] filterArgs, SearchControls cons) throws NamingException { return (NamingEnumeration) myResults.getValue(); } public NamingEnumeration search(String aName, String aFilter, Object[] filterArgs, SearchControls cons) throws NamingException { return (NamingEnumeration) myResults.getValue(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/directory/MockNamingEnumeration.java0000644000175000017500000000151007435470341033740 0ustar craftermcrafterm00000000000000package com.mockobjects.naming.directory; import com.mockobjects.*; import javax.naming.*; import javax.naming.directory.*; import java.util.*; public class MockNamingEnumeration extends MockObject implements NamingEnumeration{ private List mySearchResults = new ArrayList(); private boolean hasMore = true; public void setupAddSearchResult(Object object){ mySearchResults.add(object); } public Object next() throws NamingException{ return mySearchResults.remove(0); } public boolean hasMore() throws NamingException{ return mySearchResults.size()>0; } public void close() throws NamingException{ } public boolean hasMoreElements(){ return mySearchResults.size()>0; } public Object nextElement(){ return mySearchResults.remove(0); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/naming/MockContext.java0000644000175000017500000001324707541642204027747 0ustar craftermcrafterm00000000000000package com.mockobjects.naming; import com.mockobjects.ExpectationList; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; import com.mockobjects.ReturnObjectList; import javax.naming.*; public class MockContext extends MockObject implements Context { private final ReturnObjectList myLookupObjects = new ReturnObjectList("lookups"); private final ReturnObjectList mySubContexts = new ReturnObjectList("sub contexts"); private ExpectationList mySubContextNames = new ExpectationList( MockContext.class.getName() + "sub context name"); private ExpectationValue myBindName = new ExpectationValue( MockContext.class.getName() + "myBindName"); private ExpectationValue myBindObject = new ExpectationValue( MockContext.class.getName() + "myBindObject"); private ExpectationValue myRebindName = new ExpectationValue( MockContext.class.getName() + "myRebindName"); private ExpectationValue myLookupName = new ExpectationValue( MockContext.class.getName() + "myLookupName"); public void setupAddLookup(Object aObjectToReturn) { this.myLookupObjects.addObjectToReturn(aObjectToReturn); } public void setExpectedLookupName(String aLookupName) { this.myLookupName.setExpected(aLookupName); } public Object lookup(Name name) throws NamingException { this.myLookupName.setActual(name); return myLookupObjects.nextReturnObject(); } public Object lookup(String name) throws NamingException { this.myLookupName.setActual(name); return myLookupObjects.nextReturnObject(); } public void bind(Name aBindName, Object aBindObject) throws NamingException { this.myBindName.setExpected(aBindName); this.myBindObject.setExpected(aBindObject); } public void setExpectedBind(String aBindName, Object aBindObject) { this.myBindName.setExpected(aBindName); this.myBindObject.setExpected(aBindObject); } public void setExpectedReBind(String aBindName, Object aBindObject) { this.myRebindName.setExpected(aBindName); this.myRebindName.setExpected(aBindObject); } public void bind(String aBindName, Object aBindObject) throws NamingException { this.myBindName.setActual(aBindName); this.myBindObject.setActual(aBindObject); } public void rebind(Name aBindName, Object aBindObject) throws NamingException { this.myRebindName.setActual(aBindName); this.myRebindName.setActual(aBindObject); } public void rebind(String aBindName, Object aBindObject) throws NamingException { this.myRebindName.setActual(aBindName); this.myRebindName.setActual(aBindObject); } public void unbind(Name name) throws NamingException { notImplemented(); } public void unbind(String name) throws NamingException { notImplemented(); } public void rename(Name name, Name name2) throws NamingException { notImplemented(); } public void rename(String name, String name2) throws NamingException { notImplemented(); } public NamingEnumeration list(Name name) throws NamingException { notImplemented(); return null; } public NamingEnumeration list(String name) throws NamingException { notImplemented(); return null; } public NamingEnumeration listBindings(Name name) throws NamingException { notImplemented(); return null; } public NamingEnumeration listBindings(String name) throws NamingException { notImplemented(); return null; } public void destroySubcontext(Name name) throws NamingException { notImplemented(); } public void destroySubcontext(String name) throws NamingException { notImplemented(); } public Context createSubcontext(Name name) throws NamingException { notImplemented(); return null; } public void setupAddCreateSubContext(Context aContext){ mySubContexts.addObjectToReturn(aContext); } public void setExpectedCreateSubContext(String name){ this.mySubContextNames.addExpected(name); } public Context createSubcontext(String name) throws NamingException { mySubContextNames.addActual(name); return (Context) mySubContexts.nextReturnObject(); } public Object lookupLink(Name name) throws NamingException { notImplemented(); return null; } public Object lookupLink(String name) throws NamingException { notImplemented(); return null; } public NameParser getNameParser(Name name) throws NamingException { notImplemented(); return null; } public NameParser getNameParser(String name) throws NamingException { notImplemented(); return null; } public Name composeName(Name name, Name name2) throws NamingException { notImplemented(); return null; } public String composeName(String name, String name2) throws NamingException { notImplemented(); return null; } public Object addToEnvironment(String name, Object object) throws NamingException { notImplemented(); return null; } public Object removeFromEnvironment(String name) throws NamingException { notImplemented(); return null; } public java.util.Hashtable getEnvironment() throws NamingException { notImplemented(); return null; } public void close() throws NamingException { notImplemented(); } public String getNameInNamespace() throws NamingException { notImplemented(); return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/0000755000175000017500000000000010117310266025043 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockBodyContent.java0000755000175000017500000001064707635626434031005 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.util.AssertMo; import com.mockobjects.Verifiable; import com.mockobjects.ExpectationValue; import com.mockobjects.ReturnValue; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyContent; import java.io.IOException; import java.io.Reader; import java.io.Writer; public class MockBodyContent extends BodyContent implements Verifiable{ private final ReturnValue myEnclosingWriter = new ReturnValue("enclosing writer"); private final ExpectationValue myWriter = new ExpectationValue("writer"); public int getBufferSize() { notImplemented(); return super.getBufferSize(); } public MockBodyContent() { super(null); } public void write(int c) throws IOException { notImplemented(); super.write(c); } public void flush() throws IOException { notImplemented(); super.flush(); } public boolean isAutoFlush() { notImplemented(); return super.isAutoFlush(); } public void write(char cbuf[]) throws IOException { notImplemented(); super.write(cbuf); } public boolean equals(Object obj) { notImplemented(); return super.equals(obj); } public void clearBody() { notImplemented(); super.clearBody(); } public void write(String str) throws IOException { notImplemented(); super.write(str); } public void setupGetEnclosingWriter(JspWriter aJspWriter){ myEnclosingWriter.setValue(aJspWriter); } public JspWriter getEnclosingWriter() { return (JspWriter)myEnclosingWriter.getValue(); } private void notImplemented() { AssertMo.notImplemented(MockBodyContent.class.getName()); } public Reader getReader() { notImplemented(); return null; } public void newLine() throws IOException { notImplemented(); } public void write(char cbuf[], int off, int len) throws IOException { notImplemented(); } public void print(boolean b) throws IOException { notImplemented(); } public void setExpectedWriteOut(Writer aWriter){ myWriter.setExpected(aWriter); } public void writeOut(Writer aWriter) throws IOException { myWriter.setActual(aWriter); } public void print(char c) throws IOException { notImplemented(); } public void print(int i) throws IOException { notImplemented(); } public void print(long l) throws IOException { notImplemented(); } public void print(float v) throws IOException { notImplemented(); } public void print(double v) throws IOException { notImplemented(); } public void print(char[] chars) throws IOException { notImplemented(); } public void print(String s) throws IOException { notImplemented(); } public void print(Object o) throws IOException { notImplemented(); } public void println() throws IOException { notImplemented(); } public void println(boolean b) throws IOException { notImplemented(); } public void println(char c) throws IOException { notImplemented(); } public void println(int i) throws IOException { notImplemented(); } public void println(long l) throws IOException { notImplemented(); } public void println(float v) throws IOException { notImplemented(); } public void println(double v) throws IOException { notImplemented(); } public void println(char[] chars) throws IOException { notImplemented(); } public void println(String s) throws IOException { notImplemented(); } public void println(Object o) throws IOException { notImplemented(); } public void clear() throws IOException { notImplemented(); } public void clearBuffer() throws IOException { notImplemented(); } public void close() throws IOException { notImplemented(); } public int getRemaining() { notImplemented(); return 0; } public void write(String str, int off, int len) throws IOException { notImplemented(); super.write(str, off, len); } public String getString() { notImplemented(); return null; } public void verify() { } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockJspWriter.java0000644000175000017500000000554707613755207030503 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.ExpectationValue; import com.mockobjects.util.AssertMo; import javax.servlet.jsp.JspWriter; import java.io.PrintWriter; import java.io.StringWriter; public class MockJspWriter extends JspWriter { private final ExpectationValue expectedData = new ExpectationValue("data"); private StringWriter stringWriter = new StringWriter(); private PrintWriter printWriter = new PrintWriter(stringWriter); public MockJspWriter() { super(0, true); } public void setExpectedData(String data) { expectedData.setExpected(data); } private final void notImplemented(){ AssertMo.notImplemented(this.getClass().getName()); } public void newLine() { notImplemented(); } public void flush() { notImplemented(); } public void print(double d) { printWriter.print(String.valueOf(d)); } public void println() { notImplemented(); } public void close() { notImplemented(); } public void print(int anInt) { printWriter.print(String.valueOf(anInt)); } public void print(long aLong) { printWriter.print(String.valueOf(aLong)); } public void print(float f) { notImplemented(); } public void println(char c) { notImplemented(); } public void clear() { notImplemented(); } public void print(boolean b) { notImplemented(); } public void print(String aString) { printWriter.print(aString); } public void println(String aString) { printWriter.print(aString); } public void print(char c) { notImplemented(); } public void write(char[] buf, int off, int len) { printWriter.write(buf, off, len); } public void println(char[] c) { notImplemented(); } public void println(boolean b) { notImplemented(); } public void clearBuffer() { notImplemented(); } public void print(Object anObject) { printWriter.print(anObject); } public void println(long l) { notImplemented(); } public void println(int i) { notImplemented(); } public void print(char[] c) { notImplemented(); } public void println(float f) { notImplemented(); } public void println(double d) { notImplemented(); } public int getRemaining() { notImplemented(); return -1; } public void println(Object anObject) { printWriter.print(anObject); } public void verify() { printWriter.flush(); expectedData.setActual(stringWriter.toString()); expectedData.verify(); expectedData.setExpected(""); stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockPageContext.java0000644000175000017500000000445007435762173030765 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public class MockPageContext extends PageContext{ private JspWriter jspWriter; private ServletRequest request; private HttpSession httpSession; private ServletContext servletContext; public void release(){ } public JspWriter getOut(){ return jspWriter; } public void setJspWriter(JspWriter jspWriter){ this.jspWriter = jspWriter; } public void handlePageException(Exception e){ } public ServletContext getServletContext(){ return servletContext; } public void setServletContext(ServletContext servletContext){ this.servletContext = servletContext; } public int getAttributesScope(String s){ return -1; } public void include(String s){ } public void removeAttribute(String s, int i){ } public Enumeration getAttributeNamesInScope(int i){ return null; } public void forward(String s){ } public Object getPage(){ return null; } public void handlePageException(Throwable t){ } public void setRequest(ServletRequest servletRequest){ this.request = servletRequest; } public ServletRequest getRequest(){ return request; } public ServletResponse getResponse(){ return null; } public void removeAttribute(String s){ } public Object getAttribute(String s, int i){ return null; } public ServletConfig getServletConfig(){ return null; } public void initialize(Servlet servlet, ServletRequest servletRequest, ServletResponse servletResponse, String s, boolean b, int i, boolean b2){ } public Object findAttribute(String s) { return null; } public HttpSession getSession() { return httpSession; } public void setSession(HttpSession httpSession) { this.httpSession = httpSession; } public void setAttribute(String s, Object o){ } public void setAttribute(String s, Object o, int i) { } public Object getAttribute(String s) { return null; } public Exception getException() { return null; } public void verify(){ } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockRequestDispatcher.java0000644000175000017500000000224607557734275032213 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; public class MockRequestDispatcher extends MockObject implements RequestDispatcher { private final ExpectationValue myRequest = new ExpectationValue("request"); private final ExpectationValue myResponse = new ExpectationValue("response"); public void setExpectedRequest(ServletRequest aRequest) { myRequest.setExpected(aRequest); } public void setExpectedResponse(ServletResponse aResponse) { myResponse.setExpected(aResponse); } public void forward(ServletRequest aRequest, ServletResponse aResponse) throws ServletException, IOException { myRequest.setActual(aRequest); myResponse.setActual(aResponse); } public void include(ServletRequest aRequest, ServletResponse aResponse) throws ServletException, IOException { myRequest.setActual(aRequest); myResponse.setActual(aResponse); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockServletConfig.java0000644000175000017500000000231107435762173031310 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import javax.servlet.*; import junit.framework.*; import junit.textui.*; import java.util.*; import java.io.*; import java.net.*; import com.mockobjects.*; /** * @version $Revision: 1.1 $ */ public class MockServletConfig extends MockObject implements ServletConfig { private Dictionary myParameters = new Hashtable(); private ServletContext servletContext; public String getInitParameter(String paramName) { return (String)myParameters.get(paramName); } public void setInitParameter(String paramName, String paramValue) { myParameters.put(paramName, paramValue); } public java.util.Enumeration getInitParameterNames() { return myParameters.keys(); } public void setupAddInitParameter(String paramName, String value) { myParameters.put(paramName, value); } public void setupNoParameters() { myParameters = new Hashtable(); } public void setServletContext(ServletContext servletContext){ this.servletContext = servletContext; } public ServletContext getServletContext(){ return servletContext; } public String getServletName(){ return null; } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockServletContext.java0000644000175000017500000001042407660456066031534 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.*; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Set; public class MockServletContext extends MockObject implements ServletContext { private ReturnObjectBag returnAttributes = new ReturnObjectBag("attributes"); private Set resourcePaths; private ReturnObjectList realPaths = new ReturnObjectList("real path"); private URL resource; private HashMap initParameters = new HashMap(); private ExpectationValue expectedLogValue = new ExpectationValue("log"); private ExpectationValue expectedLogThrowable = new ExpectationValue("log throwable"); private ExpectationValue requestDispatcherURI = new ExpectationValue("RequestDispatcher URI"); private RequestDispatcher requestDispatcher; private ExpectationSet attributes = new ExpectationSet("attributes"); public Enumeration getServlets() { return null; } public void log(String string) { expectedLogValue.setActual(string); } public void setExpectedLog(String string) { expectedLogValue.setExpected(string); } public void setupGetResource(URL resource) { this.resource = resource; } public URL getResource(String string) { return resource; } public void setupGetResourcePaths(Set resourcePaths) { this.resourcePaths = resourcePaths; } public Set getResourcePaths(String string) { return resourcePaths; } public ServletContext getContext(String string) { return null; } public int getMinorVersion() { return -1; } public void removeAttribute(String string) { } public void log(String string, Throwable t) { log(string); expectedLogThrowable.setActual(t); } public void setExpectedLogThrowable(Throwable throwable) { expectedLogThrowable.setExpected(throwable); } public void addRealPath(String realPath) { this.realPaths.addObjectToReturn(realPath); } public String getRealPath(String string) { return realPaths.nextReturnObject().toString(); } public Enumeration getServletNames() { return null; } public Servlet getServlet(String string) { return null; } public void log(Exception exception, String string) { } public String getServerInfo() { return null; } public void setExpectedRequestDispatcherURI(String uri) { this.requestDispatcherURI.setExpected(uri); } public void setupGetRequestDispatcher( RequestDispatcher requestDispatcher) { this.requestDispatcher = requestDispatcher; } public RequestDispatcher getRequestDispatcher(String uri) { requestDispatcherURI.setActual(uri); return requestDispatcher; } public int getMajorVersion() { return -1; } public Set getResourcePaths() { return null; } public void setupGetAttribute(String string, Object object) { returnAttributes.putObjectToReturn(string, object); } public String getMimeType(String string) { return null; } public RequestDispatcher getNamedDispatcher(String string) { return null; } public String getInitParameter(String paramName) { return (String) initParameters.get(paramName); } public void setInitParameter(String paramName, String paramValue) { initParameters.put(paramName, paramValue); } public Object getAttribute(String string) { return returnAttributes.getNextReturnObject(string); } public Enumeration getAttributeNames() { return null; } public String getServletContextName() { return null; } public InputStream getResourceAsStream(String string) { return null; } public Enumeration getInitParameterNames() { return null; } public void addExpectedAttribute(String key, Object value) { attributes.addExpected(new MapEntry(key, value)); } public void setAttribute(String key, Object value) { attributes.addActual(new MapEntry(key, value)); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockServletInputStream.java0000644000175000017500000000114307507062275032354 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import com.mockobjects.Verifiable; import com.mockobjects.util.Verifier; import javax.servlet.ServletInputStream; public class MockServletInputStream extends ServletInputStream implements Verifiable { private byte[] myData; private int myIndex; public void verify() { Verifier.verifyObject(this); } public void setupRead(byte[] data) { myData = data; } public int read() { if(myData!=null && myIndex < myData.length) { return myData[myIndex++]; } else { return -1; } } } mockobjects-0.09/src/j2ee/common/com/mockobjects/servlet/MockServletOutputStream.java0000644000175000017500000000324207435470341032554 0ustar craftermcrafterm00000000000000package com.mockobjects.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.servlet.ServletOutputStream; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationValue; public class MockServletOutputStream extends ServletOutputStream { private ExpectationValue myWriteCalled = new ExpectationValue("MockServletOutputStream.write()"); private boolean myThrowException = false; private ExpectationCounter myCloseCallCount = new ExpectationCounter("MockServletOutputstream.close()"); private ByteArrayOutputStream myBuffer; public MockServletOutputStream() { super(); setupClearContents(); } public void setExpectedCloseCalls(int closeCall) { myCloseCallCount.setExpected(closeCall); } public void setExpectingWriteCalls(boolean expectingWriteCall) { myWriteCalled.setExpected(expectingWriteCall); } public void setThrowIOException(boolean throwException) { myThrowException = throwException; } public void close() throws IOException { myCloseCallCount.inc(); } public String toString() { return getContents(); } public void write(int b) throws IOException { myWriteCalled.setActual(true); if (myThrowException) throw new IOException("Test IOException generated by request"); myBuffer.write(b); } public void setupClearContents () { myBuffer = new ByteArrayOutputStream(); } public String getContents() { return myBuffer.toString(); } public void verify() { myWriteCalled.verify(); myCloseCallCount.verify(); } } mockobjects-0.09/src/j2ee/common/com/mockobjects/sql/0000755000175000017500000000000010117310266024156 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/j2ee/common/com/mockobjects/sql/CommonMockDataSource.java0000644000175000017500000001221407532724774031062 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.io.PrintWriter; import java.sql.Connection; import javax.sql.DataSource; import com.mockobjects.ExpectationCounter; import com.mockobjects.MockObject; /** * Abstract DataSource for use with mock testing. * Only the connection methods have been implemented here. * If testing of the log methods is needed, please submit a patch. * @see javax.sql.DataSource * @author Ted Husted * @version $Revision: 1.1 $ $Date: 2002/08/27 16:34:04 $ */ public abstract class CommonMockDataSource extends MockObject implements DataSource { private Connection myConnection; private ExpectationCounter myConnectCalls = new ExpectationCounter("CommonMockDataSource.connection"); /** * Register the number of connections the test should make. * The valid method will report any discrepancy with the * actual count. */ public void setExpectedConnectCalls(int callCount) { myConnectCalls.setExpected(callCount); } /** * Pass the connection instance for use with tests. * This instance will be returned until replaced with another. */ public void setupConnection(Connection aConnection) { myConnection = aConnection; } // -------------------------------------------------------- implemented /** * Returns connection instance passed by setupConnection, * and increments the number of connect calls. */ public Connection getConnection() { myConnectCalls.inc(); return myConnection; } // ------------------------------------------------------ notImplemented /** * Calls notImplemented. Returns null. */ public Connection getConnection(String username, String password) { notImplemented(); return null; } /** * Calls notImplemented. Returns 0. */ public int getLoginTimeout() { notImplemented(); return 0; } /** * Calls notImplemented. Returns null. */ public PrintWriter getLogWriter() { notImplemented(); return null; } /** * Calls notImplemented. */ public void setLoginTimeout(int seconds) { notImplemented(); } /** * Calls notImplemented. */ public void setLogWriter(PrintWriter out) { notImplemented(); } } /* * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */mockobjects-0.09/src/jdk/0000755000175000017500000000000010117310266016731 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.3/0000755000175000017500000000000010117310266017232 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.3/com/0000755000175000017500000000000010117310266020010 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.3/com/mockobjects/0000755000175000017500000000000010117310266022313 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/0000755000175000017500000000000010117310266023112 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockConnection.java0000755000175000017500000000031207605061410026667 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; /** * @deprecated Use temporary class MockConnection2 * @see MockConnection2 * @version $Revision: 1.3 $ */ public class MockConnection extends CommonMockConnection{ } mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockConnection2.java0000644000175000017500000000130407573373574026775 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; /** * MockConnection2 is a tempary replacement for the MockConnection. * It differs from the MockConnection in the way in which preparedstatements * are handled. The changes are significant enough to break compatiblity with * exsising testcases so MockConnection2 provides a migration path to the new * system of handling preparedstatements. * This calls will eventually be merged back into MockConnection when it is felt * systems using the classes have been provided with enough time to migrate. */ public class MockConnection2 extends CommonMockConnection2{ public MockConnection2() { } public MockConnection2(String name) { super(name); } } mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockMultiRowResultSet.java0000755000175000017500000000033707573373574030261 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; public class MockMultiRowResultSet extends CommonMockMultiRowResultSet{ public MockMultiRowResultSet() { } public MockMultiRowResultSet(String name) { super(name); } } mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockPreparedStatement.java0000755000175000017500000000015107507117153030227 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; public class MockPreparedStatement extends CommonMockPreparedStatement { } mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockResultSetMetaData.java0000755000175000017500000000114507533703026030136 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import com.mockobjects.ExpectationList; import com.mockobjects.MockObject; import com.mockobjects.ReturnObjectList; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * Minimal implementation of ResultSetMetaData for testing. * Supports column count, column names, and column sql types. * @see javax.sql.ResultSetMetaData. * @author Jeff Martin * @author Ted Husted * @version $Revision: 1.2 $ */ public class MockResultSetMetaData extends CommonMockResultSetMetaData { } mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockSingleRowResultSet.java0000755000175000017500000000015307507117153030366 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; public class MockSingleRowResultSet extends CommonMockSingleRowResultSet { } mockobjects-0.09/src/jdk/1.3/com/mockobjects/sql/MockStatement.java0000755000175000017500000000013207512255107026541 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; public class MockStatement extends CommonMockStatement { } mockobjects-0.09/src/jdk/1.4/0000755000175000017500000000000010117310266017233 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/com/0000755000175000017500000000000010117310266020011 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/com/mockobjects/0000755000175000017500000000000010117310266022314 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/com/mockobjects/constraint/0000755000175000017500000000000010117310266024500 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/com/mockobjects/constraint/Matches.java0000644000175000017500000000230707605061411026734 0ustar craftermcrafterm00000000000000/* * Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.mockobjects.constraint; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Is the value a string that matches a regular expression? */ public class Matches implements Constraint { private Pattern _pattern; /** Creates a new Matches predicate. * * @param regex * A regular expression string used to create a * {@link java.util.regex.Pattern}. The {@link #eval} method * returns true when applied to Strings that match this pattern. * Matching is tested by calling the * {@link java.util.regex.Matcher#matches} method of a * {@link java.util.regex.Matcher} object. */ public Matches(String regex) { _pattern = Pattern.compile(regex); } public boolean eval(Object arg) { if (arg instanceof String) { Matcher matcher = _pattern.matcher((String) arg); return matcher.matches(); } else { return false; } } public String toString() { return "a string that matches <" + _pattern.toString() + ">"; } } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/0000755000175000017500000000000010117310266023113 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockCallableStatement.java0000644000175000017500000000311007662630574030171 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.net.URL; import java.sql.ParameterMetaData; import java.sql.ResultSet; import java.sql.SQLException; public class MockCallableStatement extends CommonMockCallableStatement { public void setURL(int parameterIndex, URL val) { notImplemented(); } public ParameterMetaData getParameterMetaData() throws SQLException { notImplemented(); return null; } public boolean getMoreResults(int current) throws SQLException { notImplemented(); return false; } public ResultSet getGeneratedKeys() throws SQLException { notImplemented(); return null; } public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return 0; } public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { notImplemented(); return 0; } public int executeUpdate(String sql, String[] columnNames) throws SQLException { notImplemented(); return 0; } public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return false; } public boolean execute(String sql, int[] columnIndexes) throws SQLException { notImplemented(); return false; } public boolean execute(String sql, String[] columnNames) throws SQLException { notImplemented(); return false; } public int getResultSetHoldability() throws SQLException { notImplemented(); return 0; } }mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockConnection.java0000755000175000017500000000124407662630574026715 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.SQLException; import java.sql.Savepoint; /** * @deprecated Use temporary class MockConnection2 * @see MockConnection2 */ public class MockConnection extends CommonMockConnection{ public void releaseSavepoint(Savepoint savepoint) throws SQLException { notImplemented(); } public void rollback(Savepoint savepoint) throws SQLException { notImplemented(); } public Savepoint setSavepoint() throws SQLException { notImplemented(); return null; } public Savepoint setSavepoint(String name) throws SQLException { notImplemented(); return null; } } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockConnection2.java0000644000175000017500000000243207662630574026774 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.SQLException; import java.sql.Savepoint; /** * MockConnection2 is a tempary replacement for the MockConnection. * It differs from the MockConnection in the way in which PreparedStatements * are handled. The changes are significant enough to break compatiblity with * existing testcases so MockConnection2 provides a migration path to the new * system of handling PreparedStatements. * This class will eventually be merged back into MockConnection when it is * felt systems using the classes have been provided with enough time to migrate. */ public class MockConnection2 extends CommonMockConnection2{ private final MockConnection connection = new MockConnection(); public MockConnection2() { } public MockConnection2(String name) { super(name); } public void releaseSavepoint(Savepoint savepoint) throws SQLException { connection.releaseSavepoint(savepoint); } public void rollback(Savepoint savepoint) throws SQLException { connection.rollback(savepoint); } public Savepoint setSavepoint() throws SQLException { return connection.setSavepoint(); } public Savepoint setSavepoint(String name) throws SQLException { return connection.setSavepoint(); } } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockMultiRowResultSet.java0000755000175000017500000000246707507117153030252 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.net.URL; import java.sql.*; import java.sql.SQLException; import java.sql.Ref; import java.sql.Blob; import java.sql.Clob; public class MockMultiRowResultSet extends CommonMockMultiRowResultSet{ public URL getURL(int columnIndex) throws SQLException { notImplemented(); return null; } public URL getURL(String columnName) throws SQLException { notImplemented(); return null; } public void updateRef(int columnIndex, Ref x) throws SQLException { notImplemented(); } public void updateRef(String columnName, Ref x) throws SQLException { notImplemented(); } public void updateBlob(int columnIndex, Blob x) throws SQLException { notImplemented(); } public void updateBlob(String columnName, Blob x) throws SQLException { notImplemented(); } public void updateClob(int columnIndex, Clob x) throws SQLException { notImplemented(); } public void updateClob(String columnName, Clob x) throws SQLException { notImplemented(); } public void updateArray(int columnIndex, Array x) throws SQLException { notImplemented(); } public void updateArray(String columnName, Array x) throws SQLException { notImplemented(); } } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockPreparedStatement.java0000755000175000017500000000313307507117153030233 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.SQLException; import java.sql.ResultSet; import java.sql.ParameterMetaData; import java.net.URL; public class MockPreparedStatement extends CommonMockPreparedStatement { public boolean getMoreResults(int current) throws SQLException { notImplemented(); return false; } public void setURL(int parameterIndex, URL x) throws SQLException { notImplemented(); } public ResultSet getGeneratedKeys() throws SQLException { notImplemented(); return null; } public ParameterMetaData getParameterMetaData() throws SQLException { notImplemented(); return null; } public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return 0; } public int executeUpdate(String sql, int columnIndexes[]) throws SQLException { notImplemented(); return 0; } public int executeUpdate(String sql, String columnNames[]) throws SQLException { notImplemented(); return 0; } public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return false; } public boolean execute(String sql, int columnIndexes[]) throws SQLException { notImplemented(); return false; } public boolean execute(String sql, String columnNames[]) throws SQLException { notImplemented(); return false; } public int getResultSetHoldability() throws SQLException { notImplemented(); return 0; } } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockResultSetMetaData.java0000755000175000017500000000065707662630574030160 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; /** * Minimal implementation of ResultSetMetaData for testing. * Supports column count, column names, and column sql types. * @see javax.sql.ResultSetMetaData. * @author Jeff Martin * @author Ted Husted * @version $Revision: 1.3 $ */ public class MockResultSetMetaData extends CommonMockResultSetMetaData { } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockSingleRowResultSet.java0000755000175000017500000000247607662630574030412 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Ref; import java.sql.SQLException; public class MockSingleRowResultSet extends CommonMockSingleRowResultSet { public URL getURL(int columnIndex) throws SQLException { notImplemented(); return null; } public URL getURL(String columnName) throws SQLException { notImplemented(); return null; } public void updateRef(int columnIndex, Ref x) throws SQLException { notImplemented(); } public void updateRef(String columnName, Ref x) throws SQLException { notImplemented(); } public void updateBlob(int columnIndex, Blob x) throws SQLException { notImplemented(); } public void updateBlob(String columnName, Blob x) throws SQLException { notImplemented(); } public void updateClob(int columnIndex, Clob x) throws SQLException { notImplemented(); } public void updateClob(String columnName, Clob x) throws SQLException { notImplemented(); } public void updateArray(int columnIndex, Array x) throws SQLException { notImplemented(); } public void updateArray(String columnName, Array x) throws SQLException { notImplemented(); } } mockobjects-0.09/src/jdk/1.4/com/mockobjects/sql/MockStatement.java0000755000175000017500000000245107662630574026563 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.ResultSet; import java.sql.SQLException; public class MockStatement extends CommonMockStatement{ public boolean getMoreResults(int current) throws SQLException { notImplemented(); return false; } public ResultSet getGeneratedKeys() throws SQLException { notImplemented(); return null; } public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return 0; } public int executeUpdate(String sql, int columnIndexes[]) throws SQLException { notImplemented(); return 0; } public int executeUpdate(String sql, String columnNames[]) throws SQLException { notImplemented(); return 0; } public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return false; } public boolean execute(String sql, int columnIndexes[]) throws SQLException { notImplemented(); return false; } public boolean execute(String sql, String columnNames[]) throws SQLException { notImplemented(); return false; } public int getResultSetHoldability() throws SQLException { notImplemented(); return 0; } } mockobjects-0.09/src/jdk/1.4/test/0000755000175000017500000000000010117310266020212 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/test/mockobjects/0000755000175000017500000000000010117310266022515 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/test/mockobjects/constraint/0000755000175000017500000000000010117310266024701 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/1.4/test/mockobjects/constraint/MatchesTest.java0000644000175000017500000000116007662630620030000 0ustar craftermcrafterm00000000000000/* * Date: 21-Oct-2002 */ package test.mockobjects.constraint; import junit.framework.TestCase; import com.mockobjects.constraint.Constraint; import com.mockobjects.constraint.Matches; public class MatchesTest extends TestCase { public MatchesTest(String name) { super(name); } public void testMatches() { Constraint p = new Matches("^hello, (.*)\\.$"); assertTrue(p.eval("hello, world.")); assertTrue(p.eval("hello, mum.")); assertTrue(!p.eval("hello world.")); assertTrue(!p.eval("hello, world")); assertTrue(!p.eval("goodbye, world.")); } } mockobjects-0.09/src/jdk/common/0000755000175000017500000000000010117310266020221 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/alt/0000755000175000017500000000000010117310266021001 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/alt/java/0000755000175000017500000000000010117310266021722 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/alt/java/io/0000755000175000017500000000000010117310266022331 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/alt/java/io/File.java0000644000175000017500000000323407466000564024067 0ustar craftermcrafterm00000000000000package alt.java.io; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public interface File { public String getName(); public String getParent(); public File getParentFile(); public String getPath(); public boolean isAbsolute(); public String getAbsolutePath(); public File getAbsoluteFile(); public String getCanonicalPath() throws IOException; public File getCanonicalFile() throws IOException; public URL toURL() throws MalformedURLException; public boolean canRead(); public boolean canWrite(); public boolean exists(); public boolean isDirectory(); public boolean isFile(); public boolean isHidden(); public long lastModified(); public long length(); public boolean createNewFile() throws IOException; public boolean delete(); public void deleteOnExit(); public String[] list(); public String[] list(FilenameFilter filter); public File[] listFiles(); public File[] listFiles(FilenameFilter filter); public File[] listFiles(FileFilter filter); public boolean mkdir(); public boolean mkdirs(); public boolean renameTo(File dest); public boolean setLastModified(long time); public boolean setReadOnly(); public int compareTo(File pathname); public int compareTo(Object o); public java.io.File getRealFile(); public File createTempFile(String prefix, String suffix, File directory) throws IOException; public File createTempFile(String prefix, String suffix) throws IOException; public File[] listRoots(); } mockobjects-0.09/src/jdk/common/alt/java/io/FileImpl.java0000644000175000017500000000757707466000564024727 0ustar craftermcrafterm00000000000000package alt.java.io; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class FileImpl implements File { private final java.io.File file; public FileImpl(java.io.File file) { this.file = file; } public FileImpl(String fileName) { this.file = new java.io.File(fileName); } public String getName() { return file.getName(); } public String getParent() { return file.getParent(); } public File getParentFile() { return new FileImpl(file.getParentFile()); } public String getPath() { return file.getPath(); } public boolean isAbsolute() { return file.isAbsolute(); } public String getAbsolutePath() { return file.getAbsolutePath(); } public File getAbsoluteFile() { return new FileImpl(file.getAbsoluteFile()); } public String getCanonicalPath() throws IOException { return file.getCanonicalPath(); } public File getCanonicalFile() throws IOException { return new FileImpl(file.getCanonicalFile()); } public URL toURL() throws MalformedURLException { return file.toURL(); } public boolean canRead() { return file.canRead(); } public boolean canWrite() { return file.canWrite(); } public boolean exists() { return file.exists(); } public boolean isDirectory() { return file.isDirectory(); } public boolean isFile() { return file.isFile(); } public boolean isHidden() { return file.isHidden(); } public long lastModified() { return file.lastModified(); } public long length() { return file.length(); } public boolean createNewFile() throws IOException { return file.createNewFile(); } public boolean delete() { return file.delete(); } public void deleteOnExit() { file.deleteOnExit(); } public String[] list() { return file.list(); } public String[] list(FilenameFilter filter) { return file.list(); } public File[] listFiles() { return toAltFileArray(file.listFiles()); } public File[] listFiles(FilenameFilter filter) { return toAltFileArray(file.listFiles(filter)); } public File[] listFiles(FileFilter filter) { return toAltFileArray(file.listFiles(filter)); } private final File[] toAltFileArray(java.io.File[] files) { if(files==null)return null; File[] altFiles = new File[files.length]; for(int i = 0; i < files.length; i++) { altFiles[i] = new FileImpl(files[i]); } return altFiles; } public boolean mkdir() { return file.mkdir(); } public boolean mkdirs() { return file.mkdirs(); } public File createTempFile(String prefix, String suffix, File directory) throws IOException { return new FileImpl(java.io.File.createTempFile(prefix, suffix, directory.getRealFile())); } public File createTempFile(String prefix, String suffix) throws IOException { return new FileImpl(java.io.File.createTempFile(prefix, suffix)); } public File[] listRoots() { return toAltFileArray(java.io.File.listRoots()); } public boolean renameTo(File dest) { return file.renameTo(dest.getRealFile()); } public boolean setLastModified(long time) { return file.setLastModified(time); } public boolean setReadOnly() { return file.setReadOnly(); } public int compareTo(File pathname) { return file.compareTo(pathname.getRealFile()); } public int compareTo(Object o) { return file.compareTo(o); } public java.io.File getRealFile() { return file; } } mockobjects-0.09/src/jdk/common/alt/java/io/IOFactory.java0000755000175000017500000000052507605061414025046 0ustar craftermcrafterm00000000000000package alt.java.io; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; public interface IOFactory { InputStream createInputStream(File aFile) throws FileNotFoundException; OutputStream createOutputStream(File aFile) throws FileNotFoundException; File createFile(String fileName); } mockobjects-0.09/src/jdk/common/alt/java/io/IOFactoryImpl.java0000755000175000017500000000074307605061414025672 0ustar craftermcrafterm00000000000000package alt.java.io; import java.io.*; public class IOFactoryImpl implements IOFactory { public InputStream createInputStream(File aFile) throws FileNotFoundException { return new FileInputStream(aFile.getRealFile()); } public OutputStream createOutputStream(File aFile) throws FileNotFoundException { return new FileOutputStream(aFile.getRealFile()); } public File createFile(String fileName) { return new FileImpl(fileName); } } mockobjects-0.09/src/jdk/common/alt/java/net/0000755000175000017500000000000010117310266022510 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/alt/java/net/Socket.java0000755000175000017500000000236007504121237024613 0ustar craftermcrafterm00000000000000package alt.java.net; import java.net.InetAddress; import java.net.SocketException; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; public interface Socket { InetAddress getInetAddress(); InetAddress getLocalAddress(); int getPort(); int getLocalPort(); InputStream getInputStream() throws IOException; OutputStream getOutputStream() throws IOException; void setTcpNoDelay(boolean on) throws SocketException; boolean getTcpNoDelay() throws SocketException; void setSoLinger(boolean on, int linger) throws SocketException; int getSoLinger() throws SocketException; void setSoTimeout(int timeout) throws SocketException; int getSoTimeout() throws SocketException; void setSendBufferSize(int size) throws SocketException; int getSendBufferSize() throws SocketException; void setReceiveBufferSize(int size) throws SocketException; int getReceiveBufferSize() throws SocketException; void setKeepAlive(boolean on) throws SocketException; boolean getKeepAlive() throws SocketException; void close() throws IOException; void shutdownInput() throws IOException; void shutdownOutput() throws IOException; } mockobjects-0.09/src/jdk/common/alt/java/net/SocketFactory.java0000755000175000017500000000034007504121240026131 0ustar craftermcrafterm00000000000000package alt.java.net; import java.net.UnknownHostException; import java.io.IOException; public interface SocketFactory { Socket createSocket(String aHost, int aPort) throws UnknownHostException, IOException; } mockobjects-0.09/src/jdk/common/alt/java/net/SocketFactoryImpl.java0000755000175000017500000000050707504121240026760 0ustar craftermcrafterm00000000000000package alt.java.net; import java.net.UnknownHostException; import java.io.IOException; public class SocketFactoryImpl implements SocketFactory { public Socket createSocket(String host, int port) throws UnknownHostException, IOException { return new SocketImpl(new java.net.Socket(host, port)); } } mockobjects-0.09/src/jdk/common/alt/java/net/SocketImpl.java0000755000175000017500000000503307504121240025427 0ustar craftermcrafterm00000000000000package alt.java.net; import java.net.InetAddress; import java.net.SocketException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class SocketImpl implements Socket { private final java.net.Socket socket; public SocketImpl(java.net.Socket socket) { this.socket = socket; } public InetAddress getInetAddress() { return socket.getInetAddress(); } public InetAddress getLocalAddress() { return socket.getLocalAddress(); } public int getPort() { return socket.getPort(); } public int getLocalPort() { return socket.getLocalPort(); } public InputStream getInputStream() throws IOException { return socket.getInputStream(); } public OutputStream getOutputStream() throws IOException { return socket.getOutputStream(); } public void setTcpNoDelay(boolean on) throws SocketException { socket.setTcpNoDelay(on); } public boolean getTcpNoDelay() throws SocketException { return socket.getTcpNoDelay(); } public void setSoLinger(boolean on, int linger) throws SocketException { socket.setSoLinger(on, linger); } public int getSoLinger() throws SocketException { return socket.getSoLinger(); } public synchronized void setSoTimeout(int timeout) throws SocketException { socket.setSoTimeout(timeout); } public synchronized int getSoTimeout() throws SocketException { return socket.getSoTimeout(); } public synchronized void setSendBufferSize(int size) throws SocketException { socket.setSendBufferSize(size); } public synchronized int getSendBufferSize() throws SocketException { return socket.getSendBufferSize(); } public synchronized void setReceiveBufferSize(int size) throws SocketException { socket.setReceiveBufferSize(size); } public synchronized int getReceiveBufferSize() throws SocketException { return socket.getReceiveBufferSize(); } public void setKeepAlive(boolean on) throws SocketException { socket.setKeepAlive(on); } public boolean getKeepAlive() throws SocketException { return socket.getKeepAlive(); } public synchronized void close() throws IOException { socket.close(); } public void shutdownInput() throws IOException { socket.shutdownInput(); } public void shutdownOutput() throws IOException { socket.shutdownOutput(); } } mockobjects-0.09/src/jdk/common/alt/java/rmi/0000755000175000017500000000000010117310266022511 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/alt/java/rmi/Naming.java0000644000175000017500000000146307463547117024612 0ustar craftermcrafterm00000000000000package alt.java.rmi; import java.rmi.Remote; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.AlreadyBoundException; public interface Naming { Remote lookup(String name) throws NotBoundException, java.net.MalformedURLException, RemoteException; void bind(String name, Remote obj) throws AlreadyBoundException, java.net.MalformedURLException, RemoteException; void unbind(String name) throws RemoteException, NotBoundException, java.net.MalformedURLException; void rebind(String name, Remote obj) throws RemoteException, java.net.MalformedURLException; String[] list(String name) throws RemoteException, java.net.MalformedURLException; } mockobjects-0.09/src/jdk/common/alt/java/rmi/NamingImpl.java0000644000175000017500000000213607466473266025440 0ustar craftermcrafterm00000000000000package alt.java.rmi; import java.rmi.Remote; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.AlreadyBoundException; public class NamingImpl implements Naming { public Remote lookup(String name) throws NotBoundException, java.net.MalformedURLException, RemoteException { return java.rmi.Naming.lookup(name); } public void bind(String name, Remote obj) throws AlreadyBoundException, java.net.MalformedURLException, RemoteException { java.rmi.Naming.bind(name, obj); } public void unbind(String name) throws RemoteException, NotBoundException, java.net.MalformedURLException { java.rmi.Naming.unbind(name); } public void rebind(String name, Remote obj) throws RemoteException, java.net.MalformedURLException { java.rmi.Naming.rebind(name, obj); } public String[] list(String name) throws RemoteException, java.net.MalformedURLException { return java.rmi.Naming.list(name); } } mockobjects-0.09/src/jdk/common/com/0000755000175000017500000000000010117310266020777 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/0000755000175000017500000000000010117310266023302 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/beans/0000755000175000017500000000000010117310266024372 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/beans/MockPropertyChangeListener.java0000755000175000017500000000404507456044747032541 0ustar craftermcrafterm00000000000000package com.mockobjects.beans; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; /** * Mock object for a PropertyChangeListener. * This mock object can be used in verifying the event propagation mechanism * of beans. You can set the information you expect from a PropertyChangeEvent * as well as the number of events. If you expect more than one event, only the * actual values of the last event are stored. * * @author Ringo De Smet - MediaGeniX NV */ public class MockPropertyChangeListener extends MockObject implements PropertyChangeListener { protected ExpectationValue propertyName; protected ExpectationValue oldValue; protected ExpectationValue newValue; protected ExpectationCounter eventCount; public MockPropertyChangeListener(String name) { propertyName = new ExpectationValue(name + ".propertyName"); oldValue = new ExpectationValue(name + ".oldValue"); newValue = new ExpectationValue(name + ".newValue"); eventCount = new ExpectationCounter(name + ".expectedNrOfEvents"); } public MockPropertyChangeListener() { this("MockPropertyChangeListener"); } public void propertyChange(PropertyChangeEvent event) { propertyName.setActual(event.getPropertyName()); oldValue.setActual(event.getOldValue()); newValue.setActual(event.getNewValue()); eventCount.inc(); } public void setExpectedNewValue(Object expectedNewValue) { newValue.setExpected(expectedNewValue); } public void setExpectedOldValue(Object expectedOldValue) { oldValue.setExpected(expectedOldValue); } public void setExpectedEventCount(int expectedEventCount) { eventCount.setExpected(expectedEventCount); } public void setExpectedPropertyName(String expectedPropertyName) { propertyName.setExpected(expectedPropertyName); } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/0000755000175000017500000000000010117310266023711 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockFile.java0000644000175000017500000001343507645244304026266 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import com.mockobjects.MockObject; import com.mockobjects.ExpectationValue; import com.mockobjects.ReturnValue; import com.mockobjects.ExpectationCounter; import java.io.IOException; import java.io.FilenameFilter; import java.io.FileFilter; import java.net.URL; import java.net.MalformedURLException; import alt.java.io.File; public class MockFile extends MockObject implements File { private final ExpectationValue myFilenameFilter = new ExpectationValue("filename filter"); private final ReturnValue myParent = new ReturnValue("parent"); private final ReturnValue fileName = new ReturnValue("file name"); private final ReturnValue exists = new ReturnValue("exists"); private final ReturnValue mkdirs = new ReturnValue("mkdirs"); private final ReturnValue parentFile = new ReturnValue("parent file"); private final ExpectationCounter mkdirsCounter = new ExpectationCounter("mkdirs counter"); private final ReturnValue myFilesToReturn = new ReturnValue("files"); private final ReturnValue file = new ReturnValue("real file"); private final ReturnValue myPath = new ReturnValue("path"); private final ReturnValue absolutePath = new ReturnValue("absolute path"); public void setupGetName(final String name) { this.fileName.setValue(name); } public String getName() { return (String) fileName.getValue(); } public void setupGetParent(final String aParent) { myParent.setValue(aParent); } public String getParent() { return (String) myParent.getValue(); } public void setupGetParentFile(File parentFile) { this.parentFile.setValue(parentFile); } public File getParentFile() { return (File) parentFile.getValue(); } public File createTempFile(String prefix, String suffix, File directory) throws IOException { notImplemented(); return null; } public File createTempFile(String prefix, String suffix) throws IOException { notImplemented(); return null; } public File[] listRoots() { notImplemented(); return new File[0]; } public void setupGetPath(String aPath) { myPath.setValue(aPath); } public String getPath() { return (String)myPath.getValue(); } public boolean isAbsolute() { notImplemented(); return false; } public void setupGetAbsolutePath(String absolutePath) { this.absolutePath.setValue(absolutePath); } public String getAbsolutePath() { return (String)absolutePath.getValue(); } public File getAbsoluteFile() { notImplemented(); return null; } public String getCanonicalPath() throws IOException { notImplemented(); return null; } public File getCanonicalFile() throws IOException { notImplemented(); return null; } public URL toURL() throws MalformedURLException { notImplemented(); return null; } public boolean canRead() { notImplemented(); return false; } public boolean canWrite() { notImplemented(); return false; } public void setupExists(boolean exists) { this.exists.setValue(exists); } public boolean exists() { return exists.getBooleanValue(); } public boolean isDirectory() { notImplemented(); return false; } public boolean isFile() { notImplemented(); return false; } public boolean isHidden() { notImplemented(); return false; } public long lastModified() { notImplemented(); return 0; } public long length() { notImplemented(); return 0; } public boolean createNewFile() throws IOException { notImplemented(); return false; } public boolean delete() { notImplemented(); return false; } public void deleteOnExit() { notImplemented(); } public String[] list() { notImplemented(); return new String[0]; } public String[] list(FilenameFilter filter) { notImplemented(); return new String[0]; } public File[] listFiles() { notImplemented(); return new File[0]; } public void setExpectedFilenameFilter(FilenameFilter aFilenameFilter) { myFilenameFilter.setExpected(aFilenameFilter); } public void setupListFile(File[] aFilesToReturn) { myFilesToReturn.setValue(aFilesToReturn); } public File[] listFiles(FilenameFilter aFilenameFilter) { myFilenameFilter.setActual(aFilenameFilter); return (File[]) myFilesToReturn.getValue(); } public File[] listFiles(FileFilter filter) { notImplemented(); return new File[0]; } public boolean mkdir() { notImplemented(); return false; } public void setupMkdirs(boolean mkdirs, int count) { mkdirsCounter.setExpected(count); this.mkdirs.setValue(mkdirs); } public boolean mkdirs() { mkdirsCounter.inc(); return mkdirs.getBooleanValue(); } public boolean renameTo(File dest) { notImplemented(); return false; } public boolean setLastModified(long time) { notImplemented(); return false; } public boolean setReadOnly() { notImplemented(); return false; } public int compareTo(File pathname) { notImplemented(); return 0; } public int compareTo(Object o) { notImplemented(); return 0; } public void setupGetRealFile(java.io.File file) { this.file.setValue(file); } public java.io.File getRealFile() { return (java.io.File)file.getValue(); } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockFileInputStream.java0000644000175000017500000000343307644131562030457 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import java.io.*; import junit.framework.*; import com.mockobjects.*; public class MockFileInputStream extends FileInputStream { public static final String KNOWN_FILE = "c:\\autoexec.bat"; private String myContents = ""; private int myIndex = 0; private MockFileInputStream() throws FileNotFoundException { // Unfortunately as there is no interface we have to call the supertype, // which requires a file. super(KNOWN_FILE); } public static MockFileInputStream newMockFileInputStream(){ try { return new MockFileInputStream(); } catch (FileNotFoundException e) { throw new AssertionFailedError("couldn't create MockFileInputStream (requires known file: " + KNOWN_FILE +") "+e); } } public int available() throws IOException { return myContents.length(); } public void mark(int readlimit) { MockObject.notYetImplemented("MockFileInputStream.mark"); } public int read() throws IOException { if (myIndex == myContents.length()) return -1; return myContents.charAt(myIndex++); } public int read(byte b[]) throws IOException { if (myIndex == myContents.length()) return -1; for (int i = 0; i < myContents.length(); i++) { b[i] = (byte) read(); } return myContents.length(); } public int read(byte b[], int off, int len) throws IOException { if (myIndex == myContents.length()) return -1; int bytesRead = 0; for (int i = off; i < len; i++) { b[i] = (byte) myContents.charAt(myIndex); bytesRead++; myIndex++; if (myIndex == myContents.length()) { break; } } return bytesRead; } public void setupContents(String contents) { myContents = contents; myIndex = 0; } public long skip(long n) throws IOException { MockObject.notYetImplemented("MockFileInputStream.skip"); return -1; } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockIOFactory.java0000755000175000017500000000323107612034411027230 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import alt.java.io.File; import alt.java.io.IOFactory; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; import com.mockobjects.ReturnValue; import com.mockobjects.ReturnObjectBag; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; public class MockIOFactory extends MockObject implements IOFactory { private final ReturnObjectBag inputStream = new ReturnObjectBag("input stream"); private final ReturnObjectBag outputStream = new ReturnObjectBag("output stream"); private final ReturnValue file = new ReturnValue("file"); private final ExpectationValue fileName = new ExpectationValue("file name"); public void setupInputStream(File expectedFile, InputStream returnStream) { this.inputStream.putObjectToReturn(expectedFile, returnStream); } public InputStream createInputStream(File aFile) throws FileNotFoundException { return (InputStream)inputStream.getNextReturnObject(aFile); } public void setupOutputStream(File expectedFile, OutputStream returnStream) { this.outputStream.putObjectToReturn(expectedFile, outputStream); } public OutputStream createOutputStream(File aFile) throws FileNotFoundException { return (OutputStream)outputStream.getNextReturnObject(aFile); } public void setupCreateFile(File file) { this.file.setValue(file); } public void setExpectedFileName(String fileName){ this.fileName.setExpected(fileName); } public File createFile(String fileName) { this.fileName.setActual(fileName); return (File)file.getValue(); } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockOutputStream.java0000755000175000017500000000407607637565244030101 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationValue; import com.mockobjects.Verifiable; import com.mockobjects.util.Verifier; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; public class MockOutputStream extends OutputStream implements Verifiable { private ExpectationValue myWriteWasCalled = new ExpectationValue("MockOutputStream.writeWasCalled"); private ExpectationCounter myCloseCalls = new ExpectationCounter("MockOutputStream.close()"); private ExpectationCounter myFlushCalls = new ExpectationCounter("MockOutputStream.flush()"); private ByteArrayOutputStream myBuffer = new ByteArrayOutputStream(); private boolean shouldThrowException = false; public MockOutputStream() { super(); } public void clearActualBuffer() { myBuffer = new ByteArrayOutputStream(); } public void close() throws IOException { myCloseCalls.inc(); } public void flush() throws IOException { myFlushCalls.inc(); } public String getContents() { return myBuffer.toString(); } /** * Added in response to Bug report 546661. */ public byte[] getContentsAsByteArray() { return myBuffer.toByteArray(); } public void setExpectedCloseCalls(int closeCall) { myCloseCalls.setExpected(closeCall); } public void setExpectedFlushCalls(int flushCall) { myFlushCalls.setExpected(flushCall); } public void setExpectingWriteCalls(boolean expectingWriteCall) { myWriteWasCalled.setExpected(expectingWriteCall); } public void setupThrowIOException(boolean throwException) { shouldThrowException = throwException; } public void verify() { Verifier.verifyObject(this); } public void write(int b) throws IOException { myWriteWasCalled.setActual(true); if (shouldThrowException) { throw new IOException("Test IOException generated by request"); } myBuffer.write(b); } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockPrintStream.java0000755000175000017500000000260707635626435027671 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationSegment; import com.mockobjects.util.Verifier; import java.io.OutputStream; import java.io.PrintStream; public class MockPrintStream extends PrintStream { private ExpectationCounter myPrintlnCalls = new ExpectationCounter("MockPrintStream.println calls"); private ExpectationSegment mySegment = new ExpectationSegment("String segment"); private PrintStream myOldErrorStream; public MockPrintStream() { this(null); } public MockPrintStream(OutputStream out) { super(out); } public MockPrintStream(OutputStream out, boolean autoFlush) { super(out, autoFlush); } public void becomeErrorStream() { myOldErrorStream = System.err; System.setErr(this); } public void println(Object anObject) { myPrintlnCalls.inc(); } public void println(String aString) { println((Object) aString); mySegment.setActual(aString); } public void restoreErrorStream() { System.setErr(myOldErrorStream); } public void setExpectedPrintlnCalls(int calls) { myPrintlnCalls.setExpected(calls); } public void setExpectedStringSegment(String aString) { mySegment.setExpected(aString); } public void verify() { Verifier.verifyObject(this); } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockPrintWriter.java0000755000175000017500000000270607561712627027707 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationSegment; import com.mockobjects.Verifiable; import com.mockobjects.util.Verifier; /** * @author steve@m3p.co.uk * @author Francois Beausoleil (fbos@users.sourceforge.net) */ public class MockPrintWriter extends PrintWriter implements Verifiable { private ExpectationSegment mySegment = new ExpectationSegment("String segment"); private ExpectationCounter myCloseCalls = new ExpectationCounter("close calls"); private ExpectationCounter myFlushCalls = new ExpectationCounter("flush calls"); public MockPrintWriter() { this(new StringWriter()); } private MockPrintWriter(Writer writer) { super(writer); } public void setExpectedCloseCalls(int calls) { myCloseCalls.setExpected(calls); } public void setExpectedSegment(String aString) { mySegment.setExpected(aString); } public void write(String s) { super.write(s); mySegment.setActual(s); } public void setExpectedFlushCalls(int calls) { myFlushCalls.setExpected(calls); } public void flush() { super.flush(); myFlushCalls.inc(); } public void close() { super.close(); myCloseCalls.inc(); } public void verify() { Verifier.verifyObject(this); } } mockobjects-0.09/src/jdk/common/com/mockobjects/io/MockWriter.java0000644000175000017500000001316207531162556026662 0ustar craftermcrafterm00000000000000package com.mockobjects.io; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationSegment; import com.mockobjects.Verifiable; import com.mockobjects.util.Verifier; import java.io.IOException; import java.io.Writer; /** * A mock {@link java.io.Writer Writer}. *

Example usage

*

* You may use the MockWriter like this: *

  * public void testSomething() throws IOException {
  *     MockWriter out = new MockWriter();
  *     out.setExpectedSegment("some string");
  *     out.setExpectedFlushCalls(1);
  *     out.setExpectedCloseCalls(1);
  *
  *     ObjectUnderTest testee = new ObjectUnderTest(out);
  *     out.verify();
  *
  *     // If we get here, the mock's flush() and close() methods were
  *     // called exactly once each (order cannot be determined) and
  *     // the write() method was called with the string "some string" in it.
  * }
*

* @author Francois Beausoleil, fbos@users.sourceforge.net */ public class MockWriter extends Writer implements Verifiable { private ExpectationSegment segment = new ExpectationSegment("String segment"); private ExpectationCounter flushCallsCount = new ExpectationCounter("flush calls"); private ExpectationCounter closeCallsCount = new ExpectationCounter("close calls"); private boolean writeShouldThrowException = false; private boolean flushShouldThrowException = false; private boolean closeShouldThrowException = false; /** * Instantiates a new mock writer which will act as a data sink. * Once instantiated, mocks of this class do not expect anything special. * Once the object is instantiated, you should set your expectations using * the provided methods. */ public MockWriter() { // NOTE: We *have* to use the Writer(Object lock) constructor because // Writer() will use this as a lock. When we call // Verifier.verifyObject(MockWriter), it will find the lock field, // which is Verifiable, resulting in an infinite recursion loop... super(new Object()); } /** * Sets the mock's behavior when writing. * If this method has been called, then * {@link #write(char[],int,int) write(char[], int, int)} will throw an * {@link java.io.IOException IOException}. */ public void setWriteShouldThrowException() { writeShouldThrowException = true; } /** * Sets the mock's behavior when flushing. If this method has been called, * then {@link #flush() flush()} will throw * an {@link java.io.IOException IOException}. */ public void setFlushShouldThrowException() { flushShouldThrowException = true; } /** * Sets the mock's behavior when closing. * If this method has been called, then {@link #close() close()} will * throw an {@link java.io.IOException IOException}. */ public void setCloseShouldThrowException() { closeShouldThrowException = true; } /** * Sets the expected number of times that the {@link #flush() flush()} * method will be called. * @see #flush() */ public void setExpectedFlushCalls(int calls) { flushCallsCount.setExpected(calls); } /** * Sets the expected number of times that the {@link #close() close()} * method will be called. * @see #close() */ public void setExpectedCloseCalls(int calls) { closeCallsCount.setExpected(calls); } /** * Sets the value of the expected string segment. * When the {@link #write(char[], int, int) write(char[], int, int)} method * is called, a string is instantiated with the passed array and compared * to the aString parameter of this method. If the two strings * differ, an {@link junit.framework.AssertionFailedError} will be thrown. * @see com.mockobjects.ExpectationSegment * @see #write(char[], int, int) */ public void setExpectedSegment(String aString) { segment.setExpected(aString); } /** * Either throws an exception or asserts a string segment for equality. * @see com.mockobjects.ExpectationSegment * @see #setWriteShouldThrowException(boolean) */ public void write(char cbuf[], int off, int len) throws IOException { if (writeShouldThrowException) { throw new IOException("Mock Exception"); } segment.setActual(new String(cbuf, off, len)); } /** * This method will also throw an {@link java.io.IOException IOException} * if asked to do so by calling * {@link #setFlushShouldThrowException() setFlushShouldThrowException()}. * Please note that the call count will be incremented before the * check for the exception is done. * @see #setExpectedFlushCalls(int) * @see #setFlushShouldThrowException() */ public void flush() throws IOException { flushCallsCount.inc(); if (flushShouldThrowException) { throw new IOException("Mock Exception"); } } /** * Increments the close counter and asserts that this method was not * called too many times. * This method will also throw an {@link java.io.IOException IOException} * if asked to do so by calling * {@link #setCloseShouldThrowException() setCloseShouldThrowException()}. * Please note that the call count will be incremented before the * check for the exception is done. * @see #setExpectedCloseCalls(int) * @see #setCloseShouldThrowException() */ public void close() throws IOException { closeCallsCount.inc(); if (closeShouldThrowException) { throw new IOException("Mock Exception"); } } public void verify() { // WARNING: If the MockWriter calls its parent no-arg constructor, // this call will fail with a StackOverflowError. See constructor // for details. Verifier.verifyObject(this); } } mockobjects-0.09/src/jdk/common/com/mockobjects/net/0000755000175000017500000000000010117310266024070 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/net/MockSocket.java0000755000175000017500000000650407635626435027030 0ustar craftermcrafterm00000000000000package com.mockobjects.net; import alt.java.net.Socket; import com.mockobjects.ExpectationCounter; import com.mockobjects.ExpectationValue; import com.mockobjects.MockObject; import com.mockobjects.ReturnValue; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.SocketException; public class MockSocket extends MockObject implements Socket { private final ExpectationValue mySoTimeout = new ExpectationValue("so timeout"); private final ReturnValue myInputStream = new ReturnValue("input stream"); private final ReturnValue myOutputStream = new ReturnValue("output stream"); private final ExpectationCounter myCloseCalls = new ExpectationCounter("close calls"); public InetAddress getInetAddress() { notImplemented(); return null; } public InetAddress getLocalAddress() { notImplemented(); return null; } public int getPort() { notImplemented(); return 0; } public int getLocalPort() { notImplemented(); return 0; } public void setupGetInputStream(InputStream anInputStream) { myInputStream.setValue(anInputStream); } public InputStream getInputStream() throws IOException { return (InputStream) myInputStream.getValue(); } public void setupGetOutputStream(OutputStream anOutputStream) { myOutputStream.setValue(anOutputStream); } public OutputStream getOutputStream() throws IOException { return (OutputStream) myOutputStream.getValue(); } public void setTcpNoDelay(boolean on) throws SocketException { notImplemented(); } public boolean getTcpNoDelay() throws SocketException { notImplemented(); return false; } public void setSoLinger(boolean on, int linger) throws SocketException { notImplemented(); } public int getSoLinger() throws SocketException { notImplemented(); return 0; } public void setExpectedSoTimeout(int aSoTimeout) { mySoTimeout.setExpected(aSoTimeout); } public void setSoTimeout(int aSoTimeout) throws SocketException { mySoTimeout.setActual(aSoTimeout); } public int getSoTimeout() throws SocketException { notImplemented(); return 0; } public void setSendBufferSize(int size) throws SocketException { notImplemented(); } public int getSendBufferSize() throws SocketException { notImplemented(); return 0; } public void setReceiveBufferSize(int size) throws SocketException { notImplemented(); } public int getReceiveBufferSize() throws SocketException { notImplemented(); return 0; } public void setKeepAlive(boolean on) throws SocketException { notImplemented(); } public boolean getKeepAlive() throws SocketException { notImplemented(); return false; } public void setExpectedCloseCalls(int aCount) { myCloseCalls.setExpected(aCount); } public void close() throws IOException { myCloseCalls.inc(); } public void shutdownInput() throws IOException { notImplemented(); } public void shutdownOutput() throws IOException { notImplemented(); } } mockobjects-0.09/src/jdk/common/com/mockobjects/net/MockSocketFactory.java0000755000175000017500000000167007635626435030357 0ustar craftermcrafterm00000000000000package com.mockobjects.net; import alt.java.net.SocketFactory; import alt.java.net.Socket; import com.mockobjects.MockObject; import com.mockobjects.ExpectationValue; import com.mockobjects.ReturnValue; public class MockSocketFactory extends MockObject implements SocketFactory { private final ExpectationValue myHost = new ExpectationValue("host"); private final ExpectationValue myPort = new ExpectationValue("port"); private final ReturnValue mySocket = new ReturnValue("socket"); public void setupCreateSocket(Socket aSocket) { mySocket.setValue(aSocket); } public void setExpectedHost(String aHost) { myHost.setExpected(aHost); } public void setExpectedPort(String aPort) { myPort.setExpected(aPort); } public Socket createSocket(String aHost, int aPort) { myHost.setActual(aHost); myPort.setActual(aPort); return (Socket) mySocket.getValue(); } } mockobjects-0.09/src/jdk/common/com/mockobjects/rmi/0000755000175000017500000000000010117310266024071 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/rmi/MockNaming.java0000644000175000017500000000277407504121241026770 0ustar craftermcrafterm00000000000000package com.mockobjects.rmi; import com.mockobjects.*; import com.mockobjects.util.AssertMo; import java.rmi.Remote; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.NotBoundException; import java.net.MalformedURLException; import java.util.Vector; import alt.java.rmi.Naming; public class MockNaming extends MockObject implements Naming { private final ReturnObjectList myRemotes = new ReturnObjectList("remotes"); private final ExpectationValue myName = new ExpectationValue("name"); public void bind(String name, Remote obj) throws AlreadyBoundException, MalformedURLException, RemoteException { notImplemented(); } public void setupAddLookup(Remote aRemote){ myRemotes.addObjectToReturn(aRemote); } public void setExpectedLookupName(String aName){ myName.setExpected(aName); } public Remote lookup(String name) throws NotBoundException, MalformedURLException, RemoteException { myName.setActual(name); return (Remote)myRemotes.nextReturnObject(); } public void unbind(String name) throws RemoteException, NotBoundException, MalformedURLException { notImplemented(); } public void rebind(String name, Remote obj) throws RemoteException, MalformedURLException { notImplemented(); } public String[] list(String name) throws RemoteException, MalformedURLException { notImplemented(); return new String[0]; } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/0000755000175000017500000000000010117310266024101 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockCallableStatement.java0000644000175000017500000002672207612034526032334 0ustar craftermcrafterm00000000000000/* * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ // ------------------------------------------------------------------------ 78 package com.mockobjects.sql; import java.sql.*; import java.util.Calendar; import java.io.Reader; import java.io.InputStream; import java.math.BigDecimal; import java.net.URL; import com.mockobjects.*; abstract class CommonMockCallableStatement extends CommonMockPreparedStatement implements CallableStatement { public void registerOutParameter(int parameterIndex, int sqlType) { notImplemented(); } public void registerOutParameter(int parameterIndex, int sqlType, int scale) { notImplemented(); } public void registerOutParameter(int parameterIndex, int sqlType, String typeName) { notImplemented(); } public void registerOutParameter(String parameterName, int sqlType) { notImplemented(); } public void registerOutParameter(String parameterName, int sqlType, int scale) { notImplemented(); } public void registerOutParameter(String parameterName, int sqlType, String typeName) { notImplemented(); } public boolean wasNull() { notImplemented(); return false; } public String getString(int parameterIndex) { notImplemented(); return null; } public String getString(String parameterName) { notImplemented(); return null; } public boolean getBoolean(int parameterIndex) { notImplemented(); return false; } public boolean getBoolean(String parameterName) { notImplemented(); return false; } public byte getByte(int parameterIndex) { notImplemented(); return 0; } public byte getByte(String parameterName) { notImplemented(); return 0; } public short getShort(int parameterIndex) { notImplemented(); return 0; } public short getShort(String parameterName) { notImplemented(); return 0; } public int getInt(int parameterIndex) { notImplemented(); return 0; } public int getInt(String parameterName) { notImplemented(); return 0; } public long getLong(int parameterIndex) { notImplemented(); return 0; } public long getLong(String parameterName) { notImplemented(); return 0; } public float getFloat(int parameterIndex) { notImplemented(); return 0; } public float getFloat(String parameterName) { notImplemented(); return 0; } public double getDouble(int parameterIndex) { notImplemented(); return 0; } public double getDouble(String parameterName) { notImplemented(); return 0; } public BigDecimal getBigDecimal(int parameterIndex) { notImplemented(); return null; } public BigDecimal getBigDecimal(String parameterName) { notImplemented(); return null; } public BigDecimal getBigDecimal(int parameterIndex, int scale) { notImplemented(); return null; } public byte[] getBytes(int parameterIndex) { notImplemented(); return null; } public byte[] getBytes(String parameterName) { notImplemented(); return null; } public Date getDate(int parameterIndex) { notImplemented(); return null; } public Date getDate(String parameterName) { notImplemented(); return null; } public Date getDate(int parameterIndex, Calendar cal) { notImplemented(); return null; } public Date getDate(String parameterName, Calendar cal) { notImplemented(); return null; } public Time getTime(int parameterIndex) { notImplemented(); return null; } public Time getTime(String parameterName) { notImplemented(); return null; } public Time getTime(int parameterIndex, Calendar cal) { notImplemented(); return null; } public Time getTime(String parameterName, Calendar cal) { notImplemented(); return null; } public Timestamp getTimestamp(int parameterIndex) { notImplemented(); return null; } public Timestamp getTimestamp(String parameterName) { notImplemented(); return null; } public Timestamp getTimestamp(int parameterIndex, Calendar cal) { notImplemented(); return null; } public Timestamp getTimestamp(String parameterName, Calendar cal) { notImplemented(); return null; } public Object getObject(int parameterIndex) { notImplemented(); return null; } public Object getObject(String parameterName) { notImplemented(); return null; } public Object getObject(int parameterIndex, java.util.Map map) { notImplemented(); return null; } public Object getObject(String parameterName, java.util.Map map) { notImplemented(); return null; } public Ref getRef(int parameterIndex) { notImplemented(); return null; } public Ref getRef(String parameterName) { notImplemented(); return null; } public Blob getBlob(int parameterIndex) { notImplemented(); return null; } public Blob getBlob(String parameterName) { notImplemented(); return null; } public Clob getClob(int parameterIndex) { notImplemented(); return null; } public Clob getClob(String parameterName) { notImplemented(); return null; } public Array getArray(int parameterIndex) { notImplemented(); return null; } public Array getArray(String parameterName) { notImplemented(); return null; } public URL getURL(int parameterIndex) { notImplemented(); return null; } public URL getURL(String parameterName) { notImplemented(); return null; } public void setAsciiStream(String parameterName, InputStream x, int length) { notImplemented(); } public void setBigDecimal(String parameterName, BigDecimal x) { notImplemented(); } public void setBinaryStream(String parameterName, InputStream x, int length) { notImplemented(); } public void setBoolean(String parameterName, boolean x) { notImplemented(); } public void setByte(String parameterName, byte x) { notImplemented(); } public void setBytes(String parameterName, byte[] x) { notImplemented(); } public void setCharacterStream(String parameterName, Reader reader, int length) { notImplemented(); } public void setDate(String parameterName, Date x) { notImplemented(); } public void setDate(String parameterName, Date x, Calendar cal) { notImplemented(); } public void setDouble(String parameterName, double x) { notImplemented(); } public void setFloat(String parameterName, float x) { notImplemented(); } public void setInt(String parameterName, int x) { notImplemented(); } public void setLong(String parameterName, long x) { notImplemented(); } public void setNull(String parameterName, int sqlType) { notImplemented(); } public void setNull(String parameterName, int sqlType, String typeName) { notImplemented(); } public void setObject(String parameterName, Object x) { notImplemented(); } public void setObject(String parameterName, Object x, int targetSqlType) { notImplemented(); } public void setObject(String parameterName, Object x, int targetSqlType, int scale) { notImplemented(); } public void setShort(String parameterName, short x) { notImplemented(); } public void setString(String parameterName, String x) { notImplemented(); } public void setTime(String parameterName, Time x) { notImplemented(); } public void setTime(String parameterName, Time x, Calendar cal) { notImplemented(); } public void setTimestamp(String parameterName, Timestamp x) { notImplemented(); } public void setTimestamp(String parameterName, Timestamp x, Calendar cal) { notImplemented(); } public void setURL(String parameterName, URL val) { notImplemented(); } }mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockConnection.java0000755000175000017500000004117107625414342031047 0ustar craftermcrafterm00000000000000/* * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ // ------------------------------------------------------------------------ 78 /** * Abstract Connection for use with mock testing. * Can verify the expected SQL strings with PreparedStatement or Statement * instances (mock versions can be used). * Can verify the state of closed and autoCommit. * Can verify the number of calls to close, commit, createStatement, and * rollBack. * Exceptions to throw can be registered for calling createStatement, * preparedStatement, or close. * Several less-often-used methods are not implemented. * If a notImplemented method is needed for your project, please submit * a patch. * @see javax.sql.Connection * @author * @author Jeff Martin * @author Ted Husted * @version $Revision: 1.7 $ $Date: 2003/02/21 12:17:38 $ */ package com.mockobjects.sql; import com.mockobjects.*; import java.sql.*; import java.util.Map; abstract class CommonMockConnection extends MockObject implements Connection { // -------------------------------------------------------------------- fields private boolean autoCommit = false; private final ExpectationValue myResultSetConcurrency; private final ExpectationValue myResultSetType; private final ExpectationList myAutoCommit; private final ExpectationCounter myCloseCalls; private final ExpectationCounter myCommitCalls; private final ExpectationCounter myCreateStatementCalls; private boolean myIsClosed; private SQLException myCloseException; private SQLException myIsClosedException; private DatabaseMetaData myMetaData; /** * @deprecated * @see CommonMockConnection2 */ private final ReturnObjectList myPreparedStatements; /** * @deprecated use myPreparedStatementsBag * @see CommonMockConnection2 */ private final ExpectationCollection myPreparedStatementStrings; private final ExpectationCounter myRollbackCalls; private Statement myStatement; private SQLException myStatementException = null; public CommonMockConnection() { this(CommonMockConnection.class.getName()); } public CommonMockConnection(String name) { myAutoCommit = new ExpectationList(name + ".setAutoCommit"); myCloseCalls = new ExpectationCounter(name + ".close"); myCommitCalls = new ExpectationCounter(name + ".commit"); myCreateStatementCalls = new ExpectationCounter(name + ".createStatement"); myPreparedStatements = new ReturnObjectList(name + ".PreparedStatements"); myPreparedStatementStrings = new ExpectationList(name + ".preparedStatementString"); myRollbackCalls = new ExpectationCounter(name + ".rollback"); myResultSetType = new ExpectationValue(name + ".resultSetType"); myResultSetConcurrency = new ExpectationValue(name + ".resultSetConcurrency"); } /** * @deprecated * Add an SQL string to use with a prepared staement. */ public void addExpectedPreparedStatementString(String sql) { myPreparedStatementStrings.addExpected(sql); } // --------------------------------------------------------------- setExpected /** * Register the anticipated value for autoCommit during testing. */ public void addExpectedAutoCommit(boolean autoCommit) { myAutoCommit.addExpected(new Boolean(autoCommit)); } /** * Register the number of close calls the test should make. * The valid method will report any discrepancy with the * actual count. */ public void setExpectedCloseCalls(int callCount) { myCloseCalls.setExpected(callCount); } /** * Register the number of commit calls the test should make. * The valid method will report any discrepancy with the * actual count. */ public void setExpectedCommitCalls(int callCount) { myCommitCalls.setExpected(callCount); } /** * Register the number of create statement calls the test should make. * The valid method will report any discrepancy with the * actual count. */ public void setExpectedCreateStatementCalls(int calls) { myCreateStatementCalls.setExpected(calls); } /** * Register the number of roll back calls the test should make. * The valid method will report any discrepancy with the * actual count. */ public void setExpectedRollbackCalls(int callCount) { myRollbackCalls.setExpected(callCount); } // --------------------------------------------------------------------- setup /** * Sets expectations about the possible value of the * resultSetConcurrency parameter of * {@link #createStatement(int, int) createStatement()} calls. * * @param resultSetConcurrency One of the constants starting with CONCUR * in {@link java.sql.ResultSet}. */ public void setExpectedResultSetConcurrency(int resultSetConcurrency) { myResultSetConcurrency.setExpected(resultSetConcurrency); } /** * Sets expectations about the possible value of the * resultSetType parameter of * {@link #createStatement(int, int) createStatement()} calls. * * @param resultSetType One of the constants starting with TYPE * in {@link java.sql.ResultSet}. */ public void setExpectedResultSetType(int resultSetType) { myResultSetType.setExpected(resultSetType); } /** * @deprecated * Adds a PreparedStatement to be return by prepareStatement * @see CommonMockConnection2 */ public void setupAddPreparedStatement(PreparedStatement prepared) { myPreparedStatements.addObjectToReturn(prepared); } /** * Pass the SQL exception to throw if close is called * during a test. */ public void setupCloseException(SQLException aCloseException) { myCloseException = aCloseException; } /** * @deprecated Use setupIsClosed */ public void setupIsClose(boolean aIsClosed) { myIsClosed = aIsClosed; } /** * Pass the value to return if isClosed is called during a test. * This is returned unless an isClosedException has been set. */ public void setupIsClosed(boolean aIsClosed) { myIsClosed = aIsClosed; } /** * Pass the SQL exception instance to throw if isClosed * is called during a test. */ public void setupIsClosedException(SQLException aIsClosedException) { myIsClosedException = aIsClosedException; } /** * Pass the DataBaseMetaData instance for use with tests. */ public void setupMetaData(DatabaseMetaData metaData) { myMetaData = metaData; } /** * Pass the Statement instance for use with tests. */ public void setupStatement(Statement statement) { myStatement = statement; } /** * Pass the SQL exception to throw if preparedStatement or createStatement * is called during a test. */ public void setupThrowExceptionOnPrepareOrCreate(SQLException exception) { myStatementException = exception; } public void setupAutoCommit(boolean autoCommitToReturn) { autoCommit = autoCommitToReturn; } // --------------------------------------------------------------------- throw /** * Throw the Statement instance passed to * setupThrowExceptionOnPrepareOrCreate, if any. */ void throwStatementExceptionIfAny() throws SQLException { if (null != myStatementException) { throw myStatementException; } } // --------------------------------------------------------------- implemented /** * Will throw the CloseException if it has been set, * or otherwise increment the number or close calls. */ public void close() throws SQLException { if (myCloseException != null) { throw myCloseException; } myCloseCalls.inc(); } /** * Increments the number of commit calls. */ public void commit() throws SQLException { myCommitCalls.inc(); } /** * Will throw either of the statement exceptions if one has been * set, * or otherwise return the Statement passed to * setupStatement. */ public Statement createStatement() throws SQLException { myCreateStatementCalls.inc(); throwStatementExceptionIfAny(); return myStatement; } /** * Returns the DatabaseMetaData instance passed to setupMetaData. */ public DatabaseMetaData getMetaData() throws SQLException { return myMetaData; } /** * Throw the isClosedException if it has been set, * or otherwise return the value passed to setupIsClosed. */ public boolean isClosed() throws SQLException { if (myIsClosedException != null) { throw myIsClosedException; } return myIsClosed; } /** * Throws a statement exception if one has been registered * (@see throwStatementExceptionIfAny) * or returns the next PreparedStatement instance passed to * setupAddPreparedStatement. */ public PreparedStatement prepareStatement(String sql) throws SQLException { myPreparedStatementStrings.addActual(sql); throwStatementExceptionIfAny(); return (PreparedStatement) myPreparedStatements.nextReturnObject(); } /** * Increments the number of roll back calls. */ public void rollback() throws SQLException { myRollbackCalls.inc(); } /** * Stores the value passed for comparison with the value passed * to setupAutoCommit. * The validate method will report any discrepency. */ public void setAutoCommit(boolean autoCommit) throws SQLException { myAutoCommit.addActual(new Boolean(autoCommit)); } // ------------------------------------------------------------ notImplemented /** * Calls notImplemented. */ public void clearWarnings() throws SQLException { notImplemented(); } /** * Calls notImplemented. Returns null. */ public Statement createStatement( int resultSetType, int resultSetConcurrency) throws SQLException { myCreateStatementCalls.inc(); throwStatementExceptionIfAny(); myResultSetType.setActual(resultSetType); myResultSetConcurrency.setActual(resultSetConcurrency); return myStatement; } public boolean getAutoCommit() throws SQLException { return autoCommit; } /** * Calls notImplemented. Returns null. */ public String getCatalog() throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns 0. */ public int getTransactionIsolation() throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns null. */ public Map getTypeMap() throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. */ public SQLWarning getWarnings() throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns false. */ public boolean isReadOnly() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns null. */ public String nativeSQL(String sql) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. */ public CallableStatement prepareCall(String sql) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. */ public CallableStatement prepareCall( String sql, int resultSetType, int resultSetConcurrency) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. */ public PreparedStatement prepareStatement( String sql, int resultSetType, int resultSetConcurrency) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. */ public void setCatalog(String catalog) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setReadOnly(boolean readOnly) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setTransactionIsolation(int level) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setTypeMap(Map map) throws SQLException { notImplemented(); } public void setHoldability(int holdability) throws SQLException { notImplemented(); } public int getHoldability() throws SQLException { notImplemented(); return 0; } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { notImplemented(); return null; } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { notImplemented(); return null; } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { notImplemented(); return null; } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { notImplemented(); return null; } public PreparedStatement prepareStatement(String sql, int columnIndexes[]) throws SQLException { notImplemented(); return null; } public PreparedStatement prepareStatement(String sql, String columnNames[]) throws SQLException { notImplemented(); return null; } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockConnection2.java0000644000175000017500000001120707575157335031135 0ustar craftermcrafterm00000000000000/* * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ // ------------------------------------------------------------------------ 78 /** * Abstract Connection for use with mock testing. * Can verify the expected SQL strings with PreparedStatement or Statement * instances (mock versions can be used). * Can verify the state of closed and autoCommit. * Can verify the number of calls to close, commit, createStatement, and * rollBack. * Exceptions to throw can be registered for calling createStatement, * preparedStatement, or close. * Several less-often-used methods are not implemented. * If a notImplemented method is are needed for your project, please submit * a patch. * @see javax.sql.Connection * @author * @author Jeff Martin * @author Ted Husted * @version $Revision: 1.2 $ $Date: 2002/12/09 18:20:13 $ */ package com.mockobjects.sql; import com.mockobjects.ReturnObjectBag; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; abstract class CommonMockConnection2 extends CommonMockConnection implements Connection { private final ReturnObjectBag myPreparedStatements; public CommonMockConnection2() { this(CommonMockConnection2.class.getName()); } public CommonMockConnection2(String name) { super(name); myPreparedStatements = new ReturnObjectBag(name+".preparedStatements"); } /** * Adds a PreparedStatement to be return by prepareStatement */ public void setupAddPreparedStatement(String sql, PreparedStatement prepared) { myPreparedStatements.putObjectToReturn(sql, prepared); } /** * Throws a statement exception if one has been registered * (@see throwStatementExceptionIfAny) * or returns the next PreparedStatement instance passed to * setupAddPreparedStatement. */ public PreparedStatement prepareStatement(String sql) throws SQLException { throwStatementExceptionIfAny(); return (PreparedStatement) myPreparedStatements.getNextReturnObject(sql); } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockMultiRowResultSet.java0000755000175000017500000000430707645244563032415 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import com.mockobjects.util.AssertMo; import java.sql.SQLException; /** * This is a simple implementation of a MockResultSet. * It returns values for multiple rows. * @version $Revision: 1.4 $ */ abstract class CommonMockMultiRowResultSet extends MockResultSet { private Object[][] myRows = new Object[0][0]; private String[] myColumnNames; private int myRowOffset = -1; private SQLException myGetException = null; public CommonMockMultiRowResultSet() { super(); } /** * @param name Label used to identify mock when it errors */ public CommonMockMultiRowResultSet(String name) { super(name); } public void setupColumnNames(String[] columnNames) { myColumnNames = columnNames; } public void setupRows(Object[][] rows) { myRows = rows; } public void setupThrowExceptionOnGet(SQLException exception) { myGetException = exception; } public Object getObject(int columnIndex) throws SQLException { throwGetExceptionIfAny(); if (columnIndex > myRows[myRowOffset].length || columnIndex < 1) { AssertMo.fail("Column " + columnIndex + " not found in " + name); } return myRows[myRowOffset][columnIndex - 1]; } public Object getObject(String columnName) throws SQLException { throwGetExceptionIfAny(); return getObject(findIndexForColumnName(columnName)); } public boolean next() throws SQLException { myNextCalls.inc(); if (myRowOffset + 1 >= myRows.length) { return false; } myRowOffset++; return true; } public int getRow() throws SQLException { return myRowOffset + 1; } private void throwGetExceptionIfAny() throws SQLException { if (null != myGetException) { throw myGetException; } } private int findIndexForColumnName(String columnName) throws SQLException { for (int i = 0; i < myColumnNames.length; ++i) { if (myColumnNames[i].equalsIgnoreCase(columnName)) { return i + 1; } } throw new SQLException("Column name not found"); } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockPreparedStatement.java0000755000175000017500000002461707651477216032415 0ustar craftermcrafterm00000000000000/* * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ // ------------------------------------------------------------------------ 78 package com.mockobjects.sql; import java.sql.*; import java.util.Calendar; import java.io.Reader; import java.math.BigDecimal; import com.mockobjects.*; /** * Abstract PreparedStatement for use with mock testing. * If a notImplemented method is are needed for your project, * please submit a patch. * @see java.sql.PreparedStatement * @author Jeff Martin * @author Ted Husted * @version $Revision: 1.4 $ $Date: 2003/04/23 11:52:46 $ */ abstract class CommonMockPreparedStatement extends CommonMockStatement implements PreparedStatement { private ExpectationSet mySetParameters = new ExpectationSet("CommonMockPreparedStatement.setParameters"); private ExpectationCounter myClearParametersCalls = new ExpectationCounter ("CommonMockPreparedStatement.clearParameters() calls"); private ExpectationSet myTargetSQLTypes = new ExpectationSet("CommonMockPreparedStatement.targetSQLTypes"); private final ReturnObjectList myResultSets = new ReturnObjectList("result sets"); private final ReturnObjectList executeUpdates = new ReturnObjectList("update count"); public void addResultSet(MockResultSet aResultSet) { myResultSets.addObjectToReturn(aResultSet); } public void addExpectedSetParameter(int parameterIndex, int intValue) { addExpectedSetParameter(parameterIndex, new Integer(intValue)); } public void addExpectedSetParameter(int parameterIndex, Object parameterValue) { mySetParameters.addExpected(new MapEntry(new Integer(parameterIndex), parameterValue)); } public void addExpectedSetParameters(Object[] parameters) { for (int i = 0; i < parameters.length; ++i) { addExpectedSetParameter(i + 1, parameters[i]); } } public void addExpectedTargetSQLType(int aTargetSQLType){ myTargetSQLTypes.addExpected(new Integer(aTargetSQLType)); } // -------------------------------------------------------------- setExpected* public void setExpectedClearParametersCalls(int callCount) { myClearParametersCalls.setExpected(callCount); } public void setExpectingNoSetParameters() { mySetParameters.setExpectNothing(); } // --------------------------------------------------------------- implemented public void clearParameters() throws SQLException { myClearParametersCalls.inc(); } /** * Calls innerExecute() (see CommonMockStatement). Returns false. */ public boolean execute() throws SQLException { innerExecute(); return false; } /** * Returns executeQuery(String) with an empty String. */ public ResultSet executeQuery() throws SQLException { innerExecute(); return (ResultSet)myResultSets.nextReturnObject(); } /** * Added value to be returned by executeUpdate() * @param count * @see #executeUpdate */ public void addUpdateCount(int count){ this.executeUpdates.addObjectToReturn(count); } /** * Returns value set with addUpdateCount * @see #addUpdateCount */ public int executeUpdate() throws SQLException { innerExecute(); return ((Integer)executeUpdates.nextReturnObject()).intValue(); } public void setInt(int parameterIndex, int x) throws SQLException { setObject(parameterIndex, new Integer(x)); } public void setString(int parameterIndex, String x) throws SQLException { setObject(parameterIndex, x); } public void setTimestamp(int param, Timestamp timestamp) throws SQLException { setObject(param, timestamp); } public void setClob(int param, Clob clob) throws SQLException { setObject(param, clob); } public void setLong(int param, long aLong) throws SQLException { setObject(param, new Long(aLong)); } public void setNull(int param, int param1) throws SQLException { setObject(param, null); } public void setArray(int param, Array array) throws SQLException { setObject(param, array); } public void setShort(int param, short aShort) throws SQLException { setObject(param, new Short(aShort)); } public void setTime(int param, Time time, Calendar calendar) throws SQLException { setObject(param, time); } public void setObject(int param, Object anObject, int aTargetSQLType) throws SQLException { setObject(param, anObject); myTargetSQLTypes.addActual(new Integer(aTargetSQLType)); } public void setRef(int param, Ref ref) throws SQLException { setObject(param, ref); } public void setDate(int param, Date date) throws SQLException { setObject(param, date); } public void setFloat(int param, float aFloat) throws SQLException { setObject(param, new Float(aFloat)); } public void setBlob(int param, Blob blob) throws SQLException { setObject(param, blob); } public void setDate(int param, Date date, Calendar calendar) throws SQLException { setDate(param, date); } public void setBytes(int param, byte[] values) throws SQLException { setObject(param, values); } public void setObject(int param, Object anObject) throws SQLException { mySetParameters.addActual(new MapEntry(new Integer(param), anObject)); } public void setByte(int param, byte aByte) throws SQLException { setObject(param, new Byte(aByte)); } public void setDouble(int param, double aDouble) throws SQLException { setObject(param, new Double(aDouble)); } public void setTime(int param, Time time) throws SQLException { setObject(param, time); } public void setBoolean(int param, boolean aBoolean) throws SQLException { setObject(param, new Boolean(aBoolean)); } public void setBigDecimal(int param, BigDecimal bigDecimal) throws SQLException { setObject(param, bigDecimal); } // ------------------------------------------------------------ notImplemented /** * Calls notImplemented. */ public void addBatch() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setObject(int param, Object anObject, int targetSqlType, int scale) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setCharacterStream(int param, Reader reader, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setAsciiStream(int param, java.io.InputStream inputStream, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setBinaryStream(int param, java.io.InputStream inputStream, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setNull(int param, int param1, String typeName) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setUnicodeStream(int param, java.io.InputStream inputStream, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. Returns null. */ public ResultSetMetaData getMetaData() throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. */ public void setTimestamp(int param, Timestamp timestamp, Calendar calendar) throws SQLException { notImplemented(); } } // end CommonMockPreparedStatement mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockResultSetMetaData.java0000644000175000017500000002156007577222433032304 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import com.mockobjects.MockObject; import com.mockobjects.ReturnObjectList; import com.mockobjects.ExpectationList; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * @version $Revision: 1.3 $ */ class CommonMockResultSetMetaData extends MockObject implements ResultSetMetaData { private final ReturnObjectList myNames = new ReturnObjectList("MockResultSetMetaData.columnNames"); private final ReturnObjectList myTypes = new ReturnObjectList("MockResultSetMetaData.columnTypes"); private final ReturnObjectList myClassNames = new ReturnObjectList("MockResultSetMetaData.columnClassNames"); private int myColumnCount; private final ExpectationList myColumnTypeIndexes = new ExpectationList("Column Type Indexes"); private final ExpectationList myColumnNameIndexes = new ExpectationList("Column Name Indexes"); private final ExpectationList myColumnClassNameIndexes = new ExpectationList("Column Class Name Indexes"); /** * Value to return from getColumnCount. */ public void setupGetColumnCount(int aColumnCount) { myColumnCount = aColumnCount; } /** * An array of column names in the order they appear in the * resultSet. */ public void setupAddColumnNames(String[] allNames) { if (allNames != null) { for (int i = 0; i < allNames.length; i++) { setupAddColumnName(allNames[i]); } } } /** * The next column name in the resultSet. */ public void setupAddColumnName(String aName) { this.myNames.addObjectToReturn(aName); } /** * An array of column SQL types in the order they appear in the * resultSet. */ public void setupAddColumnTypes(int[] allTypes) { if (allTypes != null) { for (int i = 0; i < allTypes.length; i++) { setupAddColumnType(allTypes[i]); } } } /** * The next column's SQL type in the resultSet as an int. */ public void setupAddColumnType(int aType) { this.myTypes.addObjectToReturn(aType); } /** * Returns value passed to setupGetColumnCount. * @see ResultSetMetaData#getColumnCount() */ public int getColumnCount() throws SQLException { return myColumnCount; } /** * Returns the column name. * DOES NOT SUPPORT THE aColumnIndex PARAMETER. * You must call getColumnName in order, first to last. * Column names may be added with setupAddColumnName. * or setupAddColumnNames. * @see ResultSetMetaData#getColumnName(int) */ public String getColumnName(int aColumnIndex) throws SQLException { myColumnNameIndexes.addActual(aColumnIndex); return (String) myNames.nextReturnObject(); } /** * Adds an expectation for a column index to be passed to getColumnName * @see MockResultSetMetaData#getColumnName(int) */ public void addExpectedColumnNameIndex(int aColumnIndex){ myColumnNameIndexes.addExpected(aColumnIndex); } /** * Returns the column SQL type. * DOES NOT SUPPORT THE aColumnIndex PARAMETER. * You must call getColumnType in order, first to last. * Column SQL types may be added with setupAddColumnType. * @see ResultSetMetaData#getColumnType(int) */ public int getColumnType(int aColumnIndex) throws SQLException { myColumnTypeIndexes.addActual(aColumnIndex); return ((Integer) myTypes.nextReturnObject()).intValue(); } /** * Adds an expectation for a column index to be passed to getColumnType * @see MockResultSetMetaData#getColumnType(int) */ public void addExpectedColumnTypeIndex(int aColumnIndex){ myColumnTypeIndexes.addExpected(aColumnIndex); } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isAutoIncrement(int) */ public boolean isAutoIncrement(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isCaseSensitive(int) */ public boolean isCaseSensitive(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isSearchable(int) */ public boolean isSearchable(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isCurrency(int) */ public boolean isCurrency(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isNullable(int) */ public int isNullable(int arg0) throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isSigned(int) */ public boolean isSigned(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns 0. * @see ResultSetMetaData#getColumnDisplaySize(int) */ public int getColumnDisplaySize(int arg0) throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns null. * @see ResultSetMetaData#getColumnLabel(int) */ public String getColumnLabel(int arg0) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. * @see ResultSetMetaData#getColumnTypeName(int) */ public String getColumnTypeName(int arg0) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. * @see ResultSetMetaData#getSchemaName(int) */ public String getSchemaName(int arg0) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns 0. * @see ResultSetMetaData#getPrecision(int) */ public int getPrecision(int arg0) throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns 0. * @see ResultSetMetaData#getScale(int) */ public int getScale(int arg0) throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns null. * @see ResultSetMetaData#getTableName(int) */ public String getTableName(int arg0) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. * @see ResultSetMetaData#getCatalogName(int) */ public String getCatalogName(int arg0) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isReadOnly(int) */ public boolean isReadOnly(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isWritable(int) */ public boolean isWritable(int arg0) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. * @see ResultSetMetaData#isDefinitelyWritable(int) */ public boolean isDefinitelyWritable(int arg0) throws SQLException { notImplemented(); return false; } /** * An array of column class names in the order they appear in the * resultSet. */ public void setupAddColumnClassNames(String[] allNames) { if (allNames != null) { for (int i = 0; i < allNames.length; i++) { setupAddColumnClassName(allNames[i]); } } } /** * The next column class name in the resultSet. */ public void setupAddColumnClassName(String aName) { this.myClassNames.addObjectToReturn(aName); } /** * Returns the column class name. * DOES NOT SUPPORT THE aColumnIndex PARAMETER. * You must call getColumnClassName in order, first to last. * Column class names may be added with setupAddColumnClassName. * or setupAddColumnClassNames. * @see ResultSetMetaData#getColumnClassName(int) */ public String getColumnClassName(int aColumnIndex) throws SQLException { myColumnClassNameIndexes.addActual(aColumnIndex); return (String) myClassNames.nextReturnObject(); } /** * Adds an expectation for a column index to be passed to getColumnClassName * @see MockResultSetMetaData#getColumnClassName(int) */ public void addExpectedColumnClassNameIndex(int aColumnIndex){ myColumnClassNameIndexes.addExpected(aColumnIndex); } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockSingleRowResultSet.java0000755000175000017500000001460607575157333032547 0ustar craftermcrafterm00000000000000/* * * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */ // ------------------------------------------------------------------------ 78 package com.mockobjects.sql; import java.sql.SQLException; import java.util.Map; /** * Implementation of a MockResultSet that uses the ExpectationRow * object to simulate a ResultSet that returns a single row. * It verifies that the values fed to it have been retrieved * throw a call to next and getRow. * Column values can be retrieved using any of the getters * declared in MockResultSet. * Depending on which constructor is used, * these can be found by either column index or column name. * For basic java types (e.g. int, boolean), insert an instance of * the appropriate object (e.g. Integer, Boolean). * To force throwing a SQLException on a getter, * set the corresponding value to be of type SQLException. * @author Jeff Martin * @author Ted Husted * @version $Revision: 1.3 $ */ abstract class CommonMockSingleRowResultSet extends MockResultSet { // -------------------------------------------------------------------- fields private ExpectationSqlRow myRow = new ExpectationSqlRow("CommonMockSingleRowResultSet.SqlRow"); private int myNextCallCount = 0; // -------------------------------------------------------------- addExpected* /** * Add expected values from an array to be retrieved by index. */ public void addExpectedIndexedValues(Object[] values) { myRow.addExpectedIndexedValues(values); } /** * Add expected values from an array to be retrieved by name or * index. */ public void addExpectedNamedValues(String[] names, Object[] values) { myRow.addExpectedNamedValues(names, values); } /** * Add expected values from a Map to be retrieved by name or * index. */ public void addExpectedNamedValues(Map map) { myRow.addExpectedNamedValues(map); } // -------------------------------------------------------------- constructors /** * Default constructor. * Call one of the AddExpected* methods before use, * or use one of the alternate constructors instead. */ public CommonMockSingleRowResultSet(){ super(); } /** * Constructor to create a single row ResultSet * that can retrieve passed values by index. */ public CommonMockSingleRowResultSet(Object[] values) { addExpectedIndexedValues(values); } /** * Constructor to create a single row ResultSet * that can retrieve passed values by name. */ public CommonMockSingleRowResultSet(String[] names, Object[] values) { addExpectedNamedValues(names, values); } /** * Constructor to create a single row ResultSet * from a Map. */ public CommonMockSingleRowResultSet(Map map) { addExpectedNamedValues(map); } // --------------------------------------------------------------- implemented /** * Return true if this is the first time next is called. */ public boolean next() throws SQLException { myNextCalls.inc(); myNextCallCount++; return myNextCallCount == 1; } /** * Return 1 if next has been called exactly once. */ public int getRow() throws SQLException { return myNextCallCount; } /** * Return value set for given index by an addExpected* method. * Called by superclass to cast values to appropriate type. */ public Object getObject(int columnIndex) throws SQLException { return myRow.get(columnIndex); } /** * Return value set for given name by an addExpectedNamedValue * method. * Called by superclass to cast values to appropriate type. */ public Object getObject(String columnName) throws SQLException { return myRow.get(columnName); } } // end CommonMockSingleRowResultSet mockobjects-0.09/src/jdk/common/com/mockobjects/sql/CommonMockStatement.java0000755000175000017500000001127207651477216030723 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import com.mockobjects.ExpectationCounter; import com.mockobjects.MockObject; import com.mockobjects.ReturnObjectBag; import java.sql.*; /** * @version $Revision: 1.4 $ */ abstract class CommonMockStatement extends MockObject implements Statement { protected final ExpectationCounter myCloseCalls = new ExpectationCounter("CommonMockStatement.closeCalls"); private final ReturnObjectBag executeQueryResults = new ReturnObjectBag("executeQuery"); private final ReturnObjectBag executeUpdateResults = new ReturnObjectBag("executeUpdate"); private final ReturnObjectBag executeResults = new ReturnObjectBag("execute"); private int myUpdateCount = 0; private SQLException myExecuteException = null; private Connection myConnection = null; public void addExpectedExecuteQuery(String queryString, ResultSet resultSet) { executeQueryResults.putObjectToReturn(queryString, resultSet); } public void addExpectedExecuteUpdate(String queryString, int updateCount) { executeUpdateResults.putObjectToReturn(queryString, updateCount); } public void addExpectedExecute(String queryString, boolean success) { executeResults.putObjectToReturn(queryString, success); } public void setExpectedCloseCalls(int callCount) { myCloseCalls.setExpected(callCount); } public void setupConnection(Connection conn) { myConnection = conn; } public void setupThrowExceptionOnExecute(SQLException exception) { myExecuteException = exception; } public void setupUpdateCount(int updateCount) { myUpdateCount = updateCount; } protected void innerExecute() throws SQLException { if (null != myExecuteException) { throw myExecuteException; } } public void close() throws SQLException { myCloseCalls.inc(); } public boolean execute(String sql) throws SQLException { innerExecute(); return executeResults.getNextReturnBoolean(sql); } public ResultSet executeQuery(String sql) throws SQLException { innerExecute(); return (ResultSet) executeQueryResults.getNextReturnObject(sql); } public int executeUpdate(String sql) throws SQLException { innerExecute(); return executeUpdateResults.getNextReturnInt(sql); } public int getMaxFieldSize() throws SQLException { notImplemented(); return 0; } public void setMaxFieldSize(int max) throws SQLException { notImplemented(); } public int getMaxRows() throws SQLException { notImplemented(); return 0; } public void setMaxRows(int max) throws SQLException { notImplemented(); } public void setEscapeProcessing(boolean enable) throws SQLException { notImplemented(); } public int getQueryTimeout() throws SQLException { notImplemented(); return 0; } public void setQueryTimeout(int seconds) throws SQLException { notImplemented(); } public void cancel() throws SQLException { notImplemented(); } public SQLWarning getWarnings() throws SQLException { notImplemented(); return null; } public void clearWarnings() throws SQLException { notImplemented(); } public void setCursorName(String name) throws SQLException { notImplemented(); } public ResultSet getResultSet() throws SQLException { notImplemented(); return null; } public int getUpdateCount() throws SQLException { return myUpdateCount; } public boolean getMoreResults() throws SQLException { notImplemented(); return false; } public void setFetchDirection(int direction) throws SQLException { notImplemented(); } public int getFetchDirection() throws SQLException { notImplemented(); return 0; } public void setFetchSize(int rows) throws SQLException { notImplemented(); } public int getFetchSize() throws SQLException { notImplemented(); return 0; } public int getResultSetConcurrency() throws SQLException { notImplemented(); return 0; } public int getResultSetType() throws SQLException { notImplemented(); return 0; } public void addBatch(String sql) throws SQLException { notImplemented(); } public void clearBatch() throws SQLException { notImplemented(); } public int[] executeBatch() throws SQLException { notImplemented(); return null; } public Connection getConnection() throws SQLException { return myConnection; } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/ExpectationSqlRow.java0000755000175000017500000000341007456044747030424 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.SQLException; import java.util.Map; import java.util.Iterator; import com.mockobjects.*; import com.mockobjects.util.*; public class ExpectationSqlRow implements Verifiable { private ExpectationMap values; public ExpectationSqlRow(String name) { super(); values = new ExpectationMap(name); values.setExpectNothing(); } public ExpectationSqlRow(String name, Object[] indexedValues) { this(name); addExpectedIndexedValues(indexedValues); } public ExpectationSqlRow(String name, String[] columnNames, Object[] values) { this(name); addExpectedNamedValues(columnNames, values); } public void addExpectedIndexedValues(Object[] indexedValues) { for (int i = 0; i < indexedValues.length; ++i) { values.addExpected(new Integer(i + 1), indexedValues[i]); } } public void addExpectedNamedValues(Map map) { Iterator columnNames = map.keySet().iterator(); while (columnNames.hasNext()) { Object key = columnNames.next(); values.addExpected(key, map.get(key)); } } public void addExpectedNamedValues(String[] columnNames, Object[] someValues) { for (int i = 0; i < someValues.length; ++i) { values.addExpected(columnNames[i], someValues[i]); } } public Object get(int oneBasedIndex) throws SQLException { return get(new Integer(oneBasedIndex)); } public Object get(Object key) throws SQLException { Object result = values.get(key); if (result instanceof SQLException) { throw (SQLException)result; } return result; } public void verify() { values.verify(); } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/MockArray.java0000644000175000017500000000272707463502611026653 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import com.mockobjects.MockObject; import java.sql.*; import java.util.*; /** * MockArray.java * * @author ggalli@e-tree.com * @version $Revision: 1.1 $ */ public class MockArray extends MockObject implements Array{ private String myBaseTypeName; private Object myArray; public void setupBaseTypeName(String aBaseTypName){ myBaseTypeName = aBaseTypName; } public String getBaseTypeName(){ return myBaseTypeName; } public int getBaseType(){ notImplemented(); return 0; } public Object getArray(long l, int n) throws SQLException{ notImplemented(); return null; } public Object getArray(Map map)throws SQLException{ notImplemented(); return null; } public Object getArray(long l, int n, Map map) throws SQLException{ notImplemented(); return null; } public void setupArray(Object anArray){ myArray = anArray; } public Object getArray() throws SQLException{ return myArray; } public ResultSet getResultSet() throws SQLException{ notImplemented(); return null; } public ResultSet getResultSet(long l, int n ) throws SQLException{ notImplemented(); return null; } public ResultSet getResultSet(Map map) throws SQLException{ notImplemented(); return null; } public ResultSet getResultSet(long l, int n ,Map map) throws SQLException{ notImplemented(); return null; } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/MockDatabaseMetaData.java0000755000175000017500000005102307512355426030703 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import com.mockobjects.MockObject; public class MockDatabaseMetaData extends MockObject implements DatabaseMetaData { private String myDriverName; public void setupDriverName(String driverName) { myDriverName = driverName; } public boolean supportsANSI92FullSQL() throws SQLException { notImplemented(); return false; } public boolean supportsANSI92EntryLevelSQL() throws SQLException { notImplemented(); return false; } public boolean supportsStatementPooling() throws SQLException { notImplemented(); return false; } public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { notImplemented(); return false; } public boolean supportsSubqueriesInComparisons() throws SQLException { notImplemented(); return false; } public boolean supportsMultipleOpenResults() throws SQLException { notImplemented(); return false; } public ResultSet getProcedures(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public String getSystemFunctions() throws SQLException { notImplemented(); return null; } public boolean supportsUnionAll() throws SQLException { notImplemented(); return false; } public int getDatabaseMinorVersion() throws SQLException { notImplemented(); return 0; } public boolean supportsResultSetConcurrency(int a0, int a1) throws SQLException { notImplemented(); return false; } public ResultSet getCatalogs() throws SQLException { notImplemented(); return null; } public boolean usesLocalFilePerTable() throws SQLException { notImplemented(); return false; } public boolean supportsResultSetHoldability(int a0) throws SQLException { notImplemented(); return false; } public ResultSet getIndexInfo(String a0, String a1, String a2, boolean a3, boolean a4) throws SQLException { notImplemented(); return null; } public boolean supportsExpressionsInOrderBy() throws SQLException { notImplemented(); return false; } public String getDatabaseProductName() throws SQLException { notImplemented(); return null; } public boolean supportsIntegrityEnhancementFacility() throws SQLException { notImplemented(); return false; } public int getMaxBinaryLiteralLength() throws SQLException { notImplemented(); return 0; } public boolean supportsLimitedOuterJoins() throws SQLException { notImplemented(); return false; } public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { notImplemented(); return false; } public boolean supportsMultipleResultSets() throws SQLException { notImplemented(); return false; } public boolean supportsFullOuterJoins() throws SQLException { notImplemented(); return false; } public boolean ownDeletesAreVisible(int a0) throws SQLException { notImplemented(); return false; } public ResultSet getPrimaryKeys(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public int getMaxColumnsInIndex() throws SQLException { notImplemented(); return 0; } public ResultSet getExportedKeys(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public boolean locatorsUpdateCopy() throws SQLException { notImplemented(); return false; } public ResultSet getTables(String a0, String a1, String a2, String[] a3) throws SQLException { notImplemented(); return null; } public int getMaxColumnsInTable() throws SQLException { notImplemented(); return 0; } public String getDriverVersion() throws SQLException { notImplemented(); return null; } public boolean supportsBatchUpdates() throws SQLException { notImplemented(); return false; } public int getMaxTablesInSelect() throws SQLException { notImplemented(); return 0; } public Connection getConnection() throws SQLException { notImplemented(); return null; } public boolean supportsNonNullableColumns() throws SQLException { notImplemented(); return false; } public int getMaxColumnsInOrderBy() throws SQLException { notImplemented(); return 0; } public boolean supportsOrderByUnrelated() throws SQLException { notImplemented(); return false; } public boolean supportsCatalogsInIndexDefinitions() throws SQLException { notImplemented(); return false; } public int getJDBCMajorVersion() throws SQLException { notImplemented(); return 0; } public String getExtraNameCharacters() throws SQLException { notImplemented(); return null; } public boolean nullsAreSortedLow() throws SQLException { notImplemented(); return false; } public ResultSet getAttributes(String a0, String a1, String a2, String a3) throws SQLException { notImplemented(); return null; } public boolean updatesAreDetected(int a0) throws SQLException { notImplemented(); return false; } public boolean supportsDataManipulationTransactionsOnly() throws SQLException { notImplemented(); return false; } public int getMaxConnections() throws SQLException { notImplemented(); return 0; } public boolean supportsOpenCursorsAcrossCommit() throws SQLException { notImplemented(); return false; } public ResultSet getUDTs(String a0, String a1, String a2, int[] a3) throws SQLException { notImplemented(); return null; } public ResultSet getTableTypes() throws SQLException { notImplemented(); return null; } public int getResultSetHoldability() throws SQLException { notImplemented(); return 0; } public boolean insertsAreDetected(int a0) throws SQLException { notImplemented(); return false; } public ResultSet getSchemas() throws SQLException { notImplemented(); return null; } public int getMaxCatalogNameLength() throws SQLException { notImplemented(); return 0; } public int getDefaultTransactionIsolation() throws SQLException { notImplemented(); return 0; } public String getURL() throws SQLException { notImplemented(); return null; } public boolean usesLocalFiles() throws SQLException { notImplemented(); return false; } public boolean supportsExtendedSQLGrammar() throws SQLException { notImplemented(); return false; } public boolean supportsSchemasInProcedureCalls() throws SQLException { notImplemented(); return false; } public ResultSet getSuperTypes(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public int getMaxStatements() throws SQLException { notImplemented(); return 0; } public int getMaxCharLiteralLength() throws SQLException { notImplemented(); return 0; } public boolean supportsTransactionIsolationLevel(int a0) throws SQLException { notImplemented(); return false; } public boolean supportsTableCorrelationNames() throws SQLException { notImplemented(); return false; } public String getSearchStringEscape() throws SQLException { notImplemented(); return null; } public boolean deletesAreDetected(int a0) throws SQLException { notImplemented(); return false; } public boolean supportsColumnAliasing() throws SQLException { notImplemented(); return false; } public boolean isReadOnly() throws SQLException { notImplemented(); return false; } public boolean supportsLikeEscapeClause() throws SQLException { notImplemented(); return false; } public boolean storesLowerCaseIdentifiers() throws SQLException { notImplemented(); return false; } public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { notImplemented(); return false; } public boolean supportsMultipleTransactions() throws SQLException { notImplemented(); return false; } public String getProcedureTerm() throws SQLException { notImplemented(); return null; } public int getMaxStatementLength() throws SQLException { notImplemented(); return 0; } public boolean nullPlusNonNullIsNull() throws SQLException { notImplemented(); return false; } public boolean supportsGroupByBeyondSelect() throws SQLException { notImplemented(); return false; } public int getDriverMajorVersion() { notImplemented(); return 0; } public boolean supportsCoreSQLGrammar() throws SQLException { notImplemented(); return false; } public boolean supportsPositionedUpdate() throws SQLException { notImplemented(); return false; } public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { notImplemented(); return false; } public boolean supportsGetGeneratedKeys() throws SQLException { notImplemented(); return false; } public ResultSet getImportedKeys(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public String getIdentifierQuoteString() throws SQLException { notImplemented(); return null; } public ResultSet getSuperTables(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public boolean nullsAreSortedHigh() throws SQLException { notImplemented(); return false; } public String getNumericFunctions() throws SQLException { notImplemented(); return null; } public boolean supportsSchemasInIndexDefinitions() throws SQLException { notImplemented(); return false; } public boolean supportsGroupByUnrelated() throws SQLException { notImplemented(); return false; } public ResultSet getTypeInfo() throws SQLException { notImplemented(); return null; } public boolean supportsTransactions() throws SQLException { notImplemented(); return false; } public boolean supportsPositionedDelete() throws SQLException { notImplemented(); return false; } public int getMaxProcedureNameLength() throws SQLException { notImplemented(); return 0; } public boolean supportsOuterJoins() throws SQLException { notImplemented(); return false; } public boolean supportsOpenCursorsAcrossRollback() throws SQLException { notImplemented(); return false; } public boolean storesMixedCaseIdentifiers() throws SQLException { notImplemented(); return false; } public int getDatabaseMajorVersion() throws SQLException { notImplemented(); return 0; } public int getMaxColumnsInSelect() throws SQLException { notImplemented(); return 0; } public boolean dataDefinitionIgnoredInTransactions() throws SQLException { notImplemented(); return false; } public String getCatalogTerm() throws SQLException { notImplemented(); return null; } public int getMaxRowSize() throws SQLException { notImplemented(); return 0; } public String getUserName() throws SQLException { notImplemented(); return null; } public boolean allProceduresAreCallable() throws SQLException { notImplemented(); return false; } public boolean nullsAreSortedAtStart() throws SQLException { notImplemented(); return false; } public boolean storesUpperCaseIdentifiers() throws SQLException { notImplemented(); return false; } public boolean supportsCatalogsInDataManipulation() throws SQLException { notImplemented(); return false; } public ResultSet getBestRowIdentifier(String a0, String a1, String a2, int a3, boolean a4) throws SQLException { notImplemented(); return null; } public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { notImplemented(); return false; } public boolean nullsAreSortedAtEnd() throws SQLException { notImplemented(); return false; } public String getSQLKeywords() throws SQLException { notImplemented(); return null; } public ResultSet getCrossReference(String a0, String a1, String a2, String a3, String a4, String a5) throws SQLException { notImplemented(); return null; } public boolean isCatalogAtStart() throws SQLException { notImplemented(); return false; } public boolean supportsNamedParameters() throws SQLException { notImplemented(); return false; } public boolean supportsSubqueriesInIns() throws SQLException { notImplemented(); return false; } public ResultSet getVersionColumns(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public boolean othersInsertsAreVisible(int a0) throws SQLException { notImplemented(); return false; } public boolean supportsANSI92IntermediateSQL() throws SQLException { notImplemented(); return false; } public boolean supportsCatalogsInTableDefinitions() throws SQLException { notImplemented(); return false; } public int getJDBCMinorVersion() throws SQLException { notImplemented(); return 0; } public String getStringFunctions() throws SQLException { notImplemented(); return null; } public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { notImplemented(); return false; } public ResultSet getColumnPrivileges(String a0, String a1, String a2, String a3) throws SQLException { notImplemented(); return null; } public boolean dataDefinitionCausesTransactionCommit() throws SQLException { notImplemented(); return false; } public boolean supportsSubqueriesInExists() throws SQLException { notImplemented(); return false; } public int getMaxUserNameLength() throws SQLException { notImplemented(); return 0; } public int getMaxIndexLength() throws SQLException { notImplemented(); return 0; } public String getDriverName() throws SQLException { return myDriverName; } public boolean othersUpdatesAreVisible(int a0) throws SQLException { notImplemented(); return false; } public boolean supportsSavepoints() throws SQLException { notImplemented(); return false; } public boolean supportsMixedCaseIdentifiers() throws SQLException { notImplemented(); return false; } public String getCatalogSeparator() throws SQLException { notImplemented(); return null; } public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { notImplemented(); return false; } public int getMaxColumnsInGroupBy() throws SQLException { notImplemented(); return 0; } public boolean supportsDifferentTableCorrelationNames() throws SQLException { notImplemented(); return false; } public boolean supportsSubqueriesInQuantifieds() throws SQLException { notImplemented(); return false; } public boolean supportsResultSetType(int a0) throws SQLException { notImplemented(); return false; } public String getDatabaseProductVersion() throws SQLException { notImplemented(); return null; } public int getSQLStateType() throws SQLException { notImplemented(); return 0; } public boolean supportsSelectForUpdate() throws SQLException { notImplemented(); return false; } public int getMaxTableNameLength() throws SQLException { notImplemented(); return 0; } public boolean supportsUnion() throws SQLException { notImplemented(); return false; } public boolean supportsOpenStatementsAcrossCommit() throws SQLException { notImplemented(); return false; } public ResultSet getColumns(String a0, String a1, String a2, String a3) throws SQLException { notImplemented(); return null; } public boolean supportsAlterTableWithDropColumn() throws SQLException { notImplemented(); return false; } public boolean supportsStoredProcedures() throws SQLException { notImplemented(); return false; } public boolean othersDeletesAreVisible(int a0) throws SQLException { notImplemented(); return false; } public String getSchemaTerm() throws SQLException { notImplemented(); return null; } public int getDriverMinorVersion() { notImplemented(); return 0; } public int getMaxSchemaNameLength() throws SQLException { notImplemented(); return 0; } public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { notImplemented(); return false; } public ResultSet getTablePrivileges(String a0, String a1, String a2) throws SQLException { notImplemented(); return null; } public boolean supportsSchemasInDataManipulation() throws SQLException { notImplemented(); return false; } public int getMaxCursorNameLength() throws SQLException { notImplemented(); return 0; } public boolean supportsAlterTableWithAddColumn() throws SQLException { notImplemented(); return false; } public boolean supportsOpenStatementsAcrossRollback() throws SQLException { notImplemented(); return false; } public int getMaxColumnNameLength() throws SQLException { notImplemented(); return 0; } public boolean ownInsertsAreVisible(int a0) throws SQLException { notImplemented(); return false; } public boolean supportsGroupBy() throws SQLException { notImplemented(); return false; } public boolean supportsConvert(int a0, int a1) throws SQLException { notImplemented(); return false; } public boolean supportsConvert() throws SQLException { notImplemented(); return false; } public boolean supportsCorrelatedSubqueries() throws SQLException { notImplemented(); return false; } public String getTimeDateFunctions() throws SQLException { notImplemented(); return null; } public boolean supportsSchemasInTableDefinitions() throws SQLException { notImplemented(); return false; } public boolean supportsCatalogsInProcedureCalls() throws SQLException { notImplemented(); return false; } public boolean allTablesAreSelectable() throws SQLException { notImplemented(); return false; } public boolean supportsMinimumSQLGrammar() throws SQLException { notImplemented(); return false; } public boolean ownUpdatesAreVisible(int a0) throws SQLException { notImplemented(); return false; } public ResultSet getProcedureColumns(String a0, String a1, String a2, String a3) throws SQLException { notImplemented(); return null; } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/MockDriver.java0000755000175000017500000000165007604317144027027 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import java.sql.*; import java.util.Properties; public class MockDriver implements Driver{ public static MockDriver myDriver = new MockDriver(); private Connection myConnection; static{ try{ DriverManager.registerDriver(myDriver); }catch(SQLException e){ e.printStackTrace(); } } public void setupConnect(Connection aConnection){ this.myConnection = aConnection; } public boolean acceptsURL(String url){ return true; } public Connection connect(String url, Properties info){ return myConnection; } public int getMajorVersion(){ return 0; } public int getMinorVersion(){ return 0; } public DriverPropertyInfo[] getPropertyInfo(String url, Properties info){ return null; } public boolean jdbcCompliant(){ return false; } } mockobjects-0.09/src/jdk/common/com/mockobjects/sql/MockResultSet.java0000755000175000017500000005143207651477216027542 0ustar craftermcrafterm00000000000000package com.mockobjects.sql; import com.mockobjects.ExpectationCounter; import com.mockobjects.MockObject; import com.mockobjects.ReturnValue; import com.mockobjects.util.AssertMo; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.*; import java.util.Calendar; import java.util.Map; /** * This is the base implementation of a mock result set. * It manages converting objects from the current row into a other types. * Entries can be found by either column index or column name. * For basic java types (e.g. int, boolean), insert an instance of * the appropriate object (e.g. Integer, Boolean) * It also counts close() and next() calls * To force throwing a SQLException on a getter, * set the corresponding value to be of type SQLException. */ abstract class MockResultSet extends MockObject implements ResultSet { private final ExpectationCounter myCloseCalls; protected final ExpectationCounter myNextCalls; protected final String name; private final ReturnValue myMetaData = new ReturnValue("meta data"); private final ReturnValue myStatement = new ReturnValue("statement"); public MockResultSet() { this(MockResultSet.class.getName()); } /** * @param name Label used to identify mock when it errors */ public MockResultSet(String name) { this.name = name; myCloseCalls = new ExpectationCounter(name + ".close"); myNextCalls = new ExpectationCounter(name + ".next"); } public void setExpectedCloseCalls(int calls) { myCloseCalls.setExpected(calls); } public void setExpectedNextCalls(int calls) { myNextCalls.setExpected(calls); } // --------------------------------------------------------------------- setup public void setupMetaData(ResultSetMetaData metaData) { myMetaData.setValue(metaData); } public void setupStatement(Statement statement) { myStatement.setValue(statement); } // ------------------------------------------------------------------ abstract /** * Used as the base implementation for getting all types of object, * based on 1-based column index * @see java.sql.ResultSet#getObject(int) */ abstract public Object getObject(int columnIndex) throws SQLException; /** * Used as the base implementation for getting all types of object, * based on columnName * @see java.sql.ResultSet#getObject(int) */ abstract public Object getObject(String columnName) throws SQLException; abstract public boolean next() throws SQLException; abstract public int getRow() throws SQLException; // --------------------------------------------------------------- implemented public void close() throws SQLException { myCloseCalls.inc(); } public Array getArray(int i) throws SQLException { return (Array) getObject(i); } public Array getArray(String colName) throws SQLException { return (Array) getObject(colName); } public InputStream getAsciiStream(int columnIndex) throws SQLException { return (InputStream) getObject(columnIndex); } public InputStream getAsciiStream(String columnName) throws SQLException { return (InputStream) getObject(columnName); } public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { return getBigDecimal(columnName); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return (BigDecimal) getObject(columnIndex); } public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return (BigDecimal) getObject(columnIndex); } public BigDecimal getBigDecimal(String columnName) throws SQLException { return (BigDecimal) getObject(columnName); } public InputStream getBinaryStream(int columnIndex) throws SQLException { return (InputStream) getObject(columnIndex); } public InputStream getBinaryStream(String columnName) throws SQLException { return (InputStream) getObject(columnName); } public Blob getBlob(int i) throws SQLException { return (Blob) getObject(i); } public Blob getBlob(String colName) throws SQLException { return (Blob) getObject(colName); } public boolean getBoolean(int columnIndex) throws SQLException { return ((Boolean) getObject(columnIndex)).booleanValue(); } public boolean getBoolean(String columnName) throws SQLException { return ((Boolean) getObject(columnName)).booleanValue(); } public byte getByte(int columnIndex) throws SQLException { return ((Byte) getObject(columnIndex)).byteValue(); } public byte getByte(String columnName) throws SQLException { return ((Byte) getObject(columnName)).byteValue(); } public byte[] getBytes(int columnIndex) throws SQLException { return (byte[]) getObject(columnIndex); } public byte[] getBytes(String columnName) throws SQLException { return (byte[]) getObject(columnName); } public Reader getCharacterStream(int columnIndex) throws SQLException { return (Reader) getObject(columnIndex); } public Reader getCharacterStream(String columnName) throws SQLException { return (Reader) getObject(columnName); } public Clob getClob(int i) throws SQLException { return (Clob) getObject(i); } public Clob getClob(String colName) throws SQLException { return (Clob) getObject(colName); } public Date getDate(int columnIndex) throws SQLException { return (Date) getObject(columnIndex); } public Date getDate(String columnName) throws SQLException { return (Date) getObject(columnName); } public Date getDate(int columnIndex, Calendar cal) throws SQLException { return getDate(columnIndex); } public Date getDate(String columnName, Calendar cal) throws SQLException { return getDate(columnName); } public double getDouble(int columnIndex) throws SQLException { return ((Double) getObject(columnIndex)).doubleValue(); } public double getDouble(String columnName) throws SQLException { return ((Double) getObject(columnName)).doubleValue(); } public float getFloat(int columnIndex) throws SQLException { return ((Float) getObject(columnIndex)).floatValue(); } public float getFloat(String columnName) throws SQLException { return ((Float) getObject(columnName)).floatValue(); } public int getInt(int columnIndex) throws SQLException { return ((Integer) getObject(columnIndex)).intValue(); } public int getInt(String columnName) throws SQLException { return ((Integer) getObject(columnName)).intValue(); } public long getLong(int columnIndex) throws SQLException { return ((Long) getObject(columnIndex)).longValue(); } public long getLong(String columnName) throws SQLException { return ((Long) getObject(columnName)).longValue(); } public ResultSetMetaData getMetaData() throws SQLException { return (ResultSetMetaData) myMetaData.getValue(); } public Ref getRef(int i) throws SQLException { return (Ref) getObject(i); } public Ref getRef(String colName) throws SQLException { return (Ref) getObject(colName); } public short getShort(String columnName) throws SQLException { return ((Short) getObject(columnName)).shortValue(); } public short getShort(int columnIndex) throws SQLException { return ((Short) getObject(columnIndex)).shortValue(); } public Statement getStatement() throws SQLException { return (Statement) myStatement.getValue(); } public String getString(int columnIndex) throws SQLException { final Object object = getObject(columnIndex); if (object != null) { AssertMo.assertTrue("Column " + columnIndex + " in " + name + " is a " + object.getClass().getName() + " not a String", object instanceof String); return (String) object; } else { return null; } } public String getString(String columnName) throws SQLException { return (String) getObject(columnName); } public Time getTime(int columnIndex) throws SQLException { return (Time) getObject(columnIndex); } public Time getTime(String columnName) throws SQLException { return (Time) getObject(columnName); } public Time getTime(int columnIndex, Calendar cal) throws SQLException { return getTime(columnIndex); } public Time getTime(String columnName, Calendar cal) throws SQLException { return getTime(columnName); } public Timestamp getTimestamp(int columnIndex) throws SQLException { return (Timestamp) getObject(columnIndex); } public Timestamp getTimestamp(String columnName) throws SQLException { return (Timestamp) getObject(columnName); } public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { return getTimestamp(columnIndex); } public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { return getTimestamp(columnName); } public InputStream getUnicodeStream(int columnIndex) throws SQLException { return (InputStream) getObject(columnIndex); } public InputStream getUnicodeStream(String columnName) throws SQLException { return (InputStream) getObject(columnName); } // ------------------------------------------------------------ notImplemented public String getCursorName() throws SQLException { notImplemented(); return null; } public int getConcurrency() throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns 0. */ public int getFetchDirection() throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns 0. */ public int getFetchSize() throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns null. */ public Object getObject(int i, Map map) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns null. */ public Object getObject(String colName, Map map) throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. Returns 0. */ public int getType() throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns null. */ public SQLWarning getWarnings() throws SQLException { notImplemented(); return null; } /** * Calls notImplemented. */ public void clearWarnings() throws SQLException { notImplemented(); } /** * Calls notImplemented. Returns 0. */ public int findColumn(String columnName) throws SQLException { notImplemented(); return 0; } /** * Calls notImplemented. Returns false. */ public boolean isBeforeFirst() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean isAfterLast() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean isFirst() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean isLast() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. */ public void beforeFirst() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void afterLast() throws SQLException { notImplemented(); } /** * Calls notImplemented. Returns false. */ public boolean first() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean last() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean absolute(int row) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean relative(int rows) throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean previous() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. */ public void setFetchDirection(int direction) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void setFetchSize(int rows) throws SQLException { notImplemented(); } /** * Calls notImplemented. Returns false. */ public boolean rowUpdated() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean rowInserted() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. Returns false. */ public boolean rowDeleted() throws SQLException { notImplemented(); return false; } /** * Calls notImplemented. */ public void updateNull(int columnIndex) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBoolean(int columnIndex, boolean x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateByte(int columnIndex, byte x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateShort(int columnIndex, short x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateInt(int columnIndex, int x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateLong(int columnIndex, long x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateFloat(int columnIndex, float x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateDouble(int columnIndex, double x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateString(int columnIndex, String x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBytes(int columnIndex, byte x[]) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateDate(int columnIndex, Date x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateTime(int columnIndex, Time x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateObject(int columnIndex, Object x, int scale) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateObject(int columnIndex, Object x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateNull(String columnName) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBoolean(String columnName, boolean x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateByte(String columnName, byte x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateShort(String columnName, short x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateInt(String columnName, int x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateLong(String columnName, long x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateFloat(String columnName, float x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateDouble(String columnName, double x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateString(String columnName, String x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBytes(String columnName, byte x[]) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateDate(String columnName, Date x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateTime(String columnName, Time x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateTimestamp(String columnName, Timestamp x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateAsciiStream(String columnName, InputStream x, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateCharacterStream(String columnName, Reader reader, int length) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateObject(String columnName, Object x, int scale) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateObject(String columnName, Object x) throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void insertRow() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void updateRow() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void deleteRow() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void refreshRow() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void cancelRowUpdates() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void moveToInsertRow() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public void moveToCurrentRow() throws SQLException { notImplemented(); } /** * Calls notImplemented. */ public boolean wasNull() throws SQLException { notImplemented(); return false; } } // end MockResultSet mockobjects-0.09/src/jdk/common/test/0000755000175000017500000000000010117310266021200 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/test/mockobjects/0000755000175000017500000000000010117310266023503 5ustar craftermcrafterm00000000000000mockobjects-0.09/src/jdk/common/test/mockobjects/TestExpectationSqlRow.java0000644000175000017500000000762607555102747030673 0ustar craftermcrafterm00000000000000package test.mockobjects; import com.mockobjects.sql.ExpectationSqlRow; import com.mockobjects.util.TestCaseMo; import junit.framework.AssertionFailedError; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; public class TestExpectationSqlRow extends TestCaseMo { private static final Class THIS = TestExpectationSqlRow.class; private ExpectationSqlRow row = new ExpectationSqlRow("sql row"); public TestExpectationSqlRow(String name) { super(name); } public void testIndexedValues() throws SQLException { row.addExpectedIndexedValues(new Object[] { "one", "two" }); assertEquals("should have value", "one", row.get(1)); assertEquals("should have value", "two", row.get(2)); row.verify(); } public void testConstructorIndexedValues() throws SQLException { ExpectationSqlRow aRow = new ExpectationSqlRow("row1", new Object[] { "one", "two" }); assertEquals("should have value", "one", aRow.get(1)); assertEquals("should have value", "two", aRow.get(2)); aRow.verify(); } public void testNamedValues() throws SQLException { row.addExpectedNamedValues( new String[] {"col1", "col2" }, new Object[] {"one", "two" }); assertEquals("should have value", "two", row.get("col2")); assertEquals("should have value", "one", row.get("col1")); row.verify(); } public void testConstructorNamedValues() throws SQLException { ExpectationSqlRow aRow = new ExpectationSqlRow("row1", new String[] {"col1", "col2" }, new Object[] { "one", "two" }); assertEquals("should have value", "two", aRow.get("col2")); assertEquals("should have value", "one", aRow.get("col1")); aRow.verify(); } public void testNamedValuesFromMap() throws SQLException { Map values = new HashMap(); values.put("col1", "one"); values.put("col2", "two"); row.addExpectedNamedValues(values); assertEquals("should have value", "two", row.get("col2")); assertEquals("should have value", "one", row.get("col1")); row.verify(); } public void testNoValues() { row.verify(); } public void testFailInvalidIndex() throws SQLException { row.addExpectedIndexedValues(new Object[] { "one" }); boolean assertionFailed = false; try { row.get(3); } catch (AssertionFailedError ex) { assertionFailed = true; } assertTrue("Should have failed", assertionFailed); } public void testFailInvalidKey() throws SQLException { row.addExpectedNamedValues(new String[] {"col1" }, new Object[] {"one" }); boolean assertionFailed = false; try { row.get("col2"); } catch (AssertionFailedError ex) { assertionFailed = true; } assertTrue("Should have failed", assertionFailed); } public void testFailEmptyRow() throws SQLException { boolean assertionFailed = false; try { row.get(1); } catch (AssertionFailedError ex) { assertionFailed = true; } assertTrue("Should have failed", assertionFailed); } public void testIndexNotGot() throws SQLException { row.addExpectedIndexedValues(new Object[] { "one" }); boolean assertionFailed = false; try { row.verify(); } catch (AssertionFailedError ex) { assertionFailed = true; } assertTrue("Should have failed", assertionFailed); } public void testThrowExceptionOnGet() { row.addExpectedIndexedValues(new Object[] {new SQLException("Mock SQL Excpeption")}); try { row.get(1); fail("Should have thrown exception"); } catch (SQLException expected) { } } }