pax_global_header00006660000000000000000000000064134700253460014516gustar00rootroot0000000000000052 comment=488bfea2315261d208fd1d3bbc0115386d9003c2 jmock-library-2.12.0/000077500000000000000000000000001347002534600143455ustar00rootroot00000000000000jmock-library-2.12.0/.gitignore000066400000000000000000000003001347002534600163260ustar00rootroot00000000000000build/ out/ bin/ workspace.xml .DS_Store .idea target/ hamcrest-test-src .settings .project .classpath .gradle .factorypath gradle *.iml *.ipr *.iws gradlew gradlew.bat pom.xml.versionsBackup jmock-library-2.12.0/.travis.yml000066400000000000000000000012241347002534600164550ustar00rootroot00000000000000language: java jdk: - openjdk-ea - openjdk11 - oraclejdk11 - openjdk10 # - oraclejdk10 - openjdk9 - oraclejdk8 #not supported matrix: allow_failures: - jdk: openjdk-ea env: # Travis has slow VMs? global: - blitzerThreads=1 blitzerActions=1 blitzerTimeout=1000 - secure: "XBIyEF5RxH/zKjh0gle5ce/FRe9pP5b46LXKNOfwlau5QYvn8WXC41Sb6yYC8VW3vI9S930BnVGZONiDXsSWuylLezdu2g88nwJ2CsTxHU0Yg2GAzKwaorBQqyK/6w2foRRXtz69NJccfdIdPuDZSEhJtTKWSmMMQ7U65KH+zzQ=" - secure: "SSlAKOg8QLEAkZX1ehy9c6FR5R6gMzLhc6u2Smq9tm8JsWVz4EtS6NnTQaosthrNEfLJwVVCfmOh2dzvYZfhtbKAUMdkox45tem4+LZfgkSaQAGjSvsC6geioa4Alo6AKyR8foc5Y7P34f9ujYSZHNyRG9F6E0Qq2zj/hzHhstU=" jmock-library-2.12.0/LICENSE.txt000066400000000000000000000026631347002534600161770ustar00rootroot00000000000000Copyright (c) 2000-2017, jMock.org 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 jMock 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 THE COPYRIGHT OWNER 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. jmock-library-2.12.0/README.DEVELOPMENT000066400000000000000000000034011347002534600170040ustar00rootroot00000000000000Development rules ================= Here are some rules that we follow when developing jMock: * Never check in a class without associated unit tests. * Never check a failing unit test into the repository. * Acceptance tests may fail. A failing acceptance test indicates something that needs to be done: a todo item, feature request or bug report, for example. It's ok to check a failing acceptance test into the repository. * Separate acceptance and unit tests. Make it easy to run only the unit tests so that we can check that they pass before committing, even when acceptance tests are failing. * Resolve and remove all TODO comments before checking in. * Avoid the following words in class names and other identifiers: Helper, Impl (or a derivative), Manager. * And the reverse: don't start interfaces with an I. * Use the TestDox naming conventions for unit tests. Architectural Constraints ========================= * No dependency on any specific test framework. That means, don't use JUnit Assert.assertBlahBlah to check expectations. Throw ExpectationError to report a violated expectation. Throw some kind of RuntimeException to report programming errors in the use of the framework. E.g. trying to set up an expectation to return a result of the wrong type. Release ======= mvn versions:set -DoldVersion=* -DnewVersion=2.10.0 -DgroupId=org.jmock -DgenerateBackupPoms=false eval $(gpg-agent --daemon --no-grab --write-env-file $HOME/.gpg-agent-info) export GPG_AGENT_INFO export GPG_TTY=$(tty) export SONATYPE_USERNAME=UUU export SONATYPE_PASSWORD=PPPP mvn clean deploy -P release --settings settings.xml -Dgpg.keyname=XXXXXXXX mvn versions:set -DoldVersion=* -DnewVersion=2.11.0-SNAPSHOT -DgroupId=org.jmock -DgenerateBackupPoms=false jmock-library-2.12.0/README.md000066400000000000000000000113001347002534600156170ustar00rootroot00000000000000# JMock Library [![Build Status](https://travis-ci.org/jmock-developers/jmock-library.svg?branch=jmock2)](https://travis-ci.org/jmock-developers/jmock-library) [![Maven Central](https://img.shields.io/maven-central/v/org.jmock/jmock.svg?label=Maven%20Central)](https://mvnrepository.com/artifact/org.jmock) # Maven ```xml org.jmock jmock-junit5 2.11.0 test ``` # Gradle ``` testCompile( "junit:junit5:5.3.1", "org.jmock:jmock-junit5:2.11.0" ) ``` # Recent Changes ## 2.10.0 ### JUnit 5 Support * Swap @Rule JUnit4Mockery for @RegisterExtension JMock5Mockery * Assign to a non-private JMock5Mockery or JUnit5 won't use it ```java import org.jmock.Expectations; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class JUnit5TestThatDoesSatisfyExpectations { @RegisterExtension JUnit5Mockery context = new JUnit5Mockery(); private Runnable runnable = context.mock(Runnable.class); @Test public void doesSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); runnable.run(); } } ``` ### JUnit 4 moved to provided scope in org.jmock:jmock * This allows dependents to use other versions of junit or other test frameworks (e.g. junit 5) ### Java7 Support will be dropped next release ## 2.9.0 * Dropped JDK 6 compliance. * Exposed the InvocationDispatcher so that ThreadingPolicies ## Upgrading to 2.8.X Are you seeing NPEs? We have had to make a breaking change to `with()`. Tests using `with(any(matcher))` for method signatures that require native types will throw `NullPointerException`. You should change oneOf(mock).methodWithIntParams(with(any(Integer.class))); to the following oneOf(mock).methodWithIntParams(with.intIs(anything()); This is due to a compiler change in Java 1.7. The 2.6.0 release was compiled with Java 1.6 so it did not suffer this problem. # Advantages of jMock 2 over jMock 1 * Uses real method calls, not strings, so you can refactor more easily and autocomplete in the IDE. * Customisation by delegation, not by inheritance. * Many more plugin-points for customisation. * Independent of any testing framework: compatability with the testing framework is a plugin-point. * Can mock concrete classes *without* calling their constructors (if you really want to). * Uses Hamcrest matchers, so can use a large and ever-growing library of matchers in expectations. * Expectations match in first-in, first-out order, so tests are easier to understand. # Package Structure [jMock]() 2 is organised into published and internal packages. We guarantee backwards compatability of types in published packages within the same major version of jMock. There are no guarantees about backward compatability for types in internal packages. Types defined in published packages may themselves define public methods that accept or return types from internal packages or inherit methods from types in internal packages. Such methods have no compatability guarantees and should not be considered as part of the published interface. ## Published packages ### org.jmock DSL-style API ### org.jmock.api ### org.jmock.lib Convenient classes that implement the APIs in the core, are used by the DSL-style API, and can be used in user-defined APIs ### org.jmock.integration Classes integrating jMock with different testing APIs, such as JUnit 3.x, JUnit 4.x and TestNG. ## Packages of example code ### org.jmock.lib.nonstd Lib classes that rely on clever hacks or otherwise cannot be guaranteed to always work in all JVMs. There are no compatability guarantees with these classes. Use at your own risk. ## Internal packages ### org.jmock.internal Internal implementation details ### org.jmock.test Tests for jMock itself ## Plug-in Points ### Matcher Controls the matching of invocations to expectations ### Action Performs an action in response to an invocation ### Imposteriser Wraps mock objects in an adapter of the correct type ### Expectation Matches an invocation and fakes its behaviour ### ExpectationErrorTranslator Translates expectation errors into error type used by a specific testing framework. ### MockObjectNamingScheme Creates names for mock objects based on the mocked type. # Contributing If you'd like to contribute, then do the following: 1. clone this repository (`git clone …`) 2. install Maven (`brew install mvn` on Mac OS, for example) 3. `$ mvn package` in order to generate a signed JAR. This will run all the tests. (`$ mvn test` appears not to suffice.) jmock-library-2.12.0/jmock-example/000077500000000000000000000000001347002534600171015ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/pom.xml000066400000000000000000000037721347002534600204270ustar00rootroot00000000000000 4.0.0 jmock-example jar jMock Examples org.jmock jmock-parent 2.12.0 ../pom.xml UTF-8 UTF-8 junit junit compile org.jmock jmock ${project.version} compile org.jmock jmock ${project.version} test-jar test org.jmock jmock-junit3 ${project.version} org.jmock jmock-junit4 ${project.version} org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-example/src/000077500000000000000000000000001347002534600176705ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/000077500000000000000000000000001347002534600206145ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/000077500000000000000000000000001347002534600215355ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/000077500000000000000000000000001347002534600223245ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/000077500000000000000000000000001347002534600234275ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/000077500000000000000000000000001347002534600250625ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/announcer/000077500000000000000000000000001347002534600270525ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/announcer/Announcer.java000066400000000000000000000032211347002534600316430ustar00rootroot00000000000000package org.jmock.example.announcer; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.EventListener; import java.util.List; public class Announcer { private final T proxy; private final List listeners = new ArrayList(); public Announcer(Class listenerType) { proxy = listenerType.cast(Proxy.newProxyInstance( listenerType.getClassLoader(), new Class[]{listenerType}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { announce(method, args); return null; } })); } public void addListener(T listener) { listeners.add(listener); } public void removeListener(T listener) { listeners.remove(listener); } public T announce() { return proxy; } private void announce(Method m, Object[] args) { try { for (T listener : listeners) { m.invoke(listener, args); } } catch (IllegalAccessException e) { throw new IllegalArgumentException("could not invoke listener", e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException)cause; } else if (cause instanceof Error) { throw (Error)cause; } else { throw new UnsupportedOperationException("listener threw exception", cause); } } } public static Announcer to(Class listenerType) { return new Announcer(listenerType); } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/announcer/AnnouncerTests.java000066400000000000000000000042521347002534600326730ustar00rootroot00000000000000package org.jmock.example.announcer; import java.util.EventListener; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.integration.junit3.MockObjectTestCase; public class AnnouncerTests extends MockObjectTestCase { public static class CheckedException extends Exception {} public interface Listener extends EventListener { public void eventA(); public void eventB(); public void eventWithArguments(int a, int b); public void badEvent() throws CheckedException; } Announcer announcer = Announcer.to(Listener.class); Listener listener1 = mock(Listener.class, "listener1"); Listener listener2 = mock(Listener.class, "listener2"); @Override public void setUp() { announcer.addListener(listener1); announcer.addListener(listener2); } public void testAnnouncesToRegisteredListenersInOrderOfAddition() { final Sequence eventOrder = sequence("eventOrder"); checking(new Expectations() {{ oneOf (listener1).eventA(); inSequence(eventOrder); oneOf (listener2).eventA(); inSequence(eventOrder); oneOf (listener1).eventB(); inSequence(eventOrder); oneOf (listener2).eventB(); inSequence(eventOrder); }}); announcer.announce().eventA(); announcer.announce().eventB(); } public void testPassesEventArgumentsToListeners() { checking(new Expectations() {{ oneOf (listener1).eventWithArguments(1, 2); oneOf (listener2).eventWithArguments(1, 2); oneOf (listener1).eventWithArguments(3, 4); oneOf (listener2).eventWithArguments(3, 4); }}); announcer.announce().eventWithArguments(1, 2); announcer.announce().eventWithArguments(3, 4); } public void testCanRemoveListeners() { announcer.removeListener(listener1); checking(new Expectations() {{ oneOf (listener2).eventA(); }}); announcer.announce().eventA(); } public void testDoesNotAllowListenersToThrowCheckedExceptions() throws Exception { checking(new Expectations() {{ allowing (listener1).badEvent(); will(throwException(new CheckedException())); }}); try { announcer.announce().badEvent(); fail("should have thrown UnsupportedOperationException"); } catch (UnsupportedOperationException expected) {} } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstarted/000077500000000000000000000000001347002534600301125ustar00rootroot00000000000000GettingStartedJUnit3.java000066400000000000000000000012031347002534600346570ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstartedpackage org.jmock.example.gettingstarted; import org.jmock.Expectations; import org.jmock.integration.junit3.MockObjectTestCase; public class GettingStartedJUnit3 extends MockObjectTestCase { public void testOneSubscriberReceivesAMessage() { // set up final Subscriber subscriber = mock(Subscriber.class); Publisher publisher = new Publisher(); publisher.add(subscriber); final String message = "message"; // expectations checking(new Expectations() {{ oneOf(subscriber).receive(message); }}); // execute publisher.publish(message); } } GettingStartedJUnit3Mockomatic.java000066400000000000000000000012171347002534600366730ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstartedpackage org.jmock.example.gettingstarted; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.jmock.integration.junit3.MockObjectTestCase; public class GettingStartedJUnit3Mockomatic extends MockObjectTestCase { @Mock Subscriber subscriber; public void testOneSubscriberReceivesAMessage() { // set up Publisher publisher = new Publisher(); publisher.add(subscriber); final String message = "message"; // expectations checking(new Expectations() {{ oneOf(subscriber).receive(message); }}); // execute publisher.publish(message); } }GettingStartedJUnit4.java000066400000000000000000000014671347002534600346740ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstartedpackage org.jmock.example.gettingstarted; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class GettingStartedJUnit4 { Mockery context = new JUnit4Mockery(); @Test public void oneSubscriberReceivesAMessage() { // set up final Subscriber subscriber = context.mock(Subscriber.class); Publisher publisher = new Publisher(); publisher.add(subscriber); final String message = "message"; // expectations context.checking(new Expectations() {{ oneOf(subscriber).receive(message); }}); // execute publisher.publish(message); } }GettingStartedJUnit4Mockomatic.java000066400000000000000000000013701347002534600366740ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstartedpackage org.jmock.example.gettingstarted; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.Rule; import org.junit.Test; public class GettingStartedJUnit4Mockomatic { @Rule public JUnitRuleMockery context = new JUnitRuleMockery(); @Mock Subscriber subscriber; @Test public void oneSubscriberReceivesAMessage() { // set up Publisher publisher = new Publisher(); publisher.add(subscriber); final String message = "message"; // expectations context.checking(new Expectations() {{ oneOf(subscriber).receive(message); }}); // execute publisher.publish(message); } }GettingStartedJUnit4Rule.java000066400000000000000000000013661347002534600355220ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstartedpackage org.jmock.example.gettingstarted; import org.jmock.Expectations; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.Rule; import org.junit.Test; public class GettingStartedJUnit4Rule { @Rule public JUnitRuleMockery context = new JUnitRuleMockery(); @Test public void oneSubscriberReceivesAMessage() { // set up final Subscriber subscriber = context.mock(Subscriber.class); Publisher publisher = new Publisher(); publisher.add(subscriber); final String message = "message"; // expectations context.checking(new Expectations() {{ oneOf(subscriber).receive(message); }}); // execute publisher.publish(message); } }GettingStartedJUnit4RuleMockomatic.java000066400000000000000000000014001347002534600375160ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstartedpackage org.jmock.example.gettingstarted; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.Rule; import org.junit.Test; public class GettingStartedJUnit4RuleMockomatic { @Rule public JUnitRuleMockery context = new JUnitRuleMockery(); @Mock Subscriber subscriber; @Test public void oneSubscriberReceivesAMessage() { // set up Publisher publisher = new Publisher(); publisher.add(subscriber); final String message = "message"; // expectations context.checking(new Expectations() {{ oneOf(subscriber).receive(message); }}); // execute publisher.publish(message); } }jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstarted/Publisher.java000066400000000000000000000006631347002534600327170ustar00rootroot00000000000000package org.jmock.example.gettingstarted; import java.util.ArrayList; import java.util.List; public class Publisher { private List subscribers = new ArrayList(); public void add(Subscriber subscriber) { subscribers.add(subscriber); } public void publish(String message) { for (Subscriber subscriber : subscribers) { subscriber.receive(message); } } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/gettingstarted/Subscriber.java000066400000000000000000000001551347002534600330610ustar00rootroot00000000000000package org.jmock.example.gettingstarted; public interface Subscriber { void receive(String message); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/000077500000000000000000000000001347002534600260225ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/DJ.java000066400000000000000000000020641347002534600271640ustar00rootroot00000000000000package org.jmock.example.qcon; public class DJ implements LocationAware, MediaTracker { private final MediaControl mediaControl; private final Playlist playlist; private String currentLocationName = null; private boolean trackFinished = true; private boolean locationChanged = false; public DJ(Playlist playlist, MediaControl mediaControl) { this.playlist = playlist; this.mediaControl = mediaControl; } public void locationChangedTo(String newLocationName) { currentLocationName = newLocationName; if (trackFinished) { startPlaying(); trackFinished = false; } else { locationChanged = true; } } public void mediaFinished() { if (locationChanged) { startPlaying(); locationChanged = false; } else { trackFinished = true; } } private void startPlaying() { mediaControl.play(playlist.trackFor(currentLocationName)); } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/DJTests.java000066400000000000000000000047501347002534600302130ustar00rootroot00000000000000package org.jmock.example.qcon; import org.jmock.Expectations; import org.jmock.integration.junit3.MockObjectTestCase; public class DJTests extends MockObjectTestCase { Playlist playlist = mock(Playlist.class); MediaControl mediaControl = mock(MediaControl.class); DJ dj = new DJ(playlist, mediaControl); private static final String LOCATION_A = "location-a"; private static final String TRACK_A = "track-a"; private static final String LOCATION_B = "location-b"; private static final String TRACK_B = "track-b"; @Override public void setUp() { checking(new Expectations() {{ allowing (playlist).hasTrackFor(LOCATION_A); will(returnValue(true)); allowing (playlist).trackFor(LOCATION_A); will(returnValue(TRACK_A)); allowing (playlist).hasTrackFor(LOCATION_B); will(returnValue(true)); allowing (playlist).trackFor(LOCATION_B); will(returnValue(TRACK_B)); allowing (playlist).hasTrackFor(with(any(String.class))); will(returnValue(false)); }}); } public void testStartsPlayingTrackForCurrentLocationWhenLocationFirstDetected() { checking(new Expectations() {{ oneOf (mediaControl).play(TRACK_A); }}); dj.locationChangedTo(LOCATION_A); } public void testPlaysTrackForCurrentLocationWhenPreviousTrackFinishesIfLocationChangedWhileTrackWasPlaying() { startingIn(LOCATION_A); dj.locationChangedTo(LOCATION_B); checking(new Expectations() {{ oneOf (mediaControl).play(TRACK_B); }}); dj.mediaFinished(); } public void testDoesNotPlayTrackAgainIfStillInTheSameLocation() { startingIn(LOCATION_A); checking(new Expectations() {{ never (mediaControl).play(with(any(String.class))); }}); dj.mediaFinished(); } public void testPlaysNewTrackAsSoonAsLocationChangesIfPreviousTrackFinishedWhileInSameLocation() { startingIn(LOCATION_A); dj.mediaFinished(); checking(new Expectations() {{ oneOf (mediaControl).play(TRACK_B); }}); dj.locationChangedTo(LOCATION_B); } private void startingIn(String initialLocation) { checking(new Expectations() {{ oneOf (mediaControl).play(with(any(String.class))); }}); dj.locationChangedTo(initialLocation); } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/LocationAware.java000066400000000000000000000001701347002534600314130ustar00rootroot00000000000000package org.jmock.example.qcon; public interface LocationAware { void locationChangedTo(String newLocationName); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/MediaControl.java000066400000000000000000000001451347002534600312450ustar00rootroot00000000000000package org.jmock.example.qcon; public interface MediaControl { void play(String mediaFile); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/MediaTracker.java000066400000000000000000000001351347002534600312170ustar00rootroot00000000000000package org.jmock.example.qcon; public interface MediaTracker { void mediaFinished(); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/qcon/Playlist.java000066400000000000000000000002171347002534600304660ustar00rootroot00000000000000package org.jmock.example.qcon; public interface Playlist { boolean hasTrackFor(String location); String trackFor(String location); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/000077500000000000000000000000001347002534600263625ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/Auction.java000066400000000000000000000001731347002534600306300ustar00rootroot00000000000000package org.jmock.example.sniper; public interface Auction { public void bid(Money amount) throws AuctionException; } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/AuctionException.java000066400000000000000000000003611347002534600325060ustar00rootroot00000000000000package org.jmock.example.sniper; public class AuctionException extends Exception { public AuctionException(String message) { super(message); } public AuctionException(String message, Exception cause) { super(message, cause); } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/AuctionListener.java000066400000000000000000000001721347002534600323350ustar00rootroot00000000000000package org.jmock.example.sniper; public interface AuctionListener { void bidAccepted(Auction item, Money amount); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/AuctionSniper.java000066400000000000000000000020101347002534600320010ustar00rootroot00000000000000package org.jmock.example.sniper; public class AuctionSniper implements AuctionListener { private Auction lotToBidFor; private Money bidIncrement; private Money maximumBid; private AuctionSniperListener listener; public AuctionSniper(Auction lotToBidFor, Money bidIncrement, Money maximumBid, AuctionSniperListener listener) { this.lotToBidFor = lotToBidFor; this.bidIncrement = bidIncrement; this.maximumBid = maximumBid; this.listener = listener; } public void bidAccepted(Auction lot, Money amount) { if (lot != lotToBidFor) return; if (amount.compareTo(maximumBid) <= 0) { placeBid(lot, amount); } else { listener.sniperFinished(this); } } private void placeBid(Auction item, Money amount) { try { item.bid(Money.min(maximumBid, amount.add(bidIncrement))); } catch (AuctionException ex) { listener.sniperBidFailed(this, ex); } } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/AuctionSniperListener.java000066400000000000000000000003701347002534600335160ustar00rootroot00000000000000package org.jmock.example.sniper; import java.util.EventListener; public interface AuctionSniperListener extends EventListener { void sniperBidFailed(AuctionSniper sniper, AuctionException failure); void sniperFinished(AuctionSniper sniper); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/AuctionSniperTests.java000066400000000000000000000045331347002534600330400ustar00rootroot00000000000000package org.jmock.example.sniper; import org.jmock.Expectations; import org.jmock.integration.junit3.MockObjectTestCase; public class AuctionSniperTests extends MockObjectTestCase { Money increment = new Money(2); Money maximumBid = new Money(20); Money beatableBid = new Money(10); Money unbeatableBid = maximumBid.add(new Money(1)); Auction auction = mock(Auction.class); AuctionSniperListener listener = mock(AuctionSniperListener.class, "listener"); AuctionSniper sniper = new AuctionSniper(auction, increment, maximumBid, listener); public void testTriesToBeatTheLatestHighestBid() throws Exception { final Money expectedBid = beatableBid.add(increment); checking(new Expectations() {{ oneOf (auction).bid(expectedBid); }}); sniper.bidAccepted(auction, beatableBid); } public void testWillNotBidPriceGreaterThanMaximum() throws Exception { checking(new Expectations() {{ ignoring (listener); never (auction).bid(with(any(Money.class))); }}); sniper.bidAccepted(auction, unbeatableBid); } public void testWillLimitBidToMaximum() throws Throwable { checking(new Expectations() {{ exactly(1).of (auction).bid(maximumBid); }}); sniper.bidAccepted(auction, maximumBid.subtract(new Money(1))); } public void testWillNotBidWhenToldAboutBidsOnOtherItems() throws Throwable { final Auction otherLot = mock(Auction.class, "otherLot"); checking(new Expectations() {{ never (otherLot).bid(new Money(10)); }}); sniper.bidAccepted(otherLot, beatableBid); } public void testWillAnnounceItHasFinishedIfPriceGoesAboveMaximum() { checking(new Expectations() {{ exactly(1).of (listener).sniperFinished(sniper); }}); sniper.bidAccepted(auction, unbeatableBid); } public void testCatchesExceptionsAndReportsThemToErrorListener() throws Exception { final AuctionException exception = new AuctionException("test"); checking(new Expectations() {{ allowing (auction).bid(with(any(Money.class))); will(throwException(exception)); exactly(1).of (listener).sniperBidFailed(sniper, exception); }}); sniper.bidAccepted(auction, beatableBid); } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/sniper/Money.java000066400000000000000000000022061347002534600303140ustar00rootroot00000000000000package org.jmock.example.sniper; import java.math.BigDecimal; public class Money implements Comparable { private BigDecimal amount; public Money(BigDecimal amount) { this.amount = amount; } public Money(int amount) { this(new BigDecimal(amount)); } public Money(double amount) { this(new BigDecimal(amount)); } public Money add(Money other) { return new Money(amount.add(other.amount)); } public Money subtract(Money other) { return new Money(amount.subtract(other.amount)); } @Override public String toString() { return "£" + amount; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return amount.equals(((Money) o).amount); } @Override public int hashCode() { return amount.hashCode(); } public int compareTo(Money other) { return amount.compareTo(other.amount); } public static Money min(Money m1, Money m2) { return new Money(m1.amount.min(m2.amount)); } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/timedcache/000077500000000000000000000000001347002534600271505ustar00rootroot00000000000000jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/timedcache/Clock.java000066400000000000000000000001531347002534600310450ustar00rootroot00000000000000package org.jmock.example.timedcache; import java.util.Date; public interface Clock { Date time(); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/timedcache/ObjectLoader.java000066400000000000000000000001461347002534600323510ustar00rootroot00000000000000package org.jmock.example.timedcache; public interface ObjectLoader { Object load(Object key); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/timedcache/ReloadPolicy.java000066400000000000000000000002321347002534600323760ustar00rootroot00000000000000package org.jmock.example.timedcache; import java.util.Date; public interface ReloadPolicy { boolean shouldReload(Date loadTime, Date fetchTime); } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/timedcache/TimedCache.java000066400000000000000000000022771347002534600320110ustar00rootroot00000000000000package org.jmock.example.timedcache; import java.util.Date; import java.util.HashMap; import java.util.Map; public class TimedCache { private ObjectLoader loader; private Clock clock; private ReloadPolicy reloadPolicy; private Map cache = new HashMap(); public TimedCache(ObjectLoader loader, Clock clock, ReloadPolicy reloadPolicy) { this.loader = loader; this.clock = clock; this.reloadPolicy = reloadPolicy; } public Object lookup(Object key) { Date fetchTime = clock.time(); TimestampedValue cached = cache.get(key); if (cached == null || reloadPolicy.shouldReload(cached.loadTime, fetchTime)) { Object value = loader.load(key); cached = new TimestampedValue(value, fetchTime); cache.put(key, cached); } return cached.value; } private class TimestampedValue { public final Object value; public final Date loadTime; public TimestampedValue(Object value, Date timestamp) { this.value = value; this.loadTime = timestamp; } } } jmock-library-2.12.0/jmock-example/src/main/java/org/jmock/example/timedcache/TimedCacheTests.java000066400000000000000000000066231347002534600330330ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.example.timedcache; import java.util.Calendar; import java.util.Date; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit3.JUnit3ErrorTranslator; public class TimedCacheTests extends TestCase { final private Object KEY = "key"; final private Object VALUE = "value"; final private Object NEW_VALUE = "newValue"; private Mockery context = new Mockery() {{ setExpectationErrorTranslator(JUnit3ErrorTranslator.INSTANCE); }}; private Clock clock = context.mock(Clock.class); private ObjectLoader loader = context.mock(ObjectLoader.class, "loader"); private ReloadPolicy reloadPolicy = context.mock(ReloadPolicy.class); private TimedCache cache = new TimedCache(loader, clock, reloadPolicy); private Date loadTime = time(1); private Date fetchTime = time(2); public void testLoadsObjectThatIsNotCached() { final Object VALUE1 = "value1"; final Object VALUE2 = "value2"; context.checking(new Expectations() {{ allowing (clock).time(); will(returnValue(loadTime)); oneOf (loader).load("key1"); will(returnValue(VALUE1)); oneOf (loader).load("key2"); will(returnValue(VALUE2)); }}); Object actualValue1 = cache.lookup("key1"); Object actualValue2 = cache.lookup("key2"); context.assertIsSatisfied(); assertEquals("lookup with key1", VALUE1, actualValue1); assertEquals("lookup with key2", VALUE2, actualValue2); } public void testReturnsCachedObjectWithinTimeout() { context.checking(new Expectations() {{ oneOf (clock).time(); will(returnValue(loadTime)); oneOf (clock).time(); will(returnValue(fetchTime)); allowing (reloadPolicy).shouldReload(loadTime, fetchTime); will(returnValue(false)); oneOf (loader).load(KEY); will(returnValue(VALUE)); }}); Object actualValueFromFirstLookup = cache.lookup(KEY); Object actualValueFromSecondLookup = cache.lookup(KEY); context.assertIsSatisfied(); assertSame("should be loaded object", VALUE, actualValueFromFirstLookup); assertSame("should be cached object", VALUE, actualValueFromSecondLookup); } public void testReloadsCachedObjectAfterTimeout() { context.checking(new Expectations() {{ allowing (reloadPolicy).shouldReload(loadTime, fetchTime); will(returnValue(true)); oneOf (clock).time(); will(returnValue(loadTime)); oneOf (loader).load(KEY); will(returnValue(VALUE)); oneOf (clock).time(); will(returnValue(fetchTime)); oneOf (loader).load(KEY); will(returnValue(NEW_VALUE)); }}); Object actualValueFromFirstLookup = cache.lookup(KEY); Object actualValueFromSecondLookup = cache.lookup(KEY); context.assertIsSatisfied(); assertSame("should be loaded object", VALUE, actualValueFromFirstLookup); assertSame("should be reloaded object", NEW_VALUE, actualValueFromSecondLookup); } private Date time(int i) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.DAY_OF_YEAR, i); return calendar.getTime(); } } jmock-library-2.12.0/jmock-imposters-tests/000077500000000000000000000000001347002534600206335ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/pom.xml000066400000000000000000000043761347002534600221620ustar00rootroot00000000000000 4.0.0 org.jmock jmock-parent 2.12.0 jmock-imposters-tests org.hamcrest hamcrest-library org.jmock jmock ${project.version} test-jar org.jmock jmock-junit4 ${project.version} org.jmock jmock-junit5 ${project.version} org.jmock jmock-testjar ${project.version} test org.junit.jupiter junit-jupiter-api compile org.junit.jupiter junit-jupiter-engine org.junit.jupiter junit-jupiter-params org.junit.platform junit-platform-launcher org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-imposters-tests/src/000077500000000000000000000000001347002534600214225ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/000077500000000000000000000000001347002534600224015ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/000077500000000000000000000000001347002534600233225ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/000077500000000000000000000000001347002534600241115ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/000077500000000000000000000000001347002534600252145ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/000077500000000000000000000000001347002534600261735ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/000077500000000000000000000000001347002534600302615ustar00rootroot00000000000000AbstractImposteriserParameterResolver.java000066400000000000000000000030261347002534600406020ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Stream; import org.jmock.api.Imposteriser; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; /** * Provide known instances of Code Generating ClassImposteriser for tests * Because reflection can't be used for class imposterisation * * This is a Java 7 implementation, Java 8 is a lot simpler! * * @author oliverbye * */ public abstract class AbstractImposteriserParameterResolver implements ArgumentsProvider { private final Imposteriser[] imposters; public AbstractImposteriserParameterResolver(Imposteriser... imposters) { this.imposters = imposters; } @Override public Stream provideArguments(ExtensionContext context) { return Arrays.stream(imposters).map(new FunctionImplementation()); } // Java1.7 needs private static final class FunctionImplementation implements Function { @Override public Arguments apply(Imposteriser i) { return new ArgumentSupplier(i); } } private static final class ArgumentSupplier implements Arguments { private Imposteriser i; public ArgumentSupplier(Imposteriser i) { this.i = i; } @Override public Object[] get() { return new Object[] { i }; } } } ClassLoaderAcceptanceTests.java000066400000000000000000000076011347002534600362370ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.acceptance; import static org.junit.Assert.assertTrue; import java.io.File; import java.lang.Thread.UncaughtExceptionHandler; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import org.jmock.Mockery; import org.jmock.api.Imposteriser; import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver; import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class ClassLoaderAcceptanceTests { private static final String UNSIGNED_JAR_NAME = "../testjar/target/unsigned.jar"; private static final String CLASS_FROM_OTHER_CLASS_LOADER = "org.jmock.testjar.ClassFromOtherClassLoader"; private static final String INTERFACE_FROM_OTHER_CLASS_LOADER = "org.jmock.testjar.InterfaceFromOtherClassLoader"; Mockery mockery = new Mockery(); ClassLoader classLoader; @BeforeEach public void setUp() throws MalformedURLException, URISyntaxException { File unsignedFile = new File(UNSIGNED_JAR_NAME); assertTrue("The unsigned file is missing, mvn package will build it",unsignedFile.exists()); classLoader = new URLClassLoader(new URL[]{unsignedFile.toURI().toURL()}, null); } @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void testMockingInterfaceFromOtherClassLoaderWithClassImposteriser(Imposteriser imposteriserImpl) throws ClassNotFoundException { mockery.setImposteriser(imposteriserImpl); mockery.mock(classLoader.loadClass(INTERFACE_FROM_OTHER_CLASS_LOADER)); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testMockingClassFromOtherClassLoaderWithClassImposteriser(Imposteriser imposteriserImpl) throws ClassNotFoundException { mockery.setImposteriser(imposteriserImpl); mockery.mock(classLoader.loadClass(CLASS_FROM_OTHER_CLASS_LOADER)); } // I've been unable to reproduce the behaviour of the Maven Surefire plugin in plain JUnit tests @Disabled @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testMockingClassFromThreadContextClassLoader(final Imposteriser imposteriserImpl) throws Throwable { Runnable task = new Runnable() { public void run() { try { Class classToMock = Thread.currentThread().getContextClassLoader().loadClass(CLASS_FROM_OTHER_CLASS_LOADER); Mockery threadMockery = new Mockery(); threadMockery.setImposteriser(imposteriserImpl); threadMockery.mock(classToMock); } catch (ClassNotFoundException e) { throw new IllegalStateException("could not load class", e); } } }; ExceptionTrap exceptionTrap = new ExceptionTrap(); Thread thread = new Thread(task, getClass().getSimpleName() + " Thread"); thread.setContextClassLoader(new URLClassLoader(new URL[]{new URL("file:build/testdata/unsigned.jar")}, null)); thread.setUncaughtExceptionHandler(exceptionTrap); thread.start(); thread.join(); if (exceptionTrap.exception != null) { throw exceptionTrap.exception; } } private static class ExceptionTrap implements UncaughtExceptionHandler { public Throwable exception = null; public void uncaughtException(Thread t, Throwable e) { exception = e; } } } FinalizerIsIgnoredAcceptanceTests.java000066400000000000000000000016101347002534600375640ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import org.jmock.Mockery; import org.jmock.api.Imposteriser; import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class FinalizerIsIgnoredAcceptanceTests { public static class ClassWithFinalizer { @Override protected void finalize() throws Throwable { super.finalize(); } } Mockery mockery = new Mockery(); @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testIgnoresFinalizerInMockedClasses(Imposteriser imposteriserImpl) throws Throwable { mockery.setImposteriser(imposteriserImpl); ClassWithFinalizer mock = mockery.mock(ClassWithFinalizer.class, "mock"); mock.finalize(); } } InvocationDescriptionAcceptanceTests.java000066400000000000000000000044731347002534600403640ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import org.jmock.Expectations; import org.jmock.api.Imposteriser; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * @author Steve Freeman 2012 http://www.jmock.org */ public class InvocationDescriptionAcceptanceTests { private static final String UNEXPECTED_ARGUMENT = "unexpected argument"; private final JUnit4Mockery aMockContext = new JUnit4Mockery(); private final SubBean aSubBean = aMockContext.mock(SubBean.class); private final Collaborator aCollab = aMockContext.mock(Collaborator.class); // https://github.com/jmock-developers/jmock-library/issues/20 @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void doesNotModifyInvocationsWhileReportingFailure(Imposteriser imposteriserImpl) { final Bean lBean = new Bean(aSubBean); aMockContext.checking(new Expectations() {{ allowing(aSubBean).count(); will(returnValue(123)); oneOf(aCollab).message("xyzzy", lBean); }}); try { new Subject(aCollab).doIt(lBean); } catch (AssertionError expected) { assertThat(expected.getMessage(), containsString("collaborator.message(\"unexpected argument\", )")); return; } fail("should have thrown exception"); } static class Bean { private final SubBean aSubBean; public Bean(SubBean pSubBean) { aSubBean = pSubBean; } @Override public String toString() { // called via describeTo() when reporting error return String.format("Bean{%d}", aSubBean.count()); } } interface SubBean { int count(); } interface Collaborator { void message(String pX, Bean pBean); } static class Subject { private final Collaborator aCollab; public Subject(Collaborator pCollab) { aCollab = pCollab; } @SuppressWarnings("UnusedDeclaration") void doIt(Bean pBean) { aCollab.message(UNEXPECTED_ARGUMENT, pBean); } } } MockeryFinalizationAcceptanceTests.java000066400000000000000000000076031347002534600400260ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.junit.Assert.assertThat; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.ref.WeakReference; import org.jmock.Mockery; import org.jmock.api.Imposteriser; import org.jmock.lib.concurrent.Synchroniser; import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver; import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * Nasty test to show GitHub #36 is fixed. */ public class MockeryFinalizationAcceptanceTests { private static final int FINALIZE_COUNT = 10; // consistently shows a problem before GitHub #36 was fixed private final Mockery mockery = new Mockery() {{ setThreadingPolicy(new Synchroniser()); }}; private final ErrorStream capturingErr = new ErrorStream(); @BeforeAll public static void clearAnyOutstandingMessages() { ErrorStream localErr = new ErrorStream(); localErr.install(); String error = null; try { finalizeUntilMessageOrCount(localErr, FINALIZE_COUNT); error = localErr.output(); } finally { localErr.uninstall(); } if (error != null) System.err.println("WARNING - a previous test left output in finalization [" + error + "]"); } @BeforeEach public void captureSysErr() { capturingErr.install(); } @AfterEach public void replaceSysErr() { capturingErr.uninstall(); } @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void mockedInterfaceDoesntWarnOnFinalize(Imposteriser imposterImpl) { mockery.setImposteriser(imposterImpl); checkNoFinalizationMessage(mockery, CharSequence.class); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void mockedClassDoesntWarnOnFinalize(Imposteriser imposterImpl) { mockery.setImposteriser(imposterImpl); checkNoFinalizationMessage(mockery, Object.class); } public interface TypeThatMakesFinalizePublic { public void finalize(); } @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void mockedTypeThatMakesFinalizePublicDoesntWarnOnFinalize(Imposteriser imposterImpl) { mockery.setImposteriser(imposterImpl); checkNoFinalizationMessage(mockery, TypeThatMakesFinalizePublic.class); } private void checkNoFinalizationMessage(Mockery mockery, Class typeToMock) { WeakReference mockHolder = new WeakReference(mockery.mock(typeToMock)); while (mockHolder.get() != null) { System.gc(); System.runFinalization(); } finalizeUntilMessageOrCount(capturingErr, FINALIZE_COUNT); assertThat(capturingErr.output(), isEmptyOrNullString()); } private static void finalizeUntilMessageOrCount(ErrorStream capturingErr, int count) { for (int i = 0; i < count && capturingErr.output().isEmpty(); i++) { System.gc(); System.runFinalization(); } } private static class ErrorStream extends PrintStream { private PrintStream oldSysErr; public ErrorStream() { super(new ByteArrayOutputStream()); } public void install() { oldSysErr = System.err; System.setErr(this); } public void uninstall() { System.setErr(oldSysErr); } public String output() { return new String(((ByteArrayOutputStream) out).toByteArray()); } } }MockingClassesAcceptanceTests.java000066400000000000000000000035431347002534600367510ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import static org.junit.Assert.assertSame; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Imposteriser; import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver; import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver; import org.jmock.testjar.InterfaceFromOtherClassLoader; import org.junit.Assert; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class MockingClassesAcceptanceTests { public static final class FinalClass { } public static class ClassToMock { public FinalClass returnInstanceOfFinalClass() { return null; } } Mockery context = new Mockery(); @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testCanMockClassesWithMethodsThatReturnFinalClasses(Imposteriser imposteriserImpl) { context.setImposteriser(imposteriserImpl); final ClassToMock mock = context.mock(ClassToMock.class); final FinalClass result = new FinalClass(); context.checking(new Expectations() { { oneOf(mock).returnInstanceOfFinalClass(); will(returnValue(result)); } }); // This should not crash assertSame(result, mock.returnInstanceOfFinalClass()); } @SuppressWarnings("rawtypes") @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void testMockClassIsCached(Imposteriser imposteriserImpl) { Class class1 = context.mock(InterfaceFromOtherClassLoader.class,"1").getClass(); Class class2 = context.mock(InterfaceFromOtherClassLoader.class,"2").getClass(); Assert.assertEquals("Type should be cached", class1, class2); } } MockingGenericsFromOtherClassLoadersAcceptanceTests.java000066400000000000000000000067621347002534600432470ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.jmock.imposters.ByteBuddyClassImposteriser; import org.jmock.integration.junit4.JUnitRuleMockery; import org.jmock.testjar.InterfaceFromOtherClassLoader; import org.junit.Rule; import org.junit.Test; import org.junit.jupiter.api.Disabled; /** * This tests the solution to a longstanding jMock issue. Mock return values for * generic interfaces loaded by other class loaders had the type constraint of * the source interface not the runtime type. The ByteBuddyClassImposteriser * oxposed this issue as it cast mocked method return values to their target * type. This caused ClassCastExceptions. Returning null in the cases where * we're building expectations is the simple solution. Once will(returnValue()) * has bee called then the actual mock reply is known and can be returned at * expectation assertion time. * * @author oliverbye * */ public class MockingGenericsFromOtherClassLoadersAcceptanceTests { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery() { { setImposteriser(ByteBuddyClassImposteriser.INSTANCE); } }; /** * This test case requires a generic mock. */ @Mock public InterfaceFromOtherClassLoader mock; @SuppressWarnings("unused") @Test public void testWhenDefinedAndInvokedThroughClass() throws Exception { context.checking(new Expectations() { { // Assigning the mock is not normal // We do this to prove that the result is assignable to the generic interfaces // runtime type (ABean) ABean bean = oneOf(mock).stir(ABEAN); will(returnValue(ABEAN)); } }); ABean result1 = mock.stir(ABEAN); } @SuppressWarnings("unused") @Test public void testWhenDefinedThroughClassAndInvokedThroughMethod() throws Exception { context.checking(new Expectations() { { ABean bean = oneOf(mock).stir(ABEAN); will(returnValue(ABEAN)); } }); // Note: this is invoked through a "bridge" method and so the method // invoked when expectations are checked appears to be different from // that invoked when expectations are captured. ABean result1 = ((InterfaceFromOtherClassLoader) mock).stir(ABEAN); } @Disabled public void DONTtestAndBoxedNativeParameterIgnoingIsADocumentationWhenDefinedThroughClassAndInvokedThroughMethod() throws Exception { context.checking(new Expectations() { { oneOf(mock).stir(with(any(Integer.class))); will(returnValue(ABEAN)); } }); // Note: this is invoked through a "bridge" method and so the method // invoked when expectations are checked appears to be different from // that invoked when expectations are captured. ((InterfaceFromOtherClassLoader) mock).stir(ABEAN); } @SuppressWarnings("unused") @Test public void testWhenDefinedAndInvokedThroughInterface() throws Exception { context.checking(new Expectations() { { ABean bean = oneOf(mock).stir(ABEAN); will(returnValue(ABEAN)); } }); ABean result1 = mock.stir(ABEAN); } public static abstract class ABean { } public ABean ABEAN = new ABean() { }; } MockingImplementationOfGenericTypeAcceptanceTests.java000066400000000000000000000063431347002534600427660ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Imposteriser; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class MockingImplementationOfGenericTypeAcceptanceTests { private Mockery context = new JUnit4Mockery(); @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testWhenDefinedAndInvokedThroughClass(Imposteriser imposteriserImpl) throws Exception { context.setImposteriser(imposteriserImpl); final AnImplementation mock = context.mock(AnImplementation.class); context.checking(new Expectations() { { oneOf(mock).doSomethingWith("a"); } }); mock.doSomethingWith("a"); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testWhenDefinedThroughClassAndInvokedThroughMethod(Imposteriser imposteriserImpl) throws Exception { context.setImposteriser(imposteriserImpl); final AnImplementation mock = context.mock(AnImplementation.class); context.checking(new Expectations() { { oneOf(mock).doSomethingWith("a"); } }); // Note: this is invoked through a "bridge" method and so the method // invoked when expectations are checked appears to be different from // that invoked when expectations are captured. ((AnInterface) mock).doSomethingWith("a"); } @Disabled public void DONTtestAndBoxedNativeParameterIgnoingIsADocumentationWhenDefinedThroughClassAndInvokedThroughMethod() throws Exception { final AnImplementation mock = context.mock(AnImplementation.class); context.checking(new Expectations() { { oneOf(mock).doSomethingWith(with(any(Integer.class))); } }); // Note: this is invoked through a "bridge" method and so the method // invoked when expectations are checked appears to be different from // that invoked when expectations are captured. ((AnInterface) mock).doSomethingWith("a"); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testWhenDefinedAndInvokedThroughInterface(Imposteriser imposteriserImpl) throws Exception { context.setImposteriser(imposteriserImpl); final AnInterface mock = context.mock(AnImplementation.class); context.checking(new Expectations() { { oneOf(mock).doSomethingWith("a"); } }); mock.doSomethingWith("a"); } public interface AnInterface { void doSomethingWith(T arg); void doSomethingWith(int arg); } public static class AnImplementation implements AnInterface { public void doSomethingWith(String arg) { } public void doSomethingWith(int arg) { } } } MockingPackageProtectedTypeAcceptanceTests.java000066400000000000000000000025321347002534600414200ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.jmock.Mockery; import org.jmock.api.Imposteriser; import org.jmock.internal.CaptureControl; import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class MockingPackageProtectedTypeAcceptanceTests { Mockery mockery = new Mockery(); @Test public void testCanCreateReflectionProxyOfPackageProtectedType() { Class typeToProxy = PackageProtectedType.class; Proxy.newProxyInstance( typeToProxy.getClassLoader(), new Class[]{typeToProxy, CaptureControl.class}, new InvocationHandler(){ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); } @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void testCanMockPackageProtectedTypeWithObjenesisImposteriser(Imposteriser imposteriserImpl) { mockery.setImposteriser(imposteriserImpl); mockery.mock(PackageProtectedType.class, "mock"); } } RedeclaredObjectMethodsAcceptanceTests.java000066400000000000000000000044551347002534600405540ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import static org.junit.Assert.assertEquals; import java.util.Vector; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; import org.jmock.api.Imposteriser; import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver; import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; // Fixes issue JMOCK-96 public class RedeclaredObjectMethodsAcceptanceTests { Mockery context = new Mockery(); public interface MockedInterface { String toString(); } public static class MockedClass { @Override public String toString() { return "not mocked"; } } @ParameterizedTest @ArgumentsSource(ImposteriserParameterResolver.class) public void testCanRedeclareObjectMethodsInMockedInterfaces(Imposteriser imposteriserImpl) { context.setImposteriser(imposteriserImpl); MockedInterface mock = context.mock(MockedInterface.class, "X"); assertEquals("X", mock.toString()); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testCanRedeclareObjectMethodsInMockedClasses(Imposteriser imposteriserImpl) { context.setImposteriser(imposteriserImpl); MockedClass mock = context.mock(MockedClass.class, "X"); assertEquals("X", mock.toString()); } /* * Adapted from Jira issue JMOCK-96 */ @SuppressWarnings("unchecked") @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void testUseMockObjectHangs1(Imposteriser imposteriserImpl) { context.setImposteriser(imposteriserImpl); final Vector mock = (Vector) context.mock(Vector.class); context.checking(new Expectations() { { atLeast(1).of(mock).size(); will(returnValue(2)); } }); try { for (int i = 0; i < mock.size(); i++) { System.out.println("Vector entry " + i + " = " + mock.get(i)); } } catch (ExpectationError error) { // expected } } } jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/000077500000000000000000000000001347002534600271525ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/000077500000000000000000000000001347002534600277205ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/000077500000000000000000000000001347002534600311645ustar00rootroot00000000000000ClassImposteriserTests.java000066400000000000000000000167441347002534600364620ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacypackage org.jmock.test.unit.lib.legacy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.Date; import org.jmock.api.Action; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.api.Invokable; import org.jmock.lib.action.ReturnValueAction; import org.jmock.lib.action.VoidAction; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; public class ClassImposteriserTests { Action action = new ReturnValueAction("result"); @SuppressWarnings("ClassInitializerMayBeStatic") public static class ConcreteClassWithNastyConstructor { { nasty("initialisation block should not be run"); } public ConcreteClassWithNastyConstructor() { nasty("constructor should not be run"); } public String foo() { nasty("should not be run"); return null; // never reached } private static void nasty(String nastiness) { throw new IllegalStateException(nastiness); } } public interface AnInterface { String foo(); } public static abstract class AnAbstractNestedClass { @SuppressWarnings("UnusedDeclaration") public abstract String foo(); } public static class AnInnerClass { @SuppressWarnings("UnusedDeclaration") public String foo() {return "original result";} } public static final class AFinalClass { @SuppressWarnings("UnusedDeclaration") public String foo() {return "original result";} } public static class AClassWithAPrivateConstructor { @SuppressWarnings("unused") private AClassWithAPrivateConstructor(String someArgument) {} public String foo() {return "original result";} } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void canImposteriseInterfacesAndNonFinalInstantiableClasses(Imposteriser imposteriser) { assertTrue("should report that it can imposterise interfaces", imposteriser.canImposterise(Runnable.class)); assertTrue("should report that it can imposterise classes", imposteriser.canImposterise(Date.class)); assertTrue("should report that it cannot imposterise final classes", !imposteriser.canImposterise(AFinalClass.class)); assertTrue("should report that it can imposterise nested classes", imposteriser.canImposterise(AnAbstractNestedClass.class)); assertTrue("should report that it can imposterise inner classes", imposteriser.canImposterise(AnInnerClass.class)); assertTrue("should report that it can imposterise classes with non-public constructors", imposteriser.canImposterise(AClassWithAPrivateConstructor.class)); assertTrue("should report that it cannot imposterise primitive types", !imposteriser.canImposterise(int.class)); assertTrue("should report that it cannot imposterise void", !imposteriser.canImposterise(void.class)); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void canImposteriseAConcreteClassWithoutCallingItsConstructorOrInstanceInitialiserBlocks(Imposteriser imposteriser) { ConcreteClassWithNastyConstructor imposter = imposteriser.imposterise(action, ConcreteClassWithNastyConstructor.class); assertEquals("result", imposter.foo()); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void canImposteriseAnInterface(Imposteriser imposteriser) { AnInterface imposter = imposteriser.imposterise(action, AnInterface.class); assertEquals("result", imposter.foo()); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void canImposteriseAClassWithAPrivateConstructor(Imposteriser imposteriser) { AClassWithAPrivateConstructor imposter = imposteriser.imposterise(action, AClassWithAPrivateConstructor.class); assertEquals("result", imposter.foo()); } @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void canImposteriseAClassInASignedJarFile(Imposteriser imposteriser) throws Exception { File jarFile = new File("../testjar/target/signed.jar"); assertTrue("Signed JAR file does not exist (use Ant to build it", jarFile.exists()); URL jarURL = jarFile.toURI().toURL(); // Can't close as we might be in java 6 @SuppressWarnings("resource") URLClassLoader loader = new URLClassLoader(new URL[]{jarURL}); Class typeInSignedJar = loader.loadClass("org.jmock.testjar.TypeInSignedJar"); Object o = imposteriser.imposterise(new VoidAction(), typeInSignedJar); assertTrue(typeInSignedJar.isInstance(o)); } public static class ClassWithFinalToStringMethod { @Override public final String toString() { return "you can't override me!"; } } // See issue JMOCK-150 @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void cannotImposteriseAClassWithAFinalToStringMethod(Imposteriser imposteriser) { assertTrue("should not be able to imposterise it", !imposteriser.canImposterise(ClassWithFinalToStringMethod.class)); try { imposteriser.imposterise(new VoidAction(), ClassWithFinalToStringMethod.class); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } // See issue JMOCK-256 (Github #36) @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void doesntDelegateFinalizeMethod(Imposteriser imposteriser) throws Exception { Invokable failIfInvokedAction = new Invokable() { public Object invoke(Invocation invocation) throws Throwable { fail("invocation should not have happened"); return null; } }; Object imposter = imposteriser.imposterise(failIfInvokedAction, Object.class); invokeMethod(imposter, Object.class.getDeclaredMethod("finalize")); } public interface EmptyInterface {} // See issue JMOCK-145 @ParameterizedTest @ArgumentsSource(CodeGeneratingImposteriserParameterResolver.class) public void worksAroundBugInCglibWhenAskedToImposteriseObject(Imposteriser imposteriser) { imposteriser.imposterise(new VoidAction(), Object.class); imposteriser.imposterise(new VoidAction(), Object.class, EmptyInterface.class); imposteriser.imposterise(new VoidAction(), Object.class, AnInterface.class); } private Object invokeMethod(Object object, Method method, Object... args) throws IllegalAccessException, InvocationTargetException { method.setAccessible(true); return method.invoke(object, args); } } CodeGeneratingImposteriserParameterResolver.java000066400000000000000000000007451347002534600426250ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacypackage org.jmock.test.unit.lib.legacy; import org.jmock.imposters.ByteBuddyClassImposteriser; import org.jmock.lib.legacy.ClassImposteriser; import org.jmock.test.acceptance.AbstractImposteriserParameterResolver; public class CodeGeneratingImposteriserParameterResolver extends AbstractImposteriserParameterResolver { public CodeGeneratingImposteriserParameterResolver() { super(ByteBuddyClassImposteriser.INSTANCE, ClassImposteriser.INSTANCE); } } ImposteriserParameterResolver.java000066400000000000000000000012161347002534600400200ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacypackage org.jmock.test.unit.lib.legacy; import org.jmock.imposters.ByteBuddyClassImposteriser; import org.jmock.lib.JavaReflectionImposteriser; import org.jmock.lib.legacy.ClassImposteriser; import org.jmock.test.acceptance.AbstractImposteriserParameterResolver; /** * Provide known instances of ClassImposteriser for tests * * @author oliverbye * */ public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver { public ImposteriserParameterResolver() { super(ByteBuddyClassImposteriser.INSTANCE, ClassImposteriser.INSTANCE, JavaReflectionImposteriser.INSTANCE); } } Issue79And127UnitTest.java000066400000000000000000000045631347002534600356050ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacypackage org.jmock.test.unit.lib.legacy; import java.io.File; import javax.sql.DataSource; import org.jmock.api.Imposteriser; import org.jmock.imposters.ByteBuddyClassImposteriser; import org.jmock.junit5.JUnit5Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.jmock.test.acceptance.AbstractImposteriserParameterResolver; import org.junit.jupiter.api.condition.DisabledOnJre; import org.junit.jupiter.api.condition.JRE; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ArgumentsSource; /** * This used to fail in Java 8 as cglib-nodep used asm:5.0.3 which required * jdk<=7 Now we use cglib (not cglib-nodep) and override asm to 5.0.4 * * @see https://github.com/jmock-developers/jmock-library/issues/79 * @see https://github.com/cglib/cglib/issues/20 * */ public class Issue79And127UnitTest { @RegisterExtension public final JUnit5Mockery context = new JUnit5Mockery(); /** * However it fails in java 11 as asm and cglib do not appear to support java * 11 yet. Migrate all code to ByteBuddyClassImposteriser to solve this issue. * * java.lang.UnsupportedOperationException at * org.objectweb.asm.ClassVisitor.visitNestMemberExperimental(ClassVisitor.java:248) * * @param imposteriserImpl */ @DisabledOnJre({ JRE.JAVA_11 }) @ParameterizedTest @ArgumentsSource(ClassImposteriserParameterResolver.class) public void testMock(Imposteriser imposteriserImpl) { context.setImposteriser(imposteriserImpl); context.mock(File.class); } @ParameterizedTest @ArgumentsSource(ByteBuddyImposteriserParameterResolver.class) public void testByteBuddyImposteriser(Imposteriser imposteriserImpl) { context.setImposteriser(imposteriserImpl); context.mock(File.class); context.mock(DataSource.class); } public static class ByteBuddyImposteriserParameterResolver extends AbstractImposteriserParameterResolver { public ByteBuddyImposteriserParameterResolver() { super(ByteBuddyClassImposteriser.INSTANCE); } } public static class ClassImposteriserParameterResolver extends AbstractImposteriserParameterResolver { public ClassImposteriserParameterResolver() { super(ClassImposteriser.INSTANCE); } } } jmock-library-2.12.0/jmock-imposters/000077500000000000000000000000001347002534600174735ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/pom.xml000066400000000000000000000023721347002534600210140ustar00rootroot00000000000000 4.0.0 org.jmock jmock-parent 2.12.0 jmock-imposters Class mocks are more numerous than interface mocks, so drop the legacy name net.bytebuddy byte-buddy org.jmock jmock ${project.version} org.objenesis objenesis org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-imposters/src/000077500000000000000000000000001347002534600202625ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/src/main/000077500000000000000000000000001347002534600212065ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/src/main/java/000077500000000000000000000000001347002534600221275ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/src/main/java/org/000077500000000000000000000000001347002534600227165ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/src/main/java/org/jmock/000077500000000000000000000000001347002534600240215ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/src/main/java/org/jmock/imposters/000077500000000000000000000000001347002534600260465ustar00rootroot00000000000000ByteBuddyClassImposteriser.java000066400000000000000000000177471347002534600341410ustar00rootroot00000000000000jmock-library-2.12.0/jmock-imposters/src/main/java/org/jmock/imposterspackage org.jmock.imposters; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.api.Invokable; import org.jmock.internal.SearchingClassLoader; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import net.bytebuddy.ByteBuddy; import net.bytebuddy.NamingStrategy; import net.bytebuddy.description.modifier.Visibility; import net.bytebuddy.dynamic.DynamicType.Builder; import net.bytebuddy.dynamic.loading.ClassInjector; import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; import net.bytebuddy.implementation.FieldAccessor; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.implementation.bind.annotation.AllArguments; import net.bytebuddy.implementation.bind.annotation.FieldValue; import net.bytebuddy.implementation.bind.annotation.Origin; import net.bytebuddy.implementation.bind.annotation.RuntimeType; import net.bytebuddy.implementation.bind.annotation.This; import net.bytebuddy.matcher.ElementMatchers; /** * This class lets you imposterise abstract and concrete classes * without calling the constructors of the mocked class. * * @author olibye */ public class ByteBuddyClassImposteriser implements Imposteriser { public static final Imposteriser INSTANCE = new ByteBuddyClassImposteriser(); private static final String JMOCK_KEY = "jMock"; private final Objenesis objenesis = new ObjenesisStd(); private final Map>, Class> types = new ConcurrentHashMap>, Class>(); private ByteBuddyClassImposteriser() { } public boolean canImposterise(Class type) { return !type.isPrimitive() && !Modifier.isFinal(type.getModifiers()) && (type.isInterface() || !toStringMethodIsFinal(type)); } @Override public T imposterise(final Invokable mockObject, Class mockedType, Class... ancilliaryTypes) { if (!mockedType.isInterface() && toStringMethodIsFinal(mockedType)) { throw new IllegalArgumentException(mockedType.getName() + " has a final toString method"); } try { setConstructorsAccessible(mockedType, true); return proxy(mockObject, mockedType, ancilliaryTypes); } finally { setConstructorsAccessible(mockedType, false); } } private boolean toStringMethodIsFinal(Class type) { try { Method toString = type.getMethod("toString"); return Modifier.isFinal(toString.getModifiers()); } catch (SecurityException e) { throw new IllegalStateException("not allowed to reflect on toString method", e); } catch (NoSuchMethodException e) { throw new Error("no public toString method found", e); } } private void setConstructorsAccessible(Class mockedType, boolean accessible) { for (Constructor constructor : mockedType.getDeclaredConstructors()) { constructor.setAccessible(accessible); } } private T proxy( final Invokable mockObject, final Class mockedType, final Class... ancilliaryTypes) { try { Set> mockTypeKey = mockTypeKey(mockedType, ancilliaryTypes); Class proxyType = types.computeIfAbsent(mockTypeKey, new Function>() { @Override public Class apply(Object t) { try { return proxyClass(mockObject, mockedType, ancilliaryTypes); } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } } }); InjectInvokable invokable = (InjectInvokable) objenesis.newInstance(proxyType); invokable.setJMock(mockObject); return (T) invokable; } catch (IllegalArgumentException | SecurityException e) { throw new RuntimeException("Exception in code generation strategy available", e); } } public interface InjectInvokable { void setJMock(Invokable invokable); Invokable getJMock(); } public static class Interceptor { @RuntimeType static public Object intercept( @This Object receiver, @Origin Method method, @FieldValue(value=JMOCK_KEY) Invokable invokable, @AllArguments Object[] args ) throws Throwable { return invokable.invoke(new Invocation(receiver, method, args)); } } private Class proxyClass(final Invokable mockObject, final Class mockedType, Class... ancilliaryTypes) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Builder builder = new ByteBuddy() .with(new NamingStrategy.SuffixingRandom(JMOCK_KEY, JMOCK_KEY.toLowerCase())) .subclass(mockedType) .implement(ancilliaryTypes) .defineField(JMOCK_KEY, Invokable.class, Visibility.PRIVATE) .implement(InjectInvokable.class).intercept(FieldAccessor.ofField(JMOCK_KEY)) .method(ElementMatchers.not(ElementMatchers.isDeclaredBy(InjectInvokable.class))) .intercept(MethodDelegation.to(Interceptor.class)); /* .intercept(InvocationHandlerAdapter.of(new InvocationHandler() { public Object invoke(Object receiver, Method method, Object[] args) throws Throwable { return mockObject.invoke(new Invocation(receiver, method, args)); } })); */ // From // https://mydailyjava.blogspot.com/2018/04/jdk-11-and-proxies-in-world-past.html ClassLoadingStrategy strategy; if (ClassInjector.UsingLookup.isAvailable() && !protectedPackageNameSpaces(mockedType) && !defaultPackage(mockedType) && mockedType.getClassLoader() == this.getClass().getClassLoader()) { Class methodHandles = Class.forName("java.lang.invoke.MethodHandles"); Object lookup = methodHandles.getMethod("lookup").invoke(null); Method privateLookupIn = methodHandles.getMethod("privateLookupIn", Class.class, Class.forName("java.lang.invoke.MethodHandles$Lookup")); Object privateLookup = privateLookupIn.invoke(null, mockedType, lookup); strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); } else if (ClassInjector.UsingReflection.isAvailable()) { strategy = ClassLoadingStrategy.Default.INJECTION; } else { throw new IllegalStateException("No code generation strategy available"); } Class proxyType = builder.make() .load(SearchingClassLoader.combineLoadersOf(mockedType, ancilliaryTypes), strategy) .getLoaded(); return proxyType; } private Set> mockTypeKey(final Class mockedType, Class... ancilliaryTypes) { Set> types = new HashSet<>(); types.add(mockedType); for (Class class1 : ancilliaryTypes) { types.add(class1); } return types; } private boolean defaultPackage(Class mockedType) { return mockedType.getPackage().getName().isEmpty(); } private boolean protectedPackageNameSpaces(Class mockedType) { return mockedType.getName().startsWith("java."); } } jmock-library-2.12.0/jmock-imposters/src/main/java/org/jmock/imposters/package-info.java000066400000000000000000000002171347002534600312350ustar00rootroot00000000000000/** * These classes are tested in jmock-legacy to avoid a dependency on cglib and asm * @author oliverbye * */ package org.jmock.imposters;jmock-library-2.12.0/jmock-junit3/000077500000000000000000000000001347002534600166625ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/.gitignore000066400000000000000000000000111347002534600206420ustar00rootroot00000000000000/target/ jmock-library-2.12.0/jmock-junit3/pom.xml000066400000000000000000000034151347002534600202020ustar00rootroot00000000000000 4.0.0 org.jmock jmock-parent 2.12.0 jmock-junit3 UTF-8 junit junit 3.8.2 compile org.jmock jmock ${project.version} org.apache.maven.plugins maven-jar-plugin 2.5 test-jar org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-junit3/src/000077500000000000000000000000001347002534600174515ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/000077500000000000000000000000001347002534600203755ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/java/000077500000000000000000000000001347002534600213165ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/java/org/000077500000000000000000000000001347002534600221055ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/000077500000000000000000000000001347002534600232105ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/000077500000000000000000000000001347002534600255335ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/junit3/000077500000000000000000000000001347002534600267475ustar00rootroot00000000000000JUnit3ErrorTranslator.java000066400000000000000000000012761347002534600337410ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/junit3package org.jmock.integration.junit3; import junit.framework.AssertionFailedError; import org.hamcrest.StringDescription; import org.jmock.api.ExpectationError; import org.jmock.api.ExpectationErrorTranslator; /** * Translates {@link org.jmock.api.ExpectationError}s into JUnit's * {@link junit.framework.AssertionFailedError}s. * * @author npryce * */ public class JUnit3ErrorTranslator implements ExpectationErrorTranslator { public static final JUnit3ErrorTranslator INSTANCE = new JUnit3ErrorTranslator(); public Error translate(ExpectationError e) { return new AssertionFailedError(StringDescription.toString(e)); } private JUnit3ErrorTranslator() {} } jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/junit3/JUnit3Mockery.java000066400000000000000000000005061347002534600322610ustar00rootroot00000000000000package org.jmock.integration.junit3; import org.jmock.Mockery; /** * A {@link Mockery} that reports expectation errors as JUnit 3 test failures. * * @author nat */ public class JUnit3Mockery extends Mockery { public JUnit3Mockery() { setExpectationErrorTranslator(JUnit3ErrorTranslator.INSTANCE); } } jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/junit3/MockObjectTestCase.java000066400000000000000000000104771347002534600332770ustar00rootroot00000000000000package org.jmock.integration.junit3; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.States; import org.jmock.api.Imposteriser; import org.jmock.api.MockObjectNamingScheme; import org.jmock.auto.internal.Mockomatic; import org.jmock.internal.ExpectationBuilder; /** * A {@link junit.framework.TestCase} that supports testing with mock objects. * It wraps a {@link org.jmock.Mockery} and automatically asserts that * all expectations have been met at the end of the test before * {@link junit.framework.TestCase#tearDown()} is called. * * @author npryce */ public abstract class MockObjectTestCase extends VerifyingTestCase { private final Mockery context = new Mockery(); public MockObjectTestCase() { super(); initialise(); } public MockObjectTestCase(String name) { super(name); initialise(); } private void initialise() { context.setExpectationErrorTranslator(JUnit3ErrorTranslator.INSTANCE); addVerifier(new Runnable() { public void run() { context.assertIsSatisfied(); } }); Mockomatic mockomatic = new Mockomatic(context); mockomatic.fillIn(this); } public Mockery context() { return context; } /** * Sets the result returned for the given type when no return value has been explicitly * specified in the expectation. * * @param type * The type for which to return result. * @param result * The value to return when a method of return type type * is invoked for which an explicit return value has has not been specified. */ public void setDefaultResultForType(Class type, Object result) { context.setDefaultResultForType(type, result); } /** * Changes the imposteriser used to adapt mock objects to the mocked type. * * The default imposteriser allows a test to mock interfaces but not * classes, so you'll have to plug a different imposteriser into the * Mockery if you want to mock classes. */ public void setImposteriser(Imposteriser imposteriser) { context.setImposteriser(imposteriser); } /** * Changes the naming scheme used to generate names for mock objects that * have not been explicitly named in the test. * * The default naming scheme names mock objects by lower-casing the first * letter of the class name, so a mock object of type BananaSplit will be * called "bananaSplit" if it is not explicitly named in the test. */ public void setNamingScheme(MockObjectNamingScheme namingScheme) { context.setNamingScheme(namingScheme); } /** * Specify expectations upon the mock objects in the test. * */ public void checking(ExpectationBuilder expectations) { context.checking(expectations); } /** * Create a mock object of type T with an explicit name. * * @param typeToMock * The type to be mocked * @param name * The name of the new mock object that is used to identify the mock object * in error messages * @return * A new mock object of type */ public T mock(Class typeToMock, String name) { return context.mock(typeToMock, name); } /** * Create a mock object of type T with a name derived from its type. * * @param typeToMock * The type to be mocked * @return * A new mock object of type */ public T mock(Class typeToMock) { return context.mock(typeToMock); } /** * Returns a new sequence that is used to constrain the order in which * expectations can occur. * * @param name * The name of the sequence. * @return * A new sequence with the given name. */ public Sequence sequence(String name) { return context.sequence(name); } /** * Returns a new state machine that is used to constrain the order in which * expectations can occur. * * @param name * The name of the state machine. * @return * A new state machine with the given name. */ public States states(String name) { return context.states(name); } } jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/junit3/VerifyingTestCase.java000066400000000000000000000027511347002534600332150ustar00rootroot00000000000000/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.integration.junit3; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; /** * A {@link junit.framework.TestCase} that verifies postconditions after the * test has run and before the fixture has been torn down. * * @since 1.0 */ public abstract class VerifyingTestCase extends TestCase { private List verifiers = new ArrayList(); public VerifyingTestCase() { super(); } public VerifyingTestCase( String name ) { super(name); } /* This is virtually a copy/paste of the same invokedMethod in the TestCase class to allow * overriding of runTest in the normal manner. * * @see junit.framework.TestCase#runBare() */ @Override public void runBare() throws Throwable { Throwable exception= null; setUp(); try { runTest(); verify(); } catch (Throwable running) { exception= running; } finally { try { tearDown(); } catch (Throwable tearingDown) { if (exception == null) exception= tearingDown; } } if (exception != null) throw exception; } public void verify() { for (Runnable verifier : verifiers) { verifier.run(); } } public void addVerifier(Runnable verifier) { verifiers.add(verifier); } } jmock-library-2.12.0/jmock-junit3/src/main/java/org/jmock/integration/junit3/package.html000066400000000000000000000005021347002534600312250ustar00rootroot00000000000000

Integrates jMock with JUnit 3.

To write a mock object test in JUnit 3, extend {@link org.jmock.integration.junit3.MockObjectTestCase}. Any mock objects used in the test will be verified after the test has run and before the fixture is torn down. jmock-library-2.12.0/jmock-junit3/src/test/000077500000000000000000000000001347002534600204305ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/000077500000000000000000000000001347002534600213515ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/000077500000000000000000000000001347002534600221405ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/000077500000000000000000000000001347002534600232435ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/test/000077500000000000000000000000001347002534600242225ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/test/unit/000077500000000000000000000000001347002534600252015ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/test/unit/integration/000077500000000000000000000000001347002534600275245ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/test/unit/integration/junit3/000077500000000000000000000000001347002534600307405ustar00rootroot00000000000000MockObjectTestCaseTests.java000066400000000000000000000004501347002534600362220ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/test/unit/integration/junit3package org.jmock.test.unit.integration.junit3; import org.jmock.integration.junit3.MockObjectTestCase; public class MockObjectTestCaseTests extends MockObjectTestCase { public void testDoesNotNeedToHaveExpectationsSpecified() { // no expectations: the test should not fail } } VerifyingTestCaseTests.java000066400000000000000000000054411347002534600361510ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/org/jmock/test/unit/integration/junit3/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.integration.junit3; import junit.framework.TestCase; import org.jmock.integration.junit3.VerifyingTestCase; import testdata.jmock.integration.junit3.FailingExampleTestCase; public class VerifyingTestCaseTests extends TestCase { public static class ExampleTestCase extends VerifyingTestCase { public ExampleTestCase() { setName("testMethod"); } public void testMethod() { // Success! } } public void testCanBeConstructedWithAName() { String name = "NAME"; VerifyingTestCase testCase = new VerifyingTestCase(name) { }; assertEquals("name", name, testCase.getName()); } private boolean verifierWasRun = false; public void testRunsVerifiersAfterTest() throws Throwable { ExampleTestCase testCase = new ExampleTestCase(); testCase.addVerifier(new Runnable() { public void run() { verifierWasRun = true; } }); testCase.runBare(); assertTrue(verifierWasRun); } public void testOverridingRunTestDoesNotAffectVerification() throws Throwable { ExampleTestCase testCase = new ExampleTestCase() { @Override public void runTest() { } }; testCase.addVerifier(new Runnable() { public void run() { verifierWasRun = true; } }); testCase.runBare(); assertTrue(verifierWasRun); } public void testOverridingSetUpAndTearDownDoesNotAffectVerification() throws Throwable { ExampleTestCase testCase = new ExampleTestCase() { @Override public void setUp() { } @Override public void tearDown() { } }; testCase.addVerifier(new Runnable() { public void run() { verifierWasRun = true; } }); testCase.runBare(); assertTrue(verifierWasRun); } public void testThrowsTestExceptionRatherThanTearDownException() throws Throwable { try { new FailingExampleTestCase("testThrowsExpectedException").runBare(); fail("should have thrown exception"); } catch (Exception actual) { assertSame(FailingExampleTestCase.testException, actual); } } public void testThrowsTearDownExceptionWhenNoTestException() throws Throwable { try { new FailingExampleTestCase("testDoesNotThrowException").runBare(); fail("should have thrown exception"); } catch (Exception actual) { assertSame(FailingExampleTestCase.tearDownException, actual); } } } jmock-library-2.12.0/jmock-junit3/src/test/java/testdata/000077500000000000000000000000001347002534600231625ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/testdata/jmock/000077500000000000000000000000001347002534600242655ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/testdata/jmock/integration/000077500000000000000000000000001347002534600266105ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/testdata/jmock/integration/junit3/000077500000000000000000000000001347002534600300245ustar00rootroot00000000000000FailingExampleTestCase.java000066400000000000000000000013531347002534600351330ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit3/src/test/java/testdata/jmock/integration/junit3package testdata.jmock.integration.junit3; import org.jmock.integration.junit3.VerifyingTestCase; /** * @author Steve Freeman 2012 http://www.jmock.org */ public class FailingExampleTestCase extends VerifyingTestCase { public static final Exception tearDownException = new Exception("tear down"); public static final Exception testException = new Exception("test"); public FailingExampleTestCase(String testName) { super(testName); } @Override public void tearDown() throws Exception { throw tearDownException; } public void testDoesNotThrowException() throws Exception { // no op } public void testThrowsExpectedException() throws Exception { throw testException; } } jmock-library-2.12.0/jmock-junit4/000077500000000000000000000000001347002534600166635ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/pom.xml000066400000000000000000000040561347002534600202050ustar00rootroot00000000000000 4.0.0 jmock-junit4 jmock-junit4 org.jmock jmock-parent 2.12.0 UTF-8 junit junit compile org.jmock jmock ${project.version} compile org.jmock jmock-legacy ${project.version} runtime org.jmock jmock-imposters ${project.version} runtime org.jmock jmock ${project.version} test-jar test org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-junit4/src/000077500000000000000000000000001347002534600174525ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/000077500000000000000000000000001347002534600203765ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/java/000077500000000000000000000000001347002534600213175ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/java/org/000077500000000000000000000000001347002534600221065ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/000077500000000000000000000000001347002534600232115ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/integration/000077500000000000000000000000001347002534600255345ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/integration/junit4/000077500000000000000000000000001347002534600267515ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/integration/junit4/JMock.java000066400000000000000000000060071347002534600306220ustar00rootroot00000000000000package org.jmock.integration.junit4; import org.jmock.Mockery; import org.jmock.auto.internal.Mockomatic; import org.jmock.internal.AllDeclaredFields; import org.junit.runner.Runner; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import java.lang.reflect.Field; /** * A test {@link Runner} that asserts that all expectations have been met after * the test has finished and before the fixture is torn down. * @deprecated For JUnit 4 use {@link JUnitRuleMockery} * @author nat steve.freeman * */ @Deprecated public class JMock extends BlockJUnit4ClassRunner { private Field mockeryField; public JMock(Class testClass) throws InitializationError { super(testClass); mockeryField = findMockeryField(testClass); mockeryField.setAccessible(true); } @Override protected Object createTest() throws Exception { Object test = super.createTest(); Mockomatic mockomatic = new Mockomatic(mockeryOf(test)); mockomatic.fillIn(test); return test; } @Override @Deprecated protected Statement possiblyExpectingExceptions(FrameworkMethod method, Object test, Statement next) { return verify(method, test, super.possiblyExpectingExceptions(method, test, next)); } protected Statement verify( @SuppressWarnings("unused") FrameworkMethod method, final Object test, final Statement next) { return new Statement() { @Override public void evaluate() throws Throwable { next.evaluate(); assertMockeryIsSatisfied(test); } }; } protected void assertMockeryIsSatisfied(Object test) { mockeryOf(test).assertIsSatisfied(); } protected Mockery mockeryOf(Object test) { try { Mockery mockery = (Mockery)mockeryField.get(test); if (mockery == null) { throw new IllegalStateException("Mockery named '" + mockeryField.getName() + "' is null"); } return mockery; } catch (IllegalAccessException e) { throw new IllegalStateException("cannot get value of field " + mockeryField.getName(), e); } } static Field findMockeryField(Class testClass) throws InitializationError { Field mockeryField = null; for (Field field : AllDeclaredFields.in(testClass)) { if (Mockery.class.isAssignableFrom(field.getType())) { if (mockeryField != null) { throw new InitializationError("more than one Mockery found in test class " + testClass); } mockeryField = field; } } if (mockeryField == null) { throw new InitializationError("no Mockery found in test class " + testClass); } return mockeryField; } } jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/integration/junit4/JUnit4Mockery.java000066400000000000000000000005631347002534600322670ustar00rootroot00000000000000package org.jmock.integration.junit4; import org.jmock.Mockery; import org.jmock.lib.AssertionErrorTranslator; /** * A {@link Mockery} that reports expectation errors as JUnit 4 test failures. * @author nat */ public class JUnit4Mockery extends Mockery { public JUnit4Mockery() { setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE); } } jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/integration/junit4/JUnitRuleMockery.java000066400000000000000000000053611347002534600330340ustar00rootroot00000000000000package org.jmock.integration.junit4; import org.jmock.auto.internal.Mockomatic; import org.jmock.internal.AllDeclaredFields; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import java.lang.reflect.Field; import java.util.List; import static org.junit.Assert.fail; /** * A JUnitRuleMockery is a JUnit Rule that manages JMock expectations * and allowances, and asserts that expectations have been met after each test * has finished. To use it, add a field to the test class (note that you don't * have to specify @RunWith(JMock.class) any more). For example, * *

public class ATestWithSatisfiedExpectations {
 *  @Rule public final JUnitRuleMockery context = new JUnitRuleMockery();
 *  private final Runnable runnable = context.mock(Runnable.class);
 *     
 *  @Test
 *  public void doesSatisfyExpectations() {
 *    context.checking(new Expectations() {{
 *      oneOf (runnable).run();
 *    }});
 *          
 *    runnable.run();
 *  }
 *}
* * Note that the Rule field must be declared public and as a JUnitRuleMockery * (not a Mockery) for JUnit to recognise it, as it's checked statically. * @author smgf */ public class JUnitRuleMockery extends JUnit4Mockery implements MethodRule { private final Mockomatic mockomatic = new Mockomatic(this); public Statement apply(final Statement base, FrameworkMethod method, final Object target) { return new Statement() { @Override public void evaluate() throws Throwable { prepare(target); base.evaluate(); assertIsSatisfied(); } private void prepare(final Object target) { List allFields = AllDeclaredFields.in(target.getClass()); assertOnlyOneJMockContextIn(allFields); fillInAutoMocks(target, allFields); } private void assertOnlyOneJMockContextIn(List allFields) { Field contextField = null; for (Field field : allFields) { if (JUnitRuleMockery.class.isAssignableFrom(field.getType())) { if (null != contextField) { fail("Test class should only have one JUnitRuleMockery field, found " + contextField.getName() + " and " + field.getName()); } contextField = field; } } } private void fillInAutoMocks(final Object target, List allFields) { mockomatic.fillIn(target, allFields); } }; } } jmock-library-2.12.0/jmock-junit4/src/main/java/org/jmock/integration/junit4/package.html000066400000000000000000000027131347002534600312350ustar00rootroot00000000000000

Integrates jMock with JUnit 4.

To write a mock object test in JUnit 4, declare a field of type Mockery that holds a JUnit4Mockery and annotate your test class with @RunWith(JMock.class), as shown below. The Mockery will be verified after the test has run and before the fixture is torn down.

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.junit.Test;
import org.junit.runner.RunWith;

...

@RunWith(JMock.class)
public class ExampleJUnit4MockObjectTest {
	Mockery context = new JUnit4Mockery();
	
	...	
	
	@Test public void
	dispatchesEventToSessionsOtherThanThenSender() {
		...
		
		context.checking(new Expectations() {{
			...
		}});
		
		...
	}
}

Alternatively, from JUnit 4.7, you can use JMockContext which implements a JUnit Rule to manage expectations and allowances, and to assert the expectations after each test has run.

public class ATestWithSatisfiedExpectations {
  \@Rule public final JMockContext context = new JMockContext();
  private final Runnable runnable = context.mock(Runnable.class);
     
  \@Test
  public void doesSatisfyExpectations() {
    context.checking(new Expectations() {{
      oneOf (runnable).run();
    }});
          
    runnable.run();
  }
}
jmock-library-2.12.0/jmock-junit4/src/test/000077500000000000000000000000001347002534600204315ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/000077500000000000000000000000001347002534600213525ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/000077500000000000000000000000001347002534600221415ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/000077500000000000000000000000001347002534600232445ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/000077500000000000000000000000001347002534600242235ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/acceptance/000077500000000000000000000000001347002534600263115ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/acceptance/junit4/000077500000000000000000000000001347002534600275265ustar00rootroot00000000000000FailureRecordingRunListener.java000066400000000000000000000032151347002534600357320ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/acceptance/junit4package org.jmock.test.acceptance.junit4; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.runner.Request; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; class FailureRecordingRunListener extends RunListener { public Failure failure = null; @Override public void testFailure(Failure failure) throws Exception { this.failure = failure; } public void assertTestSucceeded() { if (failure != null) { fail("test should have passed but reported failure: " + failure.getMessage()); } } public void assertTestFailedWith(Class exceptionType) { assertNotNull("test should have failed", failure); assertTrue("should have failed with " + exceptionType.getName() + " but threw " + failure.getException(), exceptionType.isInstance(failure.getException())); } public void assertTestFailedWithInitializationError() { assertNotNull("test should have failed", failure); assertTrue("should have failed with initialization error, but failure was " + failure.toString(), failure.getDescription().toString().contains("initializationError")); } public void runTestIn(Class testClass) { Runner runner = Request.aClass(testClass).getRunner(); RunNotifier notifier = new RunNotifier(); notifier.addListener(this); runner.run(notifier); } }JUnit4TestRunnerTests.java000066400000000000000000000046001347002534600345040ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/acceptance/junit4package org.jmock.test.acceptance.junit4; import junit.framework.TestCase; import testdata.jmock.acceptance.junit4.*; public class JUnit4TestRunnerTests extends TestCase { FailureRecordingRunListener listener = new FailureRecordingRunListener(); public void testTheJUnit4TestRunnerReportsPassingTestsAsSuccessful() { listener.runTestIn(JUnit4TestThatDoesSatisfyExpectations.class); listener.assertTestSucceeded(); } public void testTheJUnit4TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() { listener.runTestIn(JUnit4TestThatDoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } public void testTheJUnit4TestRunnerLooksForTheMockeryInBaseClasses() { listener.runTestIn(DerivedJUnit4TestThatDoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } public void testTheJUnit4TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() { listener.runTestIn(JUnit4TestThatDoesNotCreateAMockery.class); listener.assertTestFailedWith(IllegalStateException.class); } // See issue JMOCK-156 public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() { listener.runTestIn(JUnit4TestThatThrowsExpectedException.class); listener.assertTestFailedWith(AssertionError.class); } // See issue JMOCK-219 public void testTheJUnit4TestRunnerReportsIfNoMockeryIsFound() { listener.runTestIn(JUnit4TestThatCreatesNoMockery.class); listener.assertTestFailedWithInitializationError(); } // See issue JMOCK-219 public void testTheJUnit4TestRunnerReportsIfMoreThanOneMockeryIsFound() { listener.runTestIn(JUnit4TestThatCreatesTwoMockeries.class); listener.assertTestFailedWithInitializationError(); } public void testDetectsNonPublicBeforeMethodsCorrectly() { listener.runTestIn(JUnit4TestWithNonPublicBeforeMethod.class); listener.assertTestFailedWith(Throwable.class); assertEquals("should have detected non-public before method", "Method before() should be public", listener.failure.getMessage()); } public void testAutoInstantiatesMocks() { listener.runTestIn(JUnit4TestThatAutoInstantiatesMocks.class); listener.assertTestSucceeded(); } } JUnit4WithRulesTestRunnerTests.java000066400000000000000000000031621347002534600363550ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/acceptance/junit4package org.jmock.test.acceptance.junit4; import junit.framework.TestCase; import testdata.jmock.acceptance.junit4.JUnit4WithRulesExamples; public class JUnit4WithRulesTestRunnerTests extends TestCase { FailureRecordingRunListener listener = new FailureRecordingRunListener(); public void testTheJUnit4TestRunnerReportsPassingTestsAsSuccessful() { listener.runTestIn(JUnit4WithRulesExamples.SatisfiesExpectations.class); listener.assertTestSucceeded(); } public void testTheJUnit4TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() { listener.runTestIn(JUnit4WithRulesExamples.DoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } public void testTheJUnit4TestRunnerLooksForTheMockeryInBaseClasses() { listener.runTestIn(JUnit4WithRulesExamples.DerivedAndDoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } // See issue JMOCK-156 public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() { listener.runTestIn(JUnit4WithRulesExamples.ThrowsExpectedException.class); listener.assertTestFailedWith(AssertionError.class); } public void testFailsWhenMoreThanOneJMockContextField() { listener.runTestIn(JUnit4WithRulesExamples.CreatesTwoMockeries.class); listener.assertTestFailedWith(AssertionError.class); } public void testAutoInstantiatesMocks() { listener.runTestIn(JUnit4WithRulesExamples.AutoInstantiatesMocks.class); listener.assertTestSucceeded(); } } jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/unit/000077500000000000000000000000001347002534600252025ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/unit/lib/000077500000000000000000000000001347002534600257505ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/unit/lib/concurrent/000077500000000000000000000000001347002534600301325ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/unit/lib/concurrent/internal/000077500000000000000000000000001347002534600317465ustar00rootroot00000000000000SynchroniserTests.java000066400000000000000000000126671347002534600362570ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/org/jmock/test/unit/lib/concurrent/internalpackage org.jmock.test.unit.lib.concurrent.internal; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.util.concurrent.atomic.AtomicInteger; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.States; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.concurrent.Blitzer; import org.jmock.lib.concurrent.Synchroniser; import org.junit.After; import org.junit.Test; public class SynchroniserTests { public interface Events { void action(); void finished(); } Synchroniser synchroniser = new Synchroniser(); // Not a rule, to allow checking the mockery is *not* satisfied Mockery mockery = new JUnit4Mockery() {{ setThreadingPolicy(synchroniser); }}; Blitzer blitzer = new Blitzer(16, 4); Events mockObject = mockery.mock(Events.class, "mockObject"); @Test(timeout=250) public void allowsMultipleThreadsToCallMockObjects() throws InterruptedException { mockery.checking(new Expectations() {{ exactly(blitzer.totalActionCount()).of(mockObject).action(); }}); blitzer.blitz(new Runnable() { public void run() { mockObject.action(); } }); mockery.assertIsSatisfied(); } @Test(timeout=250) public void canWaitForAStateMachineToEnterAGivenState() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(blitzer.totalActionCount()); final States threads = mockery.states("threads"); mockery.checking(new Expectations() {{ exactly(blitzer.totalActionCount()).of(mockObject).action(); when(threads.isNot("finished")); oneOf(mockObject).finished(); then(threads.is("finished")); }}); blitzer.blitz(new Runnable() { public void run() { mockObject.action(); if (counter.decrementAndGet() == 0) { mockObject.finished(); } } }); synchroniser.waitUntil(threads.is("finished")); mockery.assertIsSatisfied(); } @Test(timeout=250) public void canWaitForAStateMachineToEnterAGivenStateWithinSomeTimeout() throws InterruptedException { final States threads = mockery.states("threads"); mockery.checking(new Expectations() {{ exactly(blitzer.totalActionCount()).of(mockObject).action(); when(threads.isNot("finished")); oneOf(mockObject).finished(); then(threads.is("finished")); }}); blitzer.blitz(new Runnable() { AtomicInteger counter = new AtomicInteger(blitzer.totalActionCount()); public void run() { mockObject.action(); if (counter.decrementAndGet() == 0) { mockObject.finished(); } } }); synchroniser.waitUntil(threads.is("finished"), 100); mockery.assertIsSatisfied(); } @Test(timeout=250) public void failsTheTestIfStateMachineDoesNotEnterExpectedStateWithinTimeout() throws InterruptedException { States threads = mockery.states("threads"); try { synchroniser.waitUntil(threads.is("finished"), 100); } catch (AssertionError e) { return; } fail("should have thrown AssertionError"); } @Test public void throwsExpectationErrorIfExpectationFailsWhileWaitingForStateMachine() throws InterruptedException { final States threads = mockery.states("threads"); // This will cause an expectation error, and nothing will make // the "threads" state machine transition to "finished" blitzer.blitz(new Runnable() { public void run() { mockObject.action(); } }); try { synchroniser.waitUntil(threads.is("finished"), 100); fail("should have thrown AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("action()")); } } @Test public void throwsExpectationErrorIfExpectationFailsWhileWaitingForStateMachineEvenIfWaitSucceeds() throws InterruptedException { final States threads = mockery.states("threads"); mockery.checking(new Expectations() {{ oneOf(mockObject).finished(); then(threads.is("finished")); }}); blitzer.blitz(new Runnable() { AtomicInteger counter = new AtomicInteger(blitzer.totalActionCount()); public void run() { if (counter.decrementAndGet() == 0) { mockObject.finished(); } else { mockObject.action(); } } }); try { synchroniser.waitUntil(threads.is("finished"), 100); fail("should have thrown AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("action()")); } } @After public void cleanUp() { blitzer.shutdown(); } } jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/000077500000000000000000000000001347002534600231635ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/000077500000000000000000000000001347002534600242665ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/000077500000000000000000000000001347002534600263545ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4/000077500000000000000000000000001347002534600275715ustar00rootroot00000000000000BaseClassWithMockery.java000066400000000000000000000004661347002534600344110ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.runner.RunWith; @RunWith(JMock.class) public class BaseClassWithMockery { protected Mockery context = new JUnit4Mockery(); } DerivedJUnit4TestThatDoesNotSatisfyExpectations.java000066400000000000000000000007631347002534600417120ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Expectations; import org.junit.Test; public class DerivedJUnit4TestThatDoesNotSatisfyExpectations extends BaseClassWithMockery { private Runnable runnable = context.mock(Runnable.class); @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); // Return without satisfying the expectation for runnable.run() } } JUnit4TestThatAutoInstantiatesMocks.java000066400000000000000000000012021347002534600373630ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import org.jmock.Sequence; import org.jmock.States; import org.jmock.auto.Auto; import org.jmock.auto.Mock; import org.junit.Test; public class JUnit4TestThatAutoInstantiatesMocks extends BaseClassWithMockery { @Mock Runnable runnable; @Auto States states; @Auto Sequence sequence; @Test public void fieldsHaveBeenAutoInstantiated() { assertThat(runnable, notNullValue()); assertThat(states, notNullValue()); assertThat(sequence, notNullValue()); } } JUnit4TestThatCreatesNoMockery.java000066400000000000000000000004201347002534600363050ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class JUnit4TestThatCreatesNoMockery { @Test public void happy() { // a-ok! } } JUnit4TestThatCreatesTwoMockeries.java000066400000000000000000000006761347002534600370270ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class JUnit4TestThatCreatesTwoMockeries { Mockery contextA = new JUnit4Mockery(); Mockery contextB = new JUnit4Mockery(); @Test public void happy() { // a-ok! } } JUnit4TestThatDoesNotCreateAMockery.java000066400000000000000000000005201347002534600372230ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class JUnit4TestThatDoesNotCreateAMockery { Mockery context = null; @Test public void happy() { // a-ok! } } JUnit4TestThatDoesNotSatisfyExpectations.java000066400000000000000000000012611347002534600404010ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class JUnit4TestThatDoesNotSatisfyExpectations { private Mockery context = new JUnit4Mockery(); private Runnable runnable = context.mock(Runnable.class); @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); // Return without satisfying the expectation for runnable.run() } } JUnit4TestThatDoesSatisfyExpectations.java000066400000000000000000000011731347002534600377220ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class JUnit4TestThatDoesSatisfyExpectations { private Mockery context = new JUnit4Mockery(); private Runnable runnable = context.mock(Runnable.class); @Test public void doesSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); runnable.run(); } } JUnit4TestThatThrowsExpectedException.java000066400000000000000000000020621347002534600377230ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class JUnit4TestThatThrowsExpectedException { private Mockery context = new JUnit4Mockery(); private WithException withException = context.mock(WithException.class); @Test(expected=CheckedException.class) public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException { context.checking(new Expectations() {{ oneOf (withException).anotherMethod(); oneOf (withException).throwingMethod(); will(throwException(new CheckedException())); }}); withException.throwingMethod(); } public static class CheckedException extends Exception { } public interface WithException { void throwingMethod() throws CheckedException; void anotherMethod(); } } JUnit4TestWithNonPublicBeforeMethod.java000066400000000000000000000011631347002534600372650ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertTrue; @RunWith(JMock.class) public class JUnit4TestWithNonPublicBeforeMethod { @SuppressWarnings("unused") private Mockery context = new Mockery(); public boolean beforeWasCalled = false; @Before void before() { beforeWasCalled = true; } @Test public void beforeShouldBeCalled() { assertTrue("before was called", beforeWasCalled); } } JUnit4WithRulesExamples.java000066400000000000000000000067401347002534600350470ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit4/src/test/java/testdata/jmock/acceptance/junit4package testdata.jmock.acceptance.junit4; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.States; import org.jmock.auto.Auto; import org.jmock.auto.Mock; import org.jmock.integration.junit4.JUnitRuleMockery; import org.junit.Rule; import org.junit.Test; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; public class JUnit4WithRulesExamples { public static class SatisfiesExpectations { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); private final Runnable runnable = context.mock(Runnable.class); @Test public void doesSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); runnable.run(); } } public static class DoesNotSatisfyExpectations { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); private Runnable runnable = context.mock(Runnable.class); @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); // Return without satisfying the expectation for runnable.run() } } public static class DerivedAndDoesNotSatisfyExpectations extends BaseClassWithJMockContext { private Runnable runnable = context.mock(Runnable.class); @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); // Return without satisfying the expectation for runnable.run() } } public static class ThrowsExpectedException { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); private WithException withException = context.mock(WithException.class); @Test(expected=CheckedException.class) public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException { context.checking(new Expectations() {{ oneOf (withException).anotherMethod(); oneOf (withException).throwingMethod(); will(throwException(new CheckedException())); }}); withException.throwingMethod(); } public static class CheckedException extends Exception { } public interface WithException { void throwingMethod() throws CheckedException; void anotherMethod(); } } public static class CreatesTwoMockeries extends BaseClassWithJMockContext { @Rule public final JUnitRuleMockery otherContext = new JUnitRuleMockery(); @Test public void doesNothing() { // no op } } public static class AutoInstantiatesMocks extends BaseClassWithJMockContext { @Mock Runnable runnable; @Auto States states; @Auto Sequence sequence; @Test public void fieldsHaveBeenAutoInstantiated() { assertThat("runnable", runnable, notNullValue()); assertThat("states", states, notNullValue()); assertThat("sequence", sequence, notNullValue()); } } public static class BaseClassWithJMockContext { @Rule public final JUnitRuleMockery context = new JUnitRuleMockery(); } } jmock-library-2.12.0/jmock-junit5/000077500000000000000000000000001347002534600166645ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/pom.xml000066400000000000000000000046141347002534600202060ustar00rootroot00000000000000 4.0.0 jmock-junit5 org.jmock jmock-parent 2.12.0 UTF-8 org.junit.jupiter junit-jupiter-api compile org.junit.jupiter junit-jupiter-engine org.junit.jupiter junit-jupiter-params org.junit.platform junit-platform-launcher com.google.auto.service auto-service 1.0-rc1 provided org.jmock jmock ${project.version} compile org.jmock jmock-imposters ${project.version} runtime org.jmock jmock ${project.version} test-jar test org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-junit5/src/000077500000000000000000000000001347002534600174535ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/main/000077500000000000000000000000001347002534600203775ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/main/java/000077500000000000000000000000001347002534600213205ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/main/java/org/000077500000000000000000000000001347002534600221075ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/main/java/org/jmock/000077500000000000000000000000001347002534600232125ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/main/java/org/jmock/junit5/000077500000000000000000000000001347002534600244305ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/main/java/org/jmock/junit5/JUnit5Mockery.java000066400000000000000000000076751347002534600277620ustar00rootroot00000000000000package org.jmock.junit5; import java.lang.reflect.Field; import java.util.List; import org.jmock.Mockery; import org.jmock.auto.internal.Mockomatic; import org.jmock.internal.AllDeclaredFields; import org.jmock.lib.AssertionErrorTranslator; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionConfigurationException; import org.junit.jupiter.api.extension.ExtensionContext; import com.google.auto.service.AutoService; /** * A JUnit5Mockery is a JUnit Extension that manages JMock * expectations and allowances, and asserts that expectations have been met * after each test has finished. To use it, add a (non-private) field to the test class * For example, * *
 * public class ATestWithSatisfiedExpectations {
 *     @RegisterExtension
 *     final JUnitRuleMockery context = new JUnitRuleMockery();
 *     
 *     @Mock
 *     private final Runnable runnable;
 * 
 *     @Test
 *     public void doesSatisfyExpectations() {
 *         context.checking(new Expectations() {
 *             {
 *                 oneOf(runnable).run();
 *             }
 *         });
 * 
 *         runnable.run();
 *     }
 * }
 * 
* * Note that the Rule field must be declared public and as a * JUnitRuleMockery (not a Mockery) for JUnit to * recognise it, as it's checked statically. * * @author olibye */ @AutoService(Extension.class) public class JUnit5Mockery extends Mockery implements Extension, BeforeEachCallback, AfterEachCallback { private final Mockomatic mockomatic = new Mockomatic(this); public JUnit5Mockery() { setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE); } @Override public void beforeEach(ExtensionContext context) throws Exception { if (context.getTestClass().isPresent()) { Class testCaseClass = context.getTestClass().get(); List allFields = AllDeclaredFields.in(testCaseClass); fillInAutoMocks(context.getRequiredTestInstance(), allFields); checkMockery(context, testCaseClass); } } @Override public void afterEach(ExtensionContext context) throws Exception { assertIsSatisfied(); } private void fillInAutoMocks(final Object target, List allFields) { mockomatic.fillIn(target, allFields); } private static void checkMockery(ExtensionContext context, Class testCaseClass) { Field mockeryField = findMockeryField(testCaseClass, context); try { // private extension fields are not called // field will at least be default scope if we're called. mockeryField.setAccessible(true); if(mockeryField.get(context.getRequiredTestInstance()) == null) { throw new IllegalStateException("JUnit5Mockery field should not be null"); } } catch (IllegalArgumentException e) { throw new ExtensionConfigurationException("Could not check the mockery", e); } catch (IllegalAccessException e) { throw new ExtensionConfigurationException("Could not check the mockery", e); } } private static Field findMockeryField(Class testClass, ExtensionContext context) { Field mockeryField = null; for (Field field : AllDeclaredFields.in(testClass)) { if (Mockery.class.isAssignableFrom(field.getType())) { if (mockeryField != null) { throw new ExtensionConfigurationException("more than one Mockery found in test class " + testClass); } mockeryField = field; } } if (mockeryField == null) { throw new ExtensionConfigurationException("no Mockery found in test class " + testClass); } return mockeryField; } } jmock-library-2.12.0/jmock-junit5/src/main/java/org/jmock/junit5/package.html000066400000000000000000000014271347002534600267150ustar00rootroot00000000000000

Integrates jMock with JUnit 5.

To write a mock object test in JUnit 5, declare a non-private field of type JUnit5Mockery that holds a JUnit5Mockery and annotate the field with @RegisterExtension, as shown below. The Mockery will be verified after the test has run and before the fixture is torn down.

public class JUnit5TestThatDoesSatisfyExpectations {
    
    \@RegisterExtension
    JUnit5Mockery context = new JUnit5Mockery();
    
    \@Mock
    private Runnable runnable;
    
    \@Test
    public void doesSatisfyExpectations() {
        context.checking(new Expectations() {{
            oneOf (runnable).run();
        }});
        
        runnable.run();
    }
}
jmock-library-2.12.0/jmock-junit5/src/test/000077500000000000000000000000001347002534600204325ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/000077500000000000000000000000001347002534600213535ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/000077500000000000000000000000001347002534600221425ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/000077500000000000000000000000001347002534600232455ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/000077500000000000000000000000001347002534600244635ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/acceptance/000077500000000000000000000000001347002534600265515ustar00rootroot00000000000000FailureRecordingTestExecutionListener.java000066400000000000000000000054671347002534600370270ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/acceptancepackage org.jmock.junit5.acceptance; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import java.util.function.Predicate; import org.junit.jupiter.api.extension.ExtensionConfigurationException; import org.junit.platform.engine.TestExecutionResult; import org.junit.platform.engine.TestExecutionResult.Status; import org.junit.platform.launcher.Launcher; import org.junit.platform.launcher.TestExecutionListener; import org.junit.platform.launcher.TestIdentifier; import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder; import org.junit.platform.launcher.core.LauncherFactory; import com.google.auto.service.AutoService; @AutoService(TestExecutionListener.class) public class FailureRecordingTestExecutionListener implements TestExecutionListener { TestExecutionResult testExecutionResult; @Override public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { if (testIdentifier.isTest() /* ignore non test containers */) { this.testExecutionResult = testExecutionResult; } } public void assertTestSucceeded() { if (testExecutionResult.getStatus().equals(Status.FAILED)) { fail("test should have passed but reported failure: " + testExecutionResult.toString()); } } public void assertTestFailedWith(Class exceptionType) { assertEquals(Status.FAILED, testExecutionResult.getStatus(), "test should have failed"); Throwable cause = testExecutionResult.getThrowable().get(); assertTrue(exceptionType.isInstance(cause), "should have failed with " + exceptionType.getName() + " but threw " + cause); } public void assertTestFailedWithInitializationError() { assertEquals(Status.FAILED, testExecutionResult.getStatus(), "test should have failed"); assertTrue( testExecutionResult.getThrowable() .filter(new Predicate() { @Override public boolean test(Throwable t) { return t.getClass().equals(ExtensionConfigurationException.class); } }) .isPresent(), testExecutionResult.toString()); } public void runTestIn(Class testClass) { Launcher launcher = LauncherFactory.create(); launcher.registerTestExecutionListeners(this); launcher.execute(LauncherDiscoveryRequestBuilder.request() .selectors(selectClass(testClass)) .build()); } }JUnit5TestRunnerTests.java000066400000000000000000000055551347002534600335420ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/acceptancepackage org.jmock.junit5.acceptance; import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException; import org.junit.jupiter.api.Test; /** * Wrap, running "testdata" testcases. Some of which are supposed to fail * @author oliverbye * */ public class JUnit5TestRunnerTests { FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener(); @Test public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() { listener.runTestIn(JUnit5TestThatDoesSatisfyExpectations.class); listener.assertTestSucceeded(); } @Test public void testTheJUnit5TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() { listener.runTestIn(JUnit5TestThatDoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } @Test public void testTheJUnit5TestRunnerLooksForTheMockeryInBaseClasses() { listener.runTestIn(DerivedJUnit5TestThatDoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } @Test public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() { listener.runTestIn(JUnit5TestThatDoesNotCreateAMockery.class); listener.assertTestFailedWith(org.junit.platform.commons.util.PreconditionViolationException.class); } // See issue JMOCK-156 @Test public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() { listener.runTestIn(JUnit5TestThatThrowsExpectedException.class); listener.assertTestFailedWith(AssertionError.class); } // See issue JMOCK-219 @Test public void testTheJUnit5TestRunnerReportsIfNoMockeryIsFound() { listener.runTestIn(JUnit5TestThatCreatesNoMockery.class); listener.assertTestFailedWithInitializationError(); } // See issue JMOCK-219 @Test public void testTheJUnit4TestRunnerReportsIfMoreThanOneMockeryIsFound() { listener.runTestIn(JUnit5TestThatCreatesTwoMockeries.class); listener.assertTestFailedWithInitializationError(); } @Test public void testAutoInstantiatesMocks() { listener.runTestIn(JUnit5TestThatAutoInstantiatesMocks.class); listener.assertTestSucceeded(); } } JUnit5WithRulesTestRunnerTests.java000066400000000000000000000034131347002534600354000ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/acceptancepackage org.jmock.junit5.acceptance; import org.jmock.junit5.testdata.jmock.acceptance.JUnit5WithRulesExamples; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionConfigurationException; public class JUnit5WithRulesTestRunnerTests { FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener(); @Test public void testTheJUnit4TestRunnerReportsPassingTestsAsSuccessful() { listener.runTestIn(JUnit5WithRulesExamples.SatisfiesExpectations.class); listener.assertTestSucceeded(); } @Test public void testTheJUnit4TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() { listener.runTestIn(JUnit5WithRulesExamples.DoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } @Test public void testTheJUnit4TestRunnerLooksForTheMockeryInBaseClasses() { listener.runTestIn(JUnit5WithRulesExamples.DerivedAndDoesNotSatisfyExpectations.class); listener.assertTestFailedWith(AssertionError.class); } // See issue JMOCK-156 @Test public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() { listener.runTestIn(JUnit5WithRulesExamples.ThrowsExpectedException.class); listener.assertTestFailedWith(AssertionError.class); } @Test public void testFailsWhenMoreThanOneJMockContextField() { listener.runTestIn(JUnit5WithRulesExamples.CreatesTwoMockeries.class); listener.assertTestFailedWith(ExtensionConfigurationException.class); } @Test public void testAutoInstantiatesMocks() { listener.runTestIn(JUnit5WithRulesExamples.AutoInstantiatesMocks.class); listener.assertTestSucceeded(); } } jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/extensions/000077500000000000000000000000001347002534600266625ustar00rootroot00000000000000ExpectationExtension.java000066400000000000000000000053131347002534600336300ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/extensionspackage org.jmock.junit5.extensions; import java.lang.annotation.Annotation; import java.util.Timer; import java.util.TimerTask; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; import com.google.auto.service.AutoService; @AutoService(Extension.class) public class ExpectationExtension implements TestExecutionExceptionHandler, BeforeEachCallback, AfterEachCallback { private Throwable thrown = null; private Timer timer = null; @Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { if (isAnnotated(context, ExpectationThrows.class)) { if (!readExpectedFromAnnotations(context).isAssignableFrom(throwable.getClass())) { throw throwable; } thrown = throwable; } } @Override public void beforeEach(ExtensionContext context) throws Exception { if (isAnnotated(context, ExpectationTimeout.class)) { timer = new Timer(true); timer.schedule(new TimerTask() { @Override public void run() { Assertions.fail("Timed out"); } }, readTimoutFromAnnotations(context)); } } @Override public void afterEach(ExtensionContext context) throws Exception { if (isAnnotated(context, ExpectationTimeout.class)) { timer.cancel(); timer = null; } if (isAnnotated(context, ExpectationThrows.class)) { Class expected = readExpectedFromAnnotations(context); if (thrown == null || !expected.isAssignableFrom(thrown.getClass())) { Assertions.fail("Was expecting the throwable:" + expected.getName()); } } } private boolean isAnnotated(ExtensionContext context, Class annotation) { return context.getRequiredTestMethod().isAnnotationPresent(annotation); } private Class readExpectedFromAnnotations(ExtensionContext context) { ExpectationThrows annotation = context.getRequiredTestMethod().getAnnotation(ExpectationThrows.class); return annotation.expected(); } private long readTimoutFromAnnotations(ExtensionContext context) { ExpectationTimeout annotation = context.getRequiredTestMethod().getAnnotation(ExpectationTimeout.class); return annotation.timeout(); } }jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/extensions/ExpectationThrows.java000066400000000000000000000011171347002534600332170ustar00rootroot00000000000000package org.jmock.junit5.extensions; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.Test; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Test public @interface ExpectationThrows { /** * Optionally specify expected, a Throwable, to cause a test method * to succeed if and only if an exception of the specified class is thrown by * the method. */ Class expected(); }jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/extensions/ExpectationTimeout.java000066400000000000000000000010401347002534600333520ustar00rootroot00000000000000package org.jmock.junit5.extensions; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import org.junit.jupiter.api.Test; /** * Aim to replace the old Junt4.@Test(timeout) functionality * * @author oliverbye */ @Retention(RetentionPolicy.RUNTIME) @Test public @interface ExpectationTimeout { /** * Optionally specify timeout in milliseconds to cause a test * method to fail if execution time exceeds timeout milliseconds. */ long timeout() default 0L; }jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/extensions/package-info.java000066400000000000000000000001201347002534600320420ustar00rootroot00000000000000/** * */ /** * @author oliverbye * */ package org.jmock.junit5.extensions;jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/000077500000000000000000000000001347002534600262745ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/000077500000000000000000000000001347002534600273775ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/000077500000000000000000000000001347002534600314655ustar00rootroot00000000000000BaseClassWithMockery.java000066400000000000000000000004051347002534600362760ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.extension.RegisterExtension; public class BaseClassWithMockery { @RegisterExtension JUnit5Mockery context = new JUnit5Mockery(); } DerivedJUnit5TestThatDoesNotSatisfyExpectations.java000066400000000000000000000010151347002534600435760ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.junit.jupiter.api.Test; public class DerivedJUnit5TestThatDoesNotSatisfyExpectations extends BaseClassWithMockery { @Mock Runnable runnable; @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); // Return without satisfying the expectation for runnable.run() } } JUnit5TestThatAutoInstantiatesMocks.java000066400000000000000000000012421347002534600412640ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import org.jmock.Sequence; import org.jmock.States; import org.jmock.auto.Auto; import org.jmock.auto.Mock; import org.junit.jupiter.api.Test; public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery { @Mock Runnable runnable; @Auto States states; @Auto Sequence sequence; @Test public void fieldsHaveBeenAutoInstantiated() { assertThat(runnable, notNullValue()); assertThat(states, notNullValue()); assertThat(sequence, notNullValue()); } } JUnit5TestThatCreatesNoMockery.java000066400000000000000000000004771347002534600402160ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(JUnit5Mockery.class) public class JUnit5TestThatCreatesNoMockery { @Test public void happy() { // a-ok! } } JUnit5TestThatCreatesTwoMockeries.java000066400000000000000000000007001347002534600407100ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class JUnit5TestThatCreatesTwoMockeries { @RegisterExtension JUnit5Mockery contextA = new JUnit5Mockery(); @RegisterExtension JUnit5Mockery contextB = new JUnit5Mockery(); @Test public void happy() { // a-ok! } } JUnit5TestThatDoesNotCreateAMockery.java000066400000000000000000000006741347002534600411320ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; @ExtendWith(JUnit5Mockery.class) public class JUnit5TestThatDoesNotCreateAMockery { @RegisterExtension JUnit5Mockery context = null; @Test public void happy() { // a-ok! } } JUnit5TestThatDoesNotSatisfyExpectations.java000066400000000000000000000012321347002534600422740ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class JUnit5TestThatDoesNotSatisfyExpectations { @RegisterExtension JUnit5Mockery context = new JUnit5Mockery(); @Mock private Runnable runnable; @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); // Return without satisfying the expectation for runnable.run() } } JUnit5TestThatDoesSatisfyExpectations.java000066400000000000000000000011411347002534600416120ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.Expectations; import org.jmock.auto.Mock; import org.jmock.junit5.JUnit5Mockery; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class JUnit5TestThatDoesSatisfyExpectations { @RegisterExtension JUnit5Mockery context = new JUnit5Mockery(); @Mock private Runnable runnable; @Test public void doesSatisfyExpectations() { context.checking(new Expectations() {{ oneOf (runnable).run(); }}); runnable.run(); } } JUnit5TestThatThrowsExpectedException.java000066400000000000000000000023571347002534600416270ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import org.jmock.Expectations; import org.jmock.junit5.JUnit5Mockery; import org.jmock.junit5.extensions.ExpectationExtension; import org.jmock.junit5.extensions.ExpectationThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; @ExtendWith(ExpectationExtension.class) public class JUnit5TestThatThrowsExpectedException { @RegisterExtension JUnit5Mockery context = new JUnit5Mockery(); private WithException withException = context.mock(WithException.class); @Test @ExpectationThrows(expected=CheckedException.class) public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException { context.checking(new Expectations() {{ oneOf (withException).anotherMethod(); oneOf (withException).throwingMethod(); will(throwException(new CheckedException())); }}); withException.throwingMethod(); } public static class CheckedException extends Exception { } public interface WithException { void throwingMethod() throws CheckedException; void anotherMethod(); } } JUnit5WithRulesExamples.java000066400000000000000000000076661347002534600367540ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptancepackage org.jmock.junit5.testdata.jmock.acceptance; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.States; import org.jmock.auto.Auto; import org.jmock.auto.Mock; import org.jmock.junit5.JUnit5Mockery; import org.jmock.junit5.extensions.ExpectationExtension; import org.jmock.junit5.extensions.ExpectationThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; public class JUnit5WithRulesExamples { public static class SatisfiesExpectations { @RegisterExtension public final JUnit5Mockery context = new JUnit5Mockery(); private final Runnable runnable = context.mock(Runnable.class); @Test public void doesSatisfyExpectations() { context.checking(new Expectations() { { oneOf(runnable).run(); } }); runnable.run(); } } public static class DoesNotSatisfyExpectations { @RegisterExtension public final JUnit5Mockery context = new JUnit5Mockery(); private Runnable runnable = context.mock(Runnable.class); @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() { { oneOf(runnable).run(); } }); // Return without satisfying the expectation for runnable.run() } } public static class DerivedAndDoesNotSatisfyExpectations extends BaseClassWithJMockContext { private Runnable runnable = context.mock(Runnable.class); @Test public void doesNotSatisfyExpectations() { context.checking(new Expectations() { { oneOf(runnable).run(); } }); // Return without satisfying the expectation for runnable.run() } } @ExtendWith(ExpectationExtension.class) public static class ThrowsExpectedException { @RegisterExtension public final JUnit5Mockery context = new JUnit5Mockery(); private WithException withException = context.mock(WithException.class); @Test @ExpectationThrows(expected = CheckedException.class) public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException { context.checking(new Expectations() { { oneOf(withException).anotherMethod(); oneOf(withException).throwingMethod(); will(throwException(new CheckedException())); } }); withException.throwingMethod(); } @SuppressWarnings("serial") public static class CheckedException extends Exception { } public interface WithException { void throwingMethod() throws CheckedException; void anotherMethod(); } } public static class CreatesTwoMockeries extends BaseClassWithJMockContext { @RegisterExtension public final JUnit5Mockery context = new JUnit5Mockery(); @Test public void doesNothing() { // no op } } public static class AutoInstantiatesMocks extends BaseClassWithJMockContext { @Mock Runnable runnable; @Auto States states; @Auto Sequence sequence; @Test public void fieldsHaveBeenAutoInstantiated() { assertThat("runnable", runnable, notNullValue()); assertThat("states", states, notNullValue()); assertThat("sequence", sequence, notNullValue()); } } public static class BaseClassWithJMockContext { @RegisterExtension public final JUnit5Mockery context = new JUnit5Mockery(); } } jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/unit/000077500000000000000000000000001347002534600254425ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/unit/lib/000077500000000000000000000000001347002534600262105ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/unit/lib/concurrent/000077500000000000000000000000001347002534600303725ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/unit/lib/concurrent/internal/000077500000000000000000000000001347002534600322065ustar00rootroot00000000000000SynchroniserTests.java000066400000000000000000000131231347002534600365030ustar00rootroot00000000000000jmock-library-2.12.0/jmock-junit5/src/test/java/org/jmock/junit5/unit/lib/concurrent/internalpackage org.jmock.junit5.unit.lib.concurrent.internal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.atomic.AtomicInteger; import org.jmock.Expectations; import org.jmock.States; import org.jmock.junit5.JUnit5Mockery; import org.jmock.junit5.extensions.ExpectationTimeout; import org.jmock.lib.concurrent.Blitzer; import org.jmock.lib.concurrent.Synchroniser; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; public class SynchroniserTests { public interface Events { void action(); void finished(); } Synchroniser synchroniser = new Synchroniser(); // Not an extension, to allow checking the mockery is *not* satisfied JUnit5Mockery mockery = new JUnit5Mockery() {{ setThreadingPolicy(synchroniser); }}; Blitzer blitzer = new Blitzer(16, 4); Events mockObject = mockery.mock(Events.class, "mockObject"); @Test @ExpectationTimeout(timeout=250) public void allowsMultipleThreadsToCallMockObjects() throws InterruptedException { mockery.checking(new Expectations() {{ exactly(blitzer.totalActionCount()).of(mockObject).action(); }}); blitzer.blitz(new Runnable() { public void run() { mockObject.action(); } }); mockery.assertIsSatisfied(); } @Test @ExpectationTimeout(timeout=250) public void canWaitForAStateMachineToEnterAGivenState() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(blitzer.totalActionCount()); final States threads = mockery.states("threads"); mockery.checking(new Expectations() {{ exactly(blitzer.totalActionCount()).of(mockObject).action(); when(threads.isNot("finished")); oneOf(mockObject).finished(); then(threads.is("finished")); }}); blitzer.blitz(new Runnable() { public void run() { mockObject.action(); if (counter.decrementAndGet() == 0) { mockObject.finished(); } } }); synchroniser.waitUntil(threads.is("finished")); mockery.assertIsSatisfied(); } @Test @ExpectationTimeout(timeout=250) public void canWaitForAStateMachineToEnterAGivenStateWithinSomeTimeout() throws InterruptedException { final States threads = mockery.states("threads"); mockery.checking(new Expectations() {{ exactly(blitzer.totalActionCount()).of(mockObject).action(); when(threads.isNot("finished")); oneOf(mockObject).finished(); then(threads.is("finished")); }}); blitzer.blitz(new Runnable() { AtomicInteger counter = new AtomicInteger(blitzer.totalActionCount()); public void run() { mockObject.action(); if (counter.decrementAndGet() == 0) { mockObject.finished(); } } }); synchroniser.waitUntil(threads.is("finished"), 100); } @Test @ExpectationTimeout(timeout=250) public void failsTheTestIfStateMachineDoesNotEnterExpectedStateWithinTimeout() throws InterruptedException { States threads = mockery.states("threads"); try { synchroniser.waitUntil(threads.is("finished"), 100); } catch (AssertionError e) { return; } fail("should have thrown AssertionError"); } @Test public void throwsExpectationErrorIfExpectationFailsWhileWaitingForStateMachine() throws InterruptedException { final States threads = mockery.states("threads"); // This will cause an expectation error, and nothing will make // the "threads" state machine transition to "finished" blitzer.blitz(new Runnable() { public void run() { mockObject.action(); } }); try { synchroniser.waitUntil(threads.is("finished"), 100); fail("should have thrown AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("action()")); } } @Test public void throwsExpectationErrorIfExpectationFailsWhileWaitingForStateMachineEvenIfWaitSucceeds() throws InterruptedException { final States threads = mockery.states("threads"); mockery.checking(new Expectations() {{ oneOf(mockObject).finished(); then(threads.is("finished")); }}); blitzer.blitz(new Runnable() { AtomicInteger counter = new AtomicInteger(blitzer.totalActionCount()); public void run() { if (counter.decrementAndGet() == 0) { mockObject.finished(); } else { mockObject.action(); } } }); try { synchroniser.waitUntil(threads.is("finished"), 100); fail("should have thrown AssertionError"); } catch (AssertionError e) { assertThat(e.getMessage(), containsString("action()")); } } @AfterEach public void cleanUp() { blitzer.shutdown(); } } jmock-library-2.12.0/jmock-legacy/000077500000000000000000000000001347002534600167125ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/pom.xml000066400000000000000000000043361347002534600202350ustar00rootroot00000000000000 4.0.0 jmock-legacy jmock-legacy org.jmock jmock-parent 2.12.0 3.2.8 org.junit.jupiter junit-jupiter-api org.junit.jupiter junit-jupiter-params org.junit.jupiter junit-jupiter-engine org.jmock jmock ${project.version} compile org.jmock jmock ${project.version} test-jar test org.objenesis objenesis cglib cglib ${cglib.version} org.apache.ant ant org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock-legacy/src/000077500000000000000000000000001347002534600175015ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/000077500000000000000000000000001347002534600204255ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/java/000077500000000000000000000000001347002534600213465ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/java/org/000077500000000000000000000000001347002534600221355ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/java/org/jmock/000077500000000000000000000000001347002534600232405ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/java/org/jmock/lib/000077500000000000000000000000001347002534600240065ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/java/org/jmock/lib/legacy/000077500000000000000000000000001347002534600252525ustar00rootroot00000000000000jmock-library-2.12.0/jmock-legacy/src/main/java/org/jmock/lib/legacy/ClassImposteriser.java000066400000000000000000000143711347002534600315760ustar00rootroot00000000000000package org.jmock.lib.legacy; import net.sf.cglib.core.CodeGenerationException; import net.sf.cglib.core.DefaultNamingPolicy; import net.sf.cglib.core.NamingPolicy; import net.sf.cglib.core.Predicate; import net.sf.cglib.proxy.*; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.api.Invokable; import org.jmock.internal.SearchingClassLoader; import org.objenesis.Objenesis; import org.objenesis.ObjenesisStd; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; /** * This class lets you imposterise abstract and concrete classes * without calling the constructors of the mocked class. * * @author npryce * * @deprecated Java11 support is weak, Migrate to org.jmock.lib.imposters.ByteBuddyClassImposteriser */ public class ClassImposteriser implements Imposteriser { public static final Imposteriser INSTANCE = new ClassImposteriser(); private ClassImposteriser() {} private static final Method FINALIZE_METHOD = findFinalizeMethod(); private static final NamingPolicy NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES = new DefaultNamingPolicy() { @Override public String getClassName(String prefix, String source, Object key, Predicate names) { return "org.jmock.codegen." + super.getClassName(prefix, source, key, names); } }; private static final CallbackFilter IGNORED_METHODS = new CallbackFilter() { public int accept(Method method) { if (method.isBridge()) return 1; else if (method.equals(FINALIZE_METHOD)) return 1; else return 0; } }; private final Objenesis objenesis = new ObjenesisStd(); public boolean canImposterise(Class type) { return !type.isPrimitive() && !Modifier.isFinal(type.getModifiers()) && (type.isInterface() || !toStringMethodIsFinal(type)); } @Override public T imposterise(final Invokable mockObject, Class mockedType, Class... ancilliaryTypes) { if (!mockedType.isInterface() && toStringMethodIsFinal(mockedType)) { throw new IllegalArgumentException(mockedType.getName() + " has a final toString method"); } try { setConstructorsAccessible(mockedType, true); return mockedType.cast(proxy(proxyClass(mockedType, ancilliaryTypes), mockObject)); } finally { setConstructorsAccessible(mockedType, false); } } private boolean toStringMethodIsFinal(Class type) { try { Method toString = type.getMethod("toString"); return Modifier.isFinal(toString.getModifiers()); } catch (SecurityException e) { throw new IllegalStateException("not allowed to reflect on toString method", e); } catch (NoSuchMethodException e) { throw new Error("no public toString method found", e); } } private void setConstructorsAccessible(Class mockedType, boolean accessible) { for (Constructor constructor : mockedType.getDeclaredConstructors()) { constructor.setAccessible(accessible); } } private Class proxyClass(Class possibleMockedType, Class... ancilliaryTypes) { final Class mockedType = possibleMockedType == Object.class ? ClassWithSuperclassToWorkAroundCglibBug.class : possibleMockedType; final Enhancer enhancer = new Enhancer() { @Override @SuppressWarnings("unchecked") protected void filterConstructors(Class sc, List constructors) { // Don't filter } }; enhancer.setClassLoader(SearchingClassLoader.combineLoadersOf(mockedType, ancilliaryTypes)); enhancer.setUseFactory(true); if (mockedType.isInterface()) { enhancer.setSuperclass(Object.class); enhancer.setInterfaces(prepend(mockedType, ancilliaryTypes)); } else { enhancer.setSuperclass(mockedType); enhancer.setInterfaces(ancilliaryTypes); } enhancer.setCallbackTypes(new Class[]{InvocationHandler.class, NoOp.class}); enhancer.setCallbackFilter(IGNORED_METHODS); if (protectedPackageNamespace(mockedType)) { enhancer.setNamingPolicy(NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES); } try { return enhancer.createClass(); } catch (CodeGenerationException e) { // Note: I've only been able to manually test this. It exists to help people writing // Eclipse plug-ins or using other environments that have sophisticated class loader // structures. throw new IllegalArgumentException("could not imposterise " + mockedType, e); } } private Object proxy(Class proxyClass, final Invokable mockObject) { final Factory proxy = (Factory)objenesis.newInstance(proxyClass); proxy.setCallbacks(new Callback[] { new InvocationHandler() { public Object invoke(Object receiver, Method method, Object[] args) throws Throwable { return mockObject.invoke(new Invocation(receiver, method, args)); } }, NoOp.INSTANCE }); return proxy; } private Class[] prepend(Class first, Class... rest) { Class[] all = new Class[rest.length+1]; all[0] = first; System.arraycopy(rest, 0, all, 1, rest.length); return all; } private static Method findFinalizeMethod() { try { return Object.class.getDeclaredMethod("finalize"); } catch (NoSuchMethodException e) { throw new IllegalStateException("Could not find finalize method on Object"); } } private boolean protectedPackageNamespace(Class mockedType) { return mockedType.getSigners() != null || mockedType.getName().startsWith("java."); } public static class ClassWithSuperclassToWorkAroundCglibBug {} } jmock-library-2.12.0/jmock-legacy/src/main/java/org/jmock/lib/legacy/package.html000066400000000000000000000001421347002534600275300ustar00rootroot00000000000000

Plugins that make it easier to use jMock with legacy code.

jmock-library-2.12.0/jmock/000077500000000000000000000000001347002534600154505ustar00rootroot00000000000000jmock-library-2.12.0/jmock/.gitignore000066400000000000000000000000671347002534600174430ustar00rootroot00000000000000/target/ .settings .project .classpath Xpectations.javajmock-library-2.12.0/jmock/pom.xml000066400000000000000000000061731347002534600167740ustar00rootroot00000000000000 4.0.0 jmock jar jMock 2 Core org.jmock jmock-parent 2.12.0 ../pom.xml org.jmock jmock-testjar compile ${project.version} org.hamcrest hamcrest compile org.hamcrest hamcrest-library compile org.ow2.asm asm org.apache-extras.beanshell bsh javax.xml.ws jaxws-api 2.3.1 test junit junit test org.apache.maven.plugins maven-jar-plugin 3.1.2 test-jar org.codehaus.mojo exec-maven-plugin 1.6.0 process-classes exec java -cp %classpath:target/classes org.jmock.ExpectationsCreator org.codehaus.mojo versions-maven-plugin jmock-library-2.12.0/jmock/src/000077500000000000000000000000001347002534600162375ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/000077500000000000000000000000001347002534600171635ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/000077500000000000000000000000001347002534600201045ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/000077500000000000000000000000001347002534600206735ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/000077500000000000000000000000001347002534600217765ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/AbstractExpectations.java000066400000000000000000000224671347002534600270060ustar00rootroot00000000000000package org.jmock; import org.hamcrest.CoreMatchers; import org.hamcrest.Matcher; import org.hamcrest.core.*; import org.jmock.api.Action; import org.jmock.api.ExpectationCollector; import org.jmock.internal.*; import org.jmock.lib.action.*; import org.jmock.syntax.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Provides most of the syntax of jMock's "domain-specific language" API. * The methods of this class don't make any sense on their own, so the * Javadoc is rather sparse. Consult the documentation on the jMock * website for information on how to use this API. * * @author nat * */ public abstract class AbstractExpectations implements ExpectationBuilder, CardinalityClause, ArgumentConstraintPhrases, ActionClause { private List builders = new ArrayList(); private InvocationExpectationBuilder currentBuilder = null; /** * Syntactic sugar for specifying arguments that are matchers for primitive types * or are untyped matchers. */ protected final WithClause with = new WithClause() { public boolean booleanIs(Matcher matcher) { addParameterMatcher(matcher); return false; } public byte byteIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public char charIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public double doubleIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public float floatIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public int intIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public long longIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public short shortIs(Matcher matcher) { addParameterMatcher(matcher); return 0; } public T is(Matcher matcher) { addParameterMatcher(matcher); return null; } }; private void initialiseExpectationCapture(Cardinality cardinality) { checkLastExpectationWasFullySpecified(); currentBuilder = new InvocationExpectationBuilder(); currentBuilder.setCardinality(cardinality); builders.add(currentBuilder); } public void buildExpectations(Action defaultAction, ExpectationCollector collector) { checkLastExpectationWasFullySpecified(); for (InvocationExpectationBuilder builder : builders) { collector.add(builder.toExpectation(defaultAction)); } } protected InvocationExpectationBuilder currentBuilder() { if (currentBuilder == null) { throw new IllegalStateException("no expectations have been specified " + "(did you forget to to specify the cardinality of the first expectation?)"); } return currentBuilder; } private void checkLastExpectationWasFullySpecified() { if (currentBuilder != null) { currentBuilder.checkWasFullySpecified(); } } /* * Syntactic sugar */ public ReceiverClause exactly(int count) { initialiseExpectationCapture(Cardinality.exactly(count)); return currentBuilder; } // Makes the entire expectation more readable than one public T oneOf(T mockObject) { return exactly(1).of(mockObject); } /** * @deprecated Use {@link #oneOf(Object) oneOf} instead. */ public T one (T mockObject) { return oneOf(mockObject); } public ReceiverClause atLeast(int count) { initialiseExpectationCapture(Cardinality.atLeast(count)); return currentBuilder; } public ReceiverClause between(int minCount, int maxCount) { initialiseExpectationCapture(Cardinality.between(minCount, maxCount)); return currentBuilder; } public ReceiverClause atMost(int count) { initialiseExpectationCapture(Cardinality.atMost(count)); return currentBuilder; } public MethodClause allowing(Matcher mockObjectMatcher) { return atLeast(0).of(mockObjectMatcher); } public T allowing(T mockObject) { return atLeast(0).of(mockObject); } public T ignoring(T mockObject) { return allowing(mockObject); } public MethodClause ignoring(Matcher mockObjectMatcher) { return allowing(mockObjectMatcher); } public T never(T mockObject) { return exactly(0).of(mockObject); } /* * protected because the byte code injected values need to be able to call this */ protected void addParameterMatcher(Matcher matcher) { currentBuilder().addParameterMatcher(matcher); } /** * For Matchers with primitive types use the with field, for example: *
with.intIs(equalTo(34));
* For untyped matchers use: *
with.<T>is(equalTo(anObject));
*/ public T with(Matcher matcher) { addParameterMatcher(matcher); return null; } public boolean with(boolean value) { addParameterMatcher(equal(value)); return false; } public byte with(byte value) { addParameterMatcher(equal(value)); return 0; } public short with(short value) { addParameterMatcher(equal(value)); return 0; } public char with(char value) { addParameterMatcher(equal(value)); return 0; } public int with(int value) { addParameterMatcher(equal(value)); return 0; } public long with(long value) { addParameterMatcher(equal(value)); return 0; } public float with(float value) { addParameterMatcher(equal(value)); return 0; } public double with(double value) { addParameterMatcher(equal(value)); return 0; } public T with(T value) { addParameterMatcher(equal(value)); return value; } public void will(Action action) { currentBuilder().setAction(action); } /* Common constraints */ public static Matcher equal(T value) { return new IsEqual(value); } public static Matcher same(T value) { return new IsSame(value); } public static Matcher any(Class type) { return CoreMatchers.any(type); } public static Matcher anything() { return new IsAnything(); } /** * @deprecated * use {@link #aNonNull} or {@link #any} until type inference actually works in a future version of Java * @param type Class to match. Do not use for native parameters. * @return an IsInstanceOf matcher */ @Deprecated public static Matcher a(Class type) { return new IsInstanceOf(type); } /** * @deprecated * use {@link #aNonNull} or {@link #any} until type inference actually works in a future version of Java * @param type Class to match. Do not use for native parameters. * @return an IsInstanceOf matcher */ @Deprecated public static Matcher an(Class type) { return new IsInstanceOf(type); } public static Matcher aNull(Class type) { return new IsNull(); } public static Matcher aNonNull(Class type) { return new IsNot(new IsNull()); } /* Common actions */ public static Action returnValue(Object result) { return new ReturnValueAction(result); } public static Action throwException(Throwable throwable) { return new ThrowAction(throwable); } public static Action returnIterator(Collection collection) { return new ReturnIteratorAction(collection); } public static Action returnIterator(T ... items) { return new ReturnIteratorAction(items); } public static Action returnEnumeration(Collection collection) { return new ReturnEnumerationAction(collection); } public static Action returnEnumeration(T ... items) { return new ReturnEnumerationAction(items); } public static Action doAll(Action...actions) { return new DoAllAction(actions); } public static Action onConsecutiveCalls(Action...actions) { return new ActionSequence(actions); } /* Naming and ordering */ public void when(StatePredicate predicate) { currentBuilder().addOrderingConstraint(new InStateOrderingConstraint(predicate)); } public void then(State state) { currentBuilder().addSideEffect(new ChangeStateSideEffect(state)); } public void inSequence(Sequence sequence) { currentBuilder().addInSequenceOrderingConstraint(sequence); } public void inSequences(Sequence... sequences) { for (Sequence sequence : sequences) { inSequence(sequence); } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/Expectations.java000066400000000000000000000002111347002534600253010ustar00rootroot00000000000000package org.jmock; /** * Backward compatibility Methods added with ASM */ public class Expectations extends AbstractExpectations { } jmock-library-2.12.0/jmock/src/main/java/org/jmock/ExpectationsCreator.java000066400000000000000000000151641347002534600266360ustar00rootroot00000000000000package org.jmock; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Logger; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public class ExpectationsCreator implements Opcodes { private static final Logger LOG = Logger.getLogger(ExpectationsCreator.class.getSimpleName()); public static void main(String... argv) throws IOException, Exception { LOG.info("Expections Old School method injector running"); LOG.info("Running in " + new java.io.File( "." ).getCanonicalPath()); // Class klass = org.jmock.Expectations.class; String className = "org.jmock.Expectations"; // String className = "java.lang.Runnable"; String classPath = className.replace('.', '/') + ".class"; InputStream stream = ClassLoader.getSystemResourceAsStream(classPath); byte[] dump = dump(stream); FileOutputStream output = new FileOutputStream("target/classes/" + classPath); output.write(dump); output.close(); } public static byte[] dump(InputStream stream) throws Exception { ClassReader classReader = new ClassReader(stream); ClassWriter cw = new ClassWriter(classReader, 0); FieldVisitor fv; MethodVisitor mv; AnnotationVisitor av0; // 1.5 to allow our generic method overloading cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, "org/jmock/Expectations", null, "org/jmock/AbstractExpectations", null); { mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/AbstractExpectations", "", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)Z", "(Lorg/hamcrest/Matcher;)Z", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)B", "(Lorg/hamcrest/Matcher;)B", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)S", "(Lorg/hamcrest/Matcher;)S", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)C", "(Lorg/hamcrest/Matcher;)C", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)I", "(Lorg/hamcrest/Matcher;)I", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)J", "(Lorg/hamcrest/Matcher;)J", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(LCONST_0); mv.visitInsn(LRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)F", "(Lorg/hamcrest/Matcher;)F", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(FCONST_0); mv.visitInsn(FRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "with", "(Lorg/hamcrest/Matcher;)D", "(Lorg/hamcrest/Matcher;)D", null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, "org/jmock/Expectations", "addParameterMatcher", "(Lorg/hamcrest/Matcher;)V"); mv.visitInsn(DCONST_0); mv.visitInsn(DRETURN); mv.visitMaxs(2, 2); mv.visitEnd(); } return cw.toByteArray(); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/Mockery.java000066400000000000000000000261461347002534600242630ustar00rootroot00000000000000package org.jmock; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; import org.jmock.api.Expectation; import org.jmock.api.ExpectationError; import org.jmock.api.ExpectationErrorTranslator; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.api.InvocationDispatcher; import org.jmock.api.Invokable; import org.jmock.api.MockObjectNamingScheme; import org.jmock.api.ThreadingPolicy; import org.jmock.internal.CaptureControl; import org.jmock.internal.ExpectationBuilder; import org.jmock.internal.ExpectationCapture; import org.jmock.internal.InvocationDiverter; import org.jmock.internal.InvocationToExpectationTranslator; import org.jmock.internal.NamedSequence; import org.jmock.internal.ObjectMethodExpectationBouncer; import org.jmock.internal.ProxiedObjectIdentity; import org.jmock.internal.ReturnDefaultValueAction; import org.jmock.internal.SingleThreadedPolicy; import org.jmock.lib.CamelCaseNamingScheme; import org.jmock.lib.IdentityExpectationErrorTranslator; import org.jmock.lib.JavaReflectionImposteriser; import org.jmock.lib.concurrent.Synchroniser; /** * A Mockery represents the context, or neighbourhood, of the object(s) under test. * * The neighbouring objects in that context are mocked out. The test specifies the * expected interactions between the object(s) under test and its neighbours and * the Mockery checks those expectations while the test is running. * * @author npryce * @author smgf * @author olibye * @author named by Ivan Moore. */ public class Mockery implements SelfDescribing { private Imposteriser imposteriser = JavaReflectionImposteriser.INSTANCE; private ExpectationErrorTranslator expectationErrorTranslator = IdentityExpectationErrorTranslator.INSTANCE; private MockObjectNamingScheme namingScheme = CamelCaseNamingScheme.INSTANCE; private ThreadingPolicy threadingPolicy = new SingleThreadedPolicy(); private final Set mockNames = new HashSet(); private final ReturnDefaultValueAction defaultAction = new ReturnDefaultValueAction(imposteriser); private final List actualInvocations = new ArrayList(); private InvocationDispatcher dispatcher = threadingPolicy.dispatcher(); private Error firstError = null; /* * Policies */ /** * Sets the result returned for the given type when no return value has been explicitly * specified in the expectation. * * @param type * The type for which to return result. * @param result * The value to return when a method of return type type * is invoked for which an explicit return value has has not been specified. */ public void setDefaultResultForType(Class type, Object result) { defaultAction.addResult(type, result); } /** * Changes the imposteriser used to adapt mock objects to the mocked type. * * The default imposteriser allows a test to mock interfaces but not * classes, so you'll have to plug a different imposteriser into the * Mockery if you want to mock classes. * @param imposteriser makes mocks */ public void setImposteriser(Imposteriser imposteriser) { this.imposteriser = imposteriser; this.defaultAction.setImposteriser(imposteriser); } /** * Changes the naming scheme used to generate names for mock objects that * have not been explicitly named in the test. * * The default naming scheme names mock objects by lower-casing the first * letter of the class name, so a mock object of type BananaSplit will be * called "bananaSplit" if it is not explicitly named in the test. * @param namingScheme names mocks for failure reports */ public void setNamingScheme(MockObjectNamingScheme namingScheme) { this.namingScheme = namingScheme; } /** * Changes the expectation error translator used to translate expectation * errors into errors that report test failures. * * By default, expectation errors are not translated and are thrown as * errors of type {@link ExpectationError}. Plug in a new expectation error * translator if you want your favourite test framework to report expectation * failures using its own error type. * @param expectationErrorTranslator translator for your test framework */ public void setExpectationErrorTranslator(ExpectationErrorTranslator expectationErrorTranslator) { this.expectationErrorTranslator = expectationErrorTranslator; } /** * Changes the policy by which the Mockery copes with multiple threads. * * The default policy throws an exception if the Mockery is called from different * threads. * * @see Synchroniser * @param threadingPolicy how to handle different threads. */ public void setThreadingPolicy(ThreadingPolicy threadingPolicy) { this.threadingPolicy = threadingPolicy; this.dispatcher = threadingPolicy.dispatcher(); } /* * API */ /** * Creates a mock object of type typeToMock and generates a name for it. * @param is the class of the mock * @param typeToMock is the class of the mock * @return the mock of typeToMock */ public T mock(Class typeToMock) { return mock(typeToMock, namingScheme.defaultNameFor(typeToMock)); } /** * Creates a mock object of type typeToMock with the given name. * @param is the class of the mock * @param typeToMock is the class of the mock * @param name is the name of the mock object that will appear in failures * @return the mock of typeToMock */ public T mock(Class typeToMock, String name) { if (mockNames.contains(name)) { throw new IllegalArgumentException("a mock with name " + name + " already exists"); } final MockObject mock = new MockObject(typeToMock, name); mockNames.add(name); Invokable invokable = threadingPolicy.synchroniseAccessTo( new ProxiedObjectIdentity( new InvocationDiverter( CaptureControl.class, mock, mock))); return imposteriser.imposterise(invokable, typeToMock, CaptureControl.class); } /** * Returns a new sequence that is used to constrain the order in which * expectations can occur. * * @param name * The name of the sequence. * @return * A new sequence with the given name. */ public Sequence sequence(String name) { return new NamedSequence(name); } /** * Returns a new state machine that is used to constrain the order in which * expectations can occur. * * @param name * The name of the state machine. * @return * A new state machine with the given name. */ public States states(String name) { return dispatcher.newStateMachine(name); } /** * Specifies the expected invocations that the object under test will perform upon * objects in its context during the test. * * The builder is responsible for interpreting high-level, readable API calls to * construct an expectation. * * This method can be called multiple times per test and the expectations defined in * each block are combined as if they were defined in same order within a single block. * @param expectations that will be checked */ public void checking(ExpectationBuilder expectations) { expectations.buildExpectations(defaultAction, dispatcher); } /** * Adds an expected invocation that the object under test will perform upon * objects in its context during the test. * * This method allows a test to define an expectation explicitly, bypassing the * high-level API, if desired. * @param expectation to check */ public void addExpectation(Expectation expectation) { dispatcher.add(expectation); } /** * Fails the test if there are any expectations that have not been met. */ public void assertIsSatisfied() { if (firstError != null) { throw firstError; } else if (!dispatcher.isSatisfied()) { throw expectationErrorTranslator.translate( ExpectationError.notAllSatisfied(this)); } } public void describeTo(Description description) { description.appendDescriptionOf(dispatcher); describeHistory(description); } private void describeMismatch(Invocation invocation, Description description) { dispatcher.describeMismatch(invocation, description); describeHistory(description); } private void describeHistory(Description description) { description.appendText("\nwhat happened before this:"); final List invocationsSoFar = new ArrayList(actualInvocations); if (invocationsSoFar.isEmpty()) { description.appendText(" nothing!"); } else { description.appendList("\n ", "\n ", "\n", invocationsSoFar); } } private Object dispatch(Invocation invocation) throws Throwable { if (firstError != null) { throw firstError; } try { Object result = dispatcher.dispatch(invocation); actualInvocations.add(invocation); return result; } catch (ExpectationError e) { firstError = expectationErrorTranslator.translate(mismatchDescribing(e)); firstError.setStackTrace(e.getStackTrace()); throw firstError; } catch (Throwable t) { actualInvocations.add(invocation); throw t; } } private ExpectationError mismatchDescribing(final ExpectationError e) { ExpectationError filledIn = new ExpectationError(e.getMessage(), new SelfDescribing() { public void describeTo(Description description) { describeMismatch(e.invocation, description); } }, e.invocation); filledIn.setStackTrace(e.getStackTrace()); return filledIn; } private class MockObject implements Invokable, CaptureControl { private Class mockedType; private String name; public MockObject(Class mockedType, String name) { this.name = name; this.mockedType = mockedType; } @Override public String toString() { return name; } public Object invoke(Invocation invocation) throws Throwable { return dispatch(invocation); } public Object captureExpectationTo(ExpectationCapture capture) { return imposteriser.imposterise( new ObjectMethodExpectationBouncer(new InvocationToExpectationTranslator(capture, defaultAction)), mockedType); } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/Sequence.java000066400000000000000000000004721347002534600244140ustar00rootroot00000000000000package org.jmock; import org.jmock.internal.InvocationExpectation; /** * A sequence of expectations; invocations can be constrained to occur in a strict * order defined by a sequence. * * @author nat */ public interface Sequence { void constrainAsNextInSequence(InvocationExpectation expectation); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/States.java000066400000000000000000000014251347002534600241060ustar00rootroot00000000000000package org.jmock; import org.hamcrest.SelfDescribing; import org.jmock.syntax.StatesClause; /** * A state machine that is used to constrain the order of invocations. * * An invocation can be constrained to occur when a state is, or is not, active. * * @author nat */ public interface States extends SelfDescribing, StatesClause { /** * Put the state machine into state initialState. * * @param initialState * The initial state of the state machine. * @return * Itself. */ States startsAs(String initialState); /** * Put the state machine into state nextState. * * @param nextState * The next state of the state machine. */ void become(String nextState); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/000077500000000000000000000000001347002534600225475ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/Action.java000066400000000000000000000004151347002534600246270ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.api; import org.hamcrest.SelfDescribing; /** * An object that fakes the behaviour of an {@link org.jmock.internal.InvocationExpectation}. */ public interface Action extends SelfDescribing, Invokable { } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/Expectation.java000066400000000000000000000041701347002534600256770ustar00rootroot00000000000000package org.jmock.api; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; /** * An object that matches, checks and fakes an {@link org.jmock.api.Invocation} * * @author npryce * @author smgf */ public interface Expectation extends SelfDescribing { /** * Have enough {@link Invocation}s expected by this Expectation occurred? * * @return * true if the expectation has received enough * of its expected invocations, false otherwise. */ boolean isSatisfied(); /** * Can more {@link Invocation}s expected by this Expectation still occur? * * @return * true if invocations expected by this expectation can still * occur, false otherwise. */ boolean allowsMoreInvocations(); /** * Can the Expectation be invoked with invocation? * * @param invocation to be matched * * @return * true if the expectation can be invoked with * invocation, false otherwise. */ boolean matches(Invocation invocation); void describeMismatch(Invocation invocation, Description description); /** * Invokes the expectation: records that the invocation has * occurred and fakes some behaviour in response. * * @param invocation * The invocation to record and fake. * @return * A result that is eventually returned from the method call * that caused the invocation. * * @throws Throwable * An exception that is eventually thrown from the method call * that caused the invocation. * @throws IllegalStateException * The expectation has been invoked with a method that it doesn't * match or the faked behaviour has been set up incorrectly. * For example, IllegalStateException is thrown when trying to return * a value or throw a checked exception that is incompatible with the * return type of the method being mocked */ Object invoke(Invocation invocation) throws Throwable; } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/ExpectationCollector.java000066400000000000000000000001511347002534600275410ustar00rootroot00000000000000package org.jmock.api; public interface ExpectationCollector { void add(Expectation expectation); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/ExpectationError.java000066400000000000000000000024561347002534600267160ustar00rootroot00000000000000package org.jmock.api; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; import org.hamcrest.StringDescription; /** * An error thrown when an expectation is violated during a test. * * @author npryce */ public class ExpectationError extends Error implements SelfDescribing { public final SelfDescribing expectations; public final Invocation invocation; public ExpectationError(String message, SelfDescribing expectations, Invocation invocation) { super(message); this.invocation = invocation; this.expectations = expectations; } public static ExpectationError unexpected(String message, Invocation invocation) { return new ExpectationError(message, null, invocation); } public static ExpectationError notAllSatisfied(SelfDescribing expectations) { return new ExpectationError("not all expectations were satisfied", expectations, null); } @Override public String toString() { return StringDescription.toString(this); } public void describeTo(Description description) { description.appendText(getMessage()); if (invocation != null) { description.appendText(": "); invocation.describeTo(description); } if (expectations != null) { description.appendText("\n"); expectations.describeTo(description); } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/ExpectationErrorTranslator.java000066400000000000000000000011451347002534600307620ustar00rootroot00000000000000package org.jmock.api; /** * Translates expectation errors into error type used by a specific * testing framework. * * @author npryce */ public interface ExpectationErrorTranslator { /** * Translates the given {@link ExpectationError} into an error * type compatible with another testing framework. * * @param e * The {@link ExpectationError} to translate. * * @return * An error that is compatible with another testing framework * and contains the same message and stack trace as e. */ Error translate(ExpectationError e); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/Imposteriser.java000066400000000000000000000026441347002534600261050ustar00rootroot00000000000000package org.jmock.api; /** * An object that can creates a proxy of the given type to capture * {@link org.jmock.api.Invocation}s and pass them to an * {@link org.jmock.api.Invokable} object for mocking or stubbing. * * @author npryce */ public interface Imposteriser { /** * Reports if the Imposteriser is able to imposterise a given type. * * @param type * The type in question. * @return * True if this imposteriser can imposterise type, false otherwise. */ boolean canImposterise(Class type); /** * Creates an imposter for a given type that forwards {@link Invocation}s to an * {@link Invokable} object. * * @param * The static type of the imposter that is created. * @param mockObject * The object that is to receive invocations forwarded from the imposter. * @param mockedType * The class representing the static type of the imposter. * @param ancilliaryTypes * Other types for the imposter. It must be possible to dynamically cast the imposter to these types. * These types must all be interfaces because Java only allows single inheritance of classes. * @return * A new imposter. The imposter must implement the mockedType and all the ancialliaryTypes. */ T imposterise(Invokable mockObject, Class mockedType, Class... ancilliaryTypes); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/Invocation.java000066400000000000000000000137111347002534600255260ustar00rootroot00000000000000/* * Copyright (c) 2000-2004 jMock.org */ package org.jmock.api; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; import org.hamcrest.StringDescription; /** * The static details about a method and the run-time details of its invocation. * * @since 1.0 */ public class Invocation implements SelfDescribing { public static final Object[] NO_PARAMETERS = null; private final Object invokedObject; private final Method invokedMethod; private final Object[] parameterValues; private final ExpectationMode mode; // A kludge but there doesn't seem to be a way to find this out through the reflection API. private static final Map, Class> BOX_TYPES = new HashMap, Class>() { { put(boolean.class, Boolean.class); put(byte.class, Byte.class); put(char.class, Character.class); put(short.class, Short.class); put(int.class, Integer.class); put(long.class, Long.class); put(float.class, Float.class); put(double.class, Double.class); } }; /** * Support distinguish between building expectations and asserting against expectations. * ByteBuddy (for example) checks runtime return types. * It's simplest and safest to return null when building expectations */ public enum ExpectationMode { BUILDING, // We're building the expectations so invocations can return null ASSERTING, // Return the default or specified reply LEGACY // Legacy mode old imposters } public Invocation(ExpectationMode mode, Object invoked, Method method, Object... parameterValues) { this.mode = mode; this.invokedObject = invoked; this.invokedMethod = method; this.parameterValues = (parameterValues == NO_PARAMETERS) ? new Object[0] : parameterValues.clone(); } public Invocation(ExpectationMode mode, Invocation other) { this.mode = mode; this.invokedObject = other.invokedObject; this.invokedMethod = other.invokedMethod; this.parameterValues = other.parameterValues; } public Invocation(Object invoked, Method method, Object... parameterValues) { this(ExpectationMode.LEGACY, invoked, method, parameterValues); } @Override public String toString() { return super.toString() + "[" + StringDescription.toString(this) + "]"; } @Override public boolean equals(Object other) { return (other instanceof Invocation) && this.equals((Invocation) other); } public boolean equals(Invocation other) { // ignore mode return other != null && invokedObject == other.invokedObject && invokedMethod.equals(other.invokedMethod) && Arrays.equals(parameterValues, other.parameterValues); } @Override public int hashCode() { return invokedObject.hashCode() ^ invokedMethod.hashCode() ^ Arrays.hashCode(parameterValues); } public void describeTo(Description description) { description.appendText(invokedObject.toString()); description.appendText("."); description.appendText(invokedMethod.getName()); description.appendValueList("(", ", ", ")", parameterValues); } public Object getInvokedObject() { return invokedObject; } public Method getInvokedMethod() { return invokedMethod; } public int getParameterCount() { return parameterValues.length; } public Object getParameter(int i) { return parameterValues[i]; } public Object[] getParametersAsArray() { return parameterValues.clone(); } public Object applyTo(Object target) throws Throwable { try { return invokedMethod.invoke(target, getParametersAsArray()); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } public void checkReturnTypeCompatibility(final Object value) { Class returnType = invokedMethod.getReturnType(); if (returnType == void.class) { failIfReturnTypeIsNotNull(value); } else if (value == null) { failIfReturnTypeIsPrimitive(); } else { Class valueType = value.getClass(); if (!isCompatible(returnType, valueType)) { reportTypeError(returnType, valueType); } } } private boolean isCompatible(Class returnType, Class valueType) { if (returnType.isPrimitive()) { // The reflection API doesn't reflect Java's auto-boxing. return isBoxedType(returnType, valueType); } return returnType.isAssignableFrom(valueType); } private boolean isBoxedType(Class primitiveType, Class referenceType) { return BOX_TYPES.get(primitiveType) == referenceType; } private void failIfReturnTypeIsNotNull(final Object result) { if (result != null) { throw new IllegalStateException("tried to return a value from a void method: " + result); } } private void failIfReturnTypeIsPrimitive() { Class returnType = invokedMethod.getReturnType(); if (returnType.isPrimitive()) { throw new IllegalStateException( "tried to return null value from method returning " + returnType.getName()); } } private void reportTypeError(Class returnType, Class valueType) { throw new IllegalStateException( "tried to return a " + valueType.getName() + " from a method that can only return a " + returnType.getName()); } public boolean isBuildingExpectation() { return ExpectationMode.BUILDING == mode; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/InvocationDispatcher.java000066400000000000000000000010111347002534600275230ustar00rootroot00000000000000package org.jmock.api; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; import org.jmock.internal.StateMachine; public interface InvocationDispatcher extends SelfDescribing, ExpectationCollector { StateMachine newStateMachine(String name); void add(Expectation expectation); void describeTo(Description description); void describeMismatch(Invocation invocation, Description description); boolean isSatisfied(); Object dispatch(Invocation invocation) throws Throwable; }jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/Invokable.java000066400000000000000000000013401347002534600253220ustar00rootroot00000000000000package org.jmock.api; /** * An object that can receive an {@link org.jmock.api.Invocation}. * * @author npryce */ public interface Invokable { /** * Performs an action in response to an invocation. * * @param invocation * The invocation to perform. * @return * The result of the invocation, if not throwing an exception. * Must return null if the invoked method has a void return type. * @throws Throwable * An exception to be thrown to the caller, if not returning a value. Any checked exception * thrown must be in the throws list of the invoked method. */ Object invoke(Invocation invocation) throws Throwable; } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/MockObjectNamingScheme.java000066400000000000000000000007161347002534600277150ustar00rootroot00000000000000package org.jmock.api; /** * Creates names for mock objects that have not explicitly been * given a name. * * @author npryce */ public interface MockObjectNamingScheme { /** * Derive a name for a mock object from the name of the given type. * * @param typeToMock * The type being mocked. * @return * The default name for a mock object of the given type. */ String defaultNameFor(Class typeToMock); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/ThreadingPolicy.java000066400000000000000000000002361347002534600265000ustar00rootroot00000000000000package org.jmock.api; public interface ThreadingPolicy { Invokable synchroniseAccessTo(Invokable mockObject); InvocationDispatcher dispatcher(); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/api/package.html000066400000000000000000000001621347002534600250270ustar00rootroot00000000000000

The stable API that is used to extend jMock at its published plug-in points.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/auto/000077500000000000000000000000001347002534600227465ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/auto/Auto.java000066400000000000000000000004261347002534600245230ustar00rootroot00000000000000package org.jmock.auto; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(FIELD) public @interface Auto { } jmock-library-2.12.0/jmock/src/main/java/org/jmock/auto/Mock.java000066400000000000000000000004271347002534600245050ustar00rootroot00000000000000package org.jmock.auto; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target(FIELD) public @interface Mock { } jmock-library-2.12.0/jmock/src/main/java/org/jmock/auto/internal/000077500000000000000000000000001347002534600245625ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/auto/internal/Mockomatic.java000066400000000000000000000045271347002534600275230ustar00rootroot00000000000000package org.jmock.auto.internal; import java.lang.reflect.Field; import java.util.List; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.States; import org.jmock.auto.Auto; import org.jmock.auto.Mock; import org.jmock.internal.AllDeclaredFields; public class Mockomatic { private final Mockery mockery; public Mockomatic(Mockery mockery) { this.mockery = mockery; } public void fillIn(Object object) { fillIn(object, AllDeclaredFields.in(object.getClass())); } public void fillIn(Object object, final List knownFields) { for (Field field : knownFields) { if (field.isAnnotationPresent(Mock.class)) { autoMock(object, field); } else if (field.isAnnotationPresent(Auto.class)) { autoInstantiate(object, field); } } } private void autoMock(Object object, Field field) { setAutoField(field, object, mockery.mock(field.getType(), field.getName()), "auto-mock field " + field.getName()); } private void autoInstantiate(Object object, Field field) { final Class type = field.getType(); if (type == States.class) { autoInstantiateStates(field, object); } else if (type == Sequence.class) { autoInstantiateSequence(field, object); } else { throw new IllegalStateException("cannot auto-instantiate field of type " + type.getName()); } } private void autoInstantiateStates(Field field, Object object) { setAutoField(field, object, mockery.states(field.getName()), "auto-instantiate States field " + field.getName()); } private void autoInstantiateSequence(Field field, Object object) { setAutoField(field, object, mockery.sequence(field.getName()), "auto-instantiate Sequence field " + field.getName()); } private void setAutoField(Field field, Object object, Object value, String description) { try { field.setAccessible(true); field.set(object, value); } catch (IllegalAccessException e) { throw new IllegalStateException("cannot " + description, e); } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/000077500000000000000000000000001347002534600236125ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/AllDeclaredFields.java000066400000000000000000000007351347002534600277450ustar00rootroot00000000000000package org.jmock.internal; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; public class AllDeclaredFields { public static List in(Class clazz) { final ArrayList fields = new ArrayList(); for (Class c = clazz; c != Object.class; c = c.getSuperclass()) { fields.addAll(asList(c.getDeclaredFields())); } return fields; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/CaptureControl.java000066400000000000000000000002001347002534600274110ustar00rootroot00000000000000package org.jmock.internal; public interface CaptureControl { Object captureExpectationTo(ExpectationCapture capture); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/Cardinality.java000066400000000000000000000045761347002534600267340ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; /** * The acceptable range of times an expectation may be invoked. * * @author smgf * @author nat */ public class Cardinality implements SelfDescribing { public static final Cardinality ALLOWING = atLeast(0); private final int required; private final int maximum; public Cardinality(final int required, final int maximum) { this.required = required; this.maximum = maximum; } public static Cardinality exactly(int count) { return between(count, count); } public static Cardinality atLeast(int required) { return between(required, Integer.MAX_VALUE); } public static Cardinality between(int required, int maximum) { return new Cardinality(required, maximum); } public static Cardinality atMost(int maximum) { return between(0, maximum); } public boolean isSatisfied(int invocationsSoFar) { return required <= invocationsSoFar; } public boolean allowsMoreInvocations(int invocationCount) { return invocationCount < maximum; } public void describeTo(Description description) { if (required == 0 && maximum == Integer.MAX_VALUE) { description.appendText("allowed"); } else { description.appendText("expected "); if (required == 0 && maximum == 0) { description.appendText("never"); } else if (required == 1 && maximum == 1) { description.appendText("once"); } else if (required == maximum) { description.appendText("exactly "); description.appendText(Formatting.times(required)); } else if (maximum == Integer.MAX_VALUE) { description.appendText("at least "); description.appendText(Formatting.times(required)); } else if (required == 0) { description.appendText("at most "); description.appendText(Formatting.times(maximum)); } else { description.appendText(Integer.toString(required)); description.appendText(" to "); description.appendText(Formatting.times(maximum)); } } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ChangeStateSideEffect.java000066400000000000000000000006701347002534600305700ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.Description; public class ChangeStateSideEffect implements SideEffect { private final State state; public ChangeStateSideEffect(State state) { this.state = state; } public void perform() { state.activate(); } public void describeTo(Description description) { description.appendText("then "); state.describeTo(description); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ExpectationBuilder.java000066400000000000000000000003401347002534600302440ustar00rootroot00000000000000package org.jmock.internal; import org.jmock.api.Action; import org.jmock.api.ExpectationCollector; public interface ExpectationBuilder { void buildExpectations(Action defaultAction, ExpectationCollector collector); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ExpectationCapture.java000066400000000000000000000002371347002534600302660ustar00rootroot00000000000000package org.jmock.internal; import org.jmock.api.Invocation; public interface ExpectationCapture { void createExpectationFrom(Invocation invocation); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/FakeObjectMethods.java000066400000000000000000000033631347002534600300030ustar00rootroot00000000000000package org.jmock.internal; import java.lang.reflect.Method; import java.util.Arrays; import org.jmock.api.Invocation; import org.jmock.api.Invokable; public abstract class FakeObjectMethods implements Invokable { private final Invokable next; public FakeObjectMethods(Invokable next) { this.next = next; } @Override public String toString() { return next.toString(); } public Object invoke(Invocation invocation) throws Throwable { Method method = invocation.getInvokedMethod(); if (isMethod(method, int.class, "hashCode")) { return fakeHashCode(invocation.getInvokedObject()); } else if (isMethod(method, String.class, "toString")) { return fakeToString(invocation.getInvokedObject()); } else if (isMethod(method, boolean.class, "equals", Object.class)) { return fakeEquals(invocation.getInvokedObject(), invocation.getParameter(0)); } else if (isMethod(method, void.class, "finalize")) { fakeFinalize(invocation.getInvokedObject()); return null; } else { return next.invoke(invocation); } } protected abstract int fakeHashCode(Object invokedObject); protected abstract String fakeToString(Object invokedObject); protected abstract boolean fakeEquals(Object invokedObject, Object other); protected abstract void fakeFinalize(Object invokedObject); private boolean isMethod(Method method, Class returnType, String name, Class... parameterTypes) { return method.getReturnType().equals(returnType) && method.getName().equals(name) && Arrays.equals(method.getParameterTypes(), parameterTypes); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/Formatting.java000066400000000000000000000002371347002534600265710ustar00rootroot00000000000000package org.jmock.internal; public class Formatting { public static String times(int i) { return i + " " + (i == 1 ? "time" : "times"); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/InStateOrderingConstraint.java000066400000000000000000000010461347002534600315640ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.Description; public class InStateOrderingConstraint implements OrderingConstraint { private final StatePredicate statePredicate; public InStateOrderingConstraint(StatePredicate statePredicate) { this.statePredicate = statePredicate; } public boolean allowsInvocationNow() { return statePredicate.isActive(); } public void describeTo(Description description) { description.appendText("when "); statePredicate.describeTo(description); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/InvocationDiverter.java000066400000000000000000000014661347002534600303020ustar00rootroot00000000000000package org.jmock.internal; import org.jmock.api.Invocation; import org.jmock.api.Invokable; public class InvocationDiverter implements Invokable { private final Class declaringType; private final T target; private final Invokable next; public InvocationDiverter(Class declaringType, T target, Invokable next) { this.declaringType = declaringType; this.target = target; this.next = next; } @Override public String toString() { return next.toString(); } public Object invoke(Invocation invocation) throws Throwable { if (invocation.getInvokedMethod().getDeclaringClass() == declaringType) { return invocation.applyTo(target); } else { return next.invoke(invocation); } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/InvocationExpectation.java000066400000000000000000000136021347002534600307740ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.core.IsAnything; import org.jmock.api.Action; import org.jmock.api.Expectation; import org.jmock.api.Invocation; import org.jmock.api.Invocation.ExpectationMode; import org.jmock.internal.matcher.MethodMatcher; import org.jmock.lib.action.VoidAction; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * An expectation of zero or more matching invocations. * * @author npryce * @author smgf */ public class InvocationExpectation implements Expectation { private static ParametersMatcher ANY_PARAMETERS = new AnyParametersMatcher(); private Cardinality cardinality = Cardinality.ALLOWING; private Matcher objectMatcher = IsAnything.anything(); private Matcher methodMatcher = IsAnything.anything(""); private boolean methodIsKnownToBeVoid = false; private ParametersMatcher parametersMatcher = ANY_PARAMETERS; private Action action = new VoidAction(); private boolean actionIsDefault = true; private List orderingConstraints = new ArrayList(); private List sideEffects = new ArrayList(); private int invocationCount = 0; public void setCardinality(Cardinality cardinality) { this.cardinality = cardinality; } public void setObjectMatcher(Matcher objectMatcher) { this.objectMatcher = objectMatcher; } public void setMethod(Method method) { this.methodMatcher = new MethodMatcher(method); this.methodIsKnownToBeVoid = method.getReturnType() == void.class; } public void setMethodMatcher(Matcher matcher) { this.methodMatcher = matcher; this.methodIsKnownToBeVoid = false; } public void setParametersMatcher(ParametersMatcher parametersMatcher) { this.parametersMatcher = parametersMatcher; } public void addOrderingConstraint(OrderingConstraint orderingConstraint) { orderingConstraints.add(orderingConstraint); } public void addSideEffect(SideEffect sideEffect) { sideEffects.add(sideEffect); } public void setAction(Action action) { this.action = action; this.actionIsDefault = false; } public void setDefaultAction(Action action) { this.action = action; this.actionIsDefault = true; } public void describeTo(Description description) { if (! isSatisfied()) { description.appendText("! "); } describeExpectation(description); } public void describeMismatch(Invocation invocation, Description description) { describeExpectation(description); final Object[] parameters = invocation.getParametersAsArray(); if (methodMatcher.matches(invocation.getInvokedMethod()) && parametersMatcher.isCompatibleWith(parameters)) { parametersMatcher.describeMismatch(parameters, description); } } private void describeExpectation(Description description) { describeMethod(description); parametersMatcher.describeTo(description); describeSideEffects(description); } private void describeMethod(Description description) { cardinality.describeTo(description); description.appendText(", "); if (invocationCount == 0) { description.appendText("never invoked"); } else { description.appendText("already invoked "); description.appendText(Formatting.times(invocationCount)); } description.appendText(": "); objectMatcher.describeTo(description); description.appendText("."); methodMatcher.describeTo(description); } private void describeSideEffects(Description description) { for (OrderingConstraint orderingConstraint : orderingConstraints) { description.appendText("; "); orderingConstraint.describeTo(description); } if (!shouldSuppressActionDescription()) { description.appendText("; "); action.describeTo(description); } for (SideEffect sideEffect : sideEffects) { description.appendText("; "); sideEffect.describeTo(description); } } private boolean shouldSuppressActionDescription() { return methodIsKnownToBeVoid && actionIsDefault; } public boolean isSatisfied() { return cardinality.isSatisfied(invocationCount); } public boolean allowsMoreInvocations() { return cardinality.allowsMoreInvocations(invocationCount); } public boolean matches(Invocation invocation) { return allowsMoreInvocations() && objectMatcher.matches(invocation.getInvokedObject()) && methodMatcher.matches(invocation.getInvokedMethod()) && parametersMatcher.matches(invocation.getParametersAsArray()) && isInCorrectOrder(); } private boolean isInCorrectOrder() { for (OrderingConstraint constraint : orderingConstraints) { if (!constraint.allowsInvocationNow()) return false; } return true; } public Object invoke(Invocation invocation) throws Throwable { invocationCount++; performSideEffects(); final Object result = action.invoke(new Invocation(ExpectationMode.ASSERTING, invocation)); invocation.checkReturnTypeCompatibility(result); return result; } private void performSideEffects() { for (SideEffect sideEffect : sideEffects) { sideEffect.perform(); } } private static class AnyParametersMatcher extends IsAnything implements ParametersMatcher { public AnyParametersMatcher() { super("()"); } public boolean isCompatibleWith(Object[] parameters) { return true; } }; } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/InvocationExpectationBuilder.java000066400000000000000000000107731347002534600323110ustar00rootroot00000000000000package org.jmock.internal; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.Matcher; import org.jmock.Sequence; import org.jmock.api.Action; import org.jmock.api.Expectation; import org.jmock.api.Invocation; import org.jmock.internal.matcher.MethodNameMatcher; import org.jmock.internal.matcher.MockObjectMatcher; import org.jmock.internal.matcher.AllParametersMatcher; import org.jmock.syntax.MethodClause; import org.jmock.syntax.ParametersClause; import org.jmock.syntax.ReceiverClause; public class InvocationExpectationBuilder implements ExpectationCapture, ReceiverClause, MethodClause, ParametersClause { private final InvocationExpectation expectation = new InvocationExpectation(); private boolean isFullySpecified = false; private boolean needsDefaultAction = true; private List> capturedParameterMatchers = new ArrayList>(); public Expectation toExpectation(Action defaultAction) { if (needsDefaultAction) { expectation.setDefaultAction(defaultAction); } return expectation; } public void setCardinality(Cardinality cardinality) { expectation.setCardinality(cardinality); } public void addParameterMatcher(Matcher matcher) { capturedParameterMatchers.add(matcher); } public void addOrderingConstraint(OrderingConstraint constraint) { expectation.addOrderingConstraint(constraint); } public void addInSequenceOrderingConstraint(Sequence sequence) { sequence.constrainAsNextInSequence(expectation); } public void setAction(Action action) { expectation.setAction(action); needsDefaultAction = false; } public void addSideEffect(SideEffect sideEffect) { expectation.addSideEffect(sideEffect); } private T captureExpectedObject(T mockObject) { if (!(mockObject instanceof CaptureControl)) { throw new IllegalArgumentException("can only set expectations on mock objects"); } expectation.setObjectMatcher(new MockObjectMatcher(mockObject)); isFullySpecified = true; Object capturingImposter = ((CaptureControl)mockObject).captureExpectationTo(this); return asMockedType(mockObject, capturingImposter); } // Damn you Java generics! Damn you to HELL! @SuppressWarnings("unchecked") private T asMockedType(@SuppressWarnings("unused") T mockObject, Object capturingImposter) { return (T) capturingImposter; } public void createExpectationFrom(Invocation invocation) { expectation.setMethod(invocation.getInvokedMethod()); if (capturedParameterMatchers.isEmpty()) { expectation.setParametersMatcher(new AllParametersMatcher(invocation.getParametersAsArray())); } else { checkParameterMatcherCount(invocation); expectation.setParametersMatcher(new AllParametersMatcher(capturedParameterMatchers)); } } private void checkParameterMatcherCount(Invocation invocation) { if (capturedParameterMatchers.size() != invocation.getParameterCount()) { throw new IllegalArgumentException("not all parameters were given explicit matchers: either all parameters must be specified by matchers or all must be specified by values, you cannot mix matchers and values"); } } public void checkWasFullySpecified() { if (!isFullySpecified) { throw new IllegalStateException("expectation was not fully specified"); } } /* * Syntactic sugar */ public T of(T mockObject) { return captureExpectedObject(mockObject); } public MethodClause of(Matcher objectMatcher) { expectation.setObjectMatcher(objectMatcher); isFullySpecified = true; return this; } public ParametersClause method(Matcher methodMatcher) { expectation.setMethodMatcher(methodMatcher); return this; } public ParametersClause method(String nameRegex) { return method(new MethodNameMatcher(nameRegex)); } public void with(Matcher... parameterMatchers) { expectation.setParametersMatcher(new AllParametersMatcher(Arrays.asList(parameterMatchers))); } public void withNoArguments() { with(); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/InvocationToExpectationTranslator.java000066400000000000000000000015161347002534600333520ustar00rootroot00000000000000package org.jmock.internal; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.api.Invocation.ExpectationMode; import org.jmock.api.Invokable; public class InvocationToExpectationTranslator implements Invokable { private final ExpectationCapture capture; private Action defaultAction; public InvocationToExpectationTranslator(ExpectationCapture capture, Action defaultAction) { this.capture = capture; this.defaultAction = defaultAction; } public Object invoke(Invocation invocation) throws Throwable { Invocation buildingInvocation = new Invocation(ExpectationMode.BUILDING,invocation); capture.createExpectationFrom(buildingInvocation); return defaultAction.invoke(buildingInvocation); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/NamedSequence.java000066400000000000000000000032131347002534600271710ustar00rootroot00000000000000package org.jmock.internal; import java.util.ArrayList; import java.util.List; import org.hamcrest.Description; import org.jmock.Sequence; import org.jmock.api.Expectation; /** * A sequence of expectations. * * Invocations can be constrained to occur in strict order defined by a sequence. * * @author nat */ public class NamedSequence implements Sequence { private final String name; private List elements = new ArrayList(); public NamedSequence(String name) { this.name = name; } @Override public String toString() { return name; } public void constrainAsNextInSequence(InvocationExpectation expectation) { int index = elements.size(); elements.add(expectation); expectation.addOrderingConstraint(new InSequenceOrderingConstraint(this, index)); } private boolean isSatisfiedToIndex(int index) { for (int i = 0; i < index; i++) { if (!elements.get(i).isSatisfied()) return false; } return true; } private static class InSequenceOrderingConstraint implements OrderingConstraint { private final NamedSequence sequence; private final int index; public InSequenceOrderingConstraint(NamedSequence sequence, int index) { this.sequence = sequence; this.index = index; } public boolean allowsInvocationNow() { return sequence.isSatisfiedToIndex(index); } public void describeTo(Description description) { description.appendText("in sequence ").appendText(sequence.name); } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ObjectMethodExpectationBouncer.java000066400000000000000000000016121347002534600325460ustar00rootroot00000000000000package org.jmock.internal; import org.jmock.api.Invokable; public class ObjectMethodExpectationBouncer extends FakeObjectMethods { public ObjectMethodExpectationBouncer(Invokable next) { super(next); } @Override protected boolean fakeEquals(Object invokedObject, Object other) { throw cannotDefineExpectation(); } @Override protected void fakeFinalize(Object invokedObject) { throw cannotDefineExpectation(); } @Override protected int fakeHashCode(Object invokedObject) { throw cannotDefineExpectation(); } @Override protected String fakeToString(Object invokedObject) { throw cannotDefineExpectation(); } private IllegalArgumentException cannotDefineExpectation() { return new IllegalArgumentException("you cannot define expectations for methods defined by the Object class"); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/OrderingConstraint.java000066400000000000000000000002441347002534600302730ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.SelfDescribing; public interface OrderingConstraint extends SelfDescribing { boolean allowsInvocationNow(); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ParametersMatcher.java000066400000000000000000000005641347002534600300710ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.Matcher; public interface ParametersMatcher extends Matcher { /** * Is this matcher likely to be relevant to the given parameters? * @param parameters The parameters to be matched * @return true iff the parameters may be relevant. */ boolean isCompatibleWith(Object[] parameters); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ProxiedObjectIdentity.java000066400000000000000000000012171347002534600307310ustar00rootroot00000000000000package org.jmock.internal; import org.jmock.api.Invokable; public class ProxiedObjectIdentity extends FakeObjectMethods { public ProxiedObjectIdentity(Invokable next) { super(next); } @Override protected void fakeFinalize(Object invokedObject) { } @Override protected boolean fakeEquals(Object invokedObject, Object other) { return other == invokedObject; } @Override protected String fakeToString(Object invokedObject) { return toString(); } @Override protected int fakeHashCode(Object invokedObject) { return System.identityHashCode(invokedObject); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/ReturnDefaultValueAction.java000066400000000000000000000112401347002534600313720ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.internal; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.lib.JavaReflectionImposteriser; import java.lang.reflect.Array; import java.util.*; import static java.lang.reflect.Modifier.isAbstract; /** * Returns a default value for the invoked method's result type. *
    *
  • Returns nothing from void methods.
  • *
  • Returns zero or false results for primitive types.
  • *
  • Returns zero length instances for arrays and strings.
  • *
  • Returns empty instances for collections and maps types in {@link java.util}.
  • *
  • Returns imposterised Null Objects for * types that can be imposterised by the action's {@link Imposteriser}.
  • *
  • Otherwise returns null.
  • *
* The default value can be overridden for specific types. * * @author Nat Pryce * @author Steve Freeman 2013 */ public class ReturnDefaultValueAction implements Action { private final static Class[] CONCRETE_COLLECTION_TYPES = { LinkedList.class, TreeSet.class, TreeMap.class }; private final Map, Object> resultValuesByType; private Imposteriser imposteriser; public ReturnDefaultValueAction(Imposteriser imposteriser, Map, Object> typeToResultValue) { this.imposteriser = imposteriser; this.resultValuesByType = typeToResultValue; } public ReturnDefaultValueAction(Imposteriser imposteriser) { this(imposteriser, createDefaultResults()); } public ReturnDefaultValueAction() { this(new JavaReflectionImposteriser()); } public void setImposteriser(Imposteriser newImposteriser) { this.imposteriser = newImposteriser; } public void describeTo(Description description) { description.appendText("returns a default value"); } public void addResult(Class resultType, Object resultValue) { resultValuesByType.put(resultType, resultValue); } public Object invoke(Invocation invocation) throws Throwable { final Class returnType = invocation.getInvokedMethod().getReturnType(); if(Object.class.equals(returnType) && invocation.isBuildingExpectation()) { return null; } if (resultValuesByType.containsKey(returnType)) { return resultValuesByType.get(returnType); } if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); } if (isCollectionOrMap(returnType)) { final Object instance = collectionOrMapInstanceFor(returnType); if (instance != null) return instance; } if (imposteriser.canImposterise(returnType) && !invocation.isBuildingExpectation()) { return imposteriser.imposterise(this, returnType); } return null; } private static Object collectionOrMapInstanceFor(Class returnType) throws Throwable { return cannotCreateNewInstance(returnType) ? instanceForCollectionType(returnType) : returnType.newInstance(); } private static Object instanceForCollectionType(Class type) throws Throwable { for (Class collectionType : CONCRETE_COLLECTION_TYPES) { if (type.isAssignableFrom(collectionType)) { return collectionType.newInstance(); } } return null; } private static boolean isCollectionOrMap(Class type) { return Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type); } private static boolean cannotCreateNewInstance(Class returnType) { return returnType.isInterface() || isAbstract(returnType.getModifiers()); } protected static Map, Object> createDefaultResults() { final HashMap, Object> result = new HashMap, Object>(); result.put(boolean.class, Boolean.FALSE); result.put(void.class, null); result.put(byte.class, (byte) 0); result.put(short.class, (short) 0); result.put(int.class, 0); result.put(long.class, 0L); result.put(char.class, '\0'); result.put(float.class, 0.0F); result.put(double.class, 0.0); result.put(Boolean.class, Boolean.FALSE); result.put(Byte.class, (byte) 0); result.put(Short.class, (short) 0); result.put(Integer.class, 0); result.put(Long.class, 0L); result.put(Character.class, '\0'); result.put(Float.class, 0.0F); result.put(Double.class, 0.0); result.put(String.class, ""); result.put(Object.class, new Object()); return result; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/SearchingClassLoader.java000066400000000000000000000047511347002534600305040ustar00rootroot00000000000000package org.jmock.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.lang.Thread.currentThread; public class SearchingClassLoader extends ClassLoader { private final ClassLoader nextToSearch; public SearchingClassLoader(ClassLoader parent, ClassLoader nextToSearch) { super(parent); this.nextToSearch = nextToSearch; } public static ClassLoader combine(ClassLoader... parentLoaders) { return combine(Arrays.asList(parentLoaders)); } public static ClassLoader combine(List parentLoaders) { ClassLoader loader = parentLoaders.get(parentLoaders.size()-1); for (int i = parentLoaders.size()-2; i >= 0; i--) { loader = new SearchingClassLoader(parentLoaders.get(i), loader); } return loader; } public static ClassLoader combineLoadersOf(Class... classes) { return combineLoadersOf(classes[0], classes); } public static ClassLoader combineLoadersOf(Class first, Class... others) { List loaders = new ArrayList(); addIfNewElement(loaders, first.getClassLoader()); for (Class c : others) { addIfNewElement(loaders, c.getClassLoader()); } // To support Eclipse Plug-in tests. // In an Eclipse plug-in, jMock itself will not be on the system class loader // but in the class loader of the plug-in. // // Note: I've been unable to reproduce the error in jMock's test suite. addIfNewElement(loaders, SearchingClassLoader.class.getClassLoader()); // To support the Maven Surefire plugin. // Note: I've been unable to reproduce the error in jMock's test suite. addIfNewElement(loaders, currentThread().getContextClassLoader()); addIfNewElement(loaders, ClassLoader.getSystemClassLoader()); return combine(loaders); } private static void addIfNewElement(List loaders, ClassLoader c) { if (c != null && !loaders.contains(c)) { loaders.add(c); } } @Override protected Class findClass(String name) throws ClassNotFoundException { if (nextToSearch != null) { return nextToSearch.loadClass(name); } else { return super.findClass(name); // will throw ClassNotFoundException } } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/SideEffect.java000066400000000000000000000005001347002534600264510ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.SelfDescribing; import org.jmock.api.Action; /** * An expectation has one {@link Action} but can have zero or more SideEffects * that are triggered before the Action. * * @author nat * */ public interface SideEffect extends SelfDescribing { void perform(); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/SingleThreadedPolicy.java000066400000000000000000000025521347002534600305230ustar00rootroot00000000000000package org.jmock.internal; import java.util.ConcurrentModificationException; import org.jmock.api.Invocation; import org.jmock.api.InvocationDispatcher; import org.jmock.api.Invokable; import org.jmock.api.ThreadingPolicy; import org.jmock.lib.concurrent.Synchroniser; import org.jmock.lib.concurrent.UnsynchronisedInvocationDispatcher; public class SingleThreadedPolicy implements ThreadingPolicy { private final Thread testThread; public SingleThreadedPolicy() { this.testThread = Thread.currentThread(); } public Invokable synchroniseAccessTo(final Invokable mockObject) { return new Invokable() { public Object invoke(Invocation invocation) throws Throwable { checkRunningOnTestThread(); return mockObject.invoke(invocation); } }; } private void checkRunningOnTestThread() { if (Thread.currentThread() != testThread) { reportError("the Mockery is not thread-safe: use a " + Synchroniser.class.getSimpleName() + " to ensure thread safety"); } } private void reportError(String error) { System.err.println(error); throw new ConcurrentModificationException(error); } public InvocationDispatcher dispatcher() { return new UnsynchronisedInvocationDispatcher(); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/State.java000066400000000000000000000001441347002534600255340ustar00rootroot00000000000000package org.jmock.internal; public interface State extends StatePredicate { void activate(); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/StateMachine.java000066400000000000000000000031731347002534600270260ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.Description; import org.hamcrest.StringDescription; import org.jmock.States; public class StateMachine implements States { private final String name; private String currentState = null; public StateMachine(String name) { this.name = name; } @Override public String toString() { return StringDescription.asString(this); } public States startsAs(String initialState) { become(initialState); return this; } public void become(String nextState) { currentState = nextState; } public State is(final String state) { return new State() { public void activate() { currentState = state; } public boolean isActive() { return state.equals(currentState); } public void describeTo(Description description) { description.appendText(name).appendText(" is ").appendText(state); } }; } public StatePredicate isNot(final String state) { return new StatePredicate() { public boolean isActive() { return !state.equals(currentState); } public void describeTo(Description description) { description.appendText(name).appendText(" is not ").appendText(state); } }; } public void describeTo(Description description) { description.appendText(name) .appendText(currentState == null ? " has no current state" : (" is " + currentState)); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/StatePredicate.java000066400000000000000000000002251347002534600273550ustar00rootroot00000000000000package org.jmock.internal; import org.hamcrest.SelfDescribing; public interface StatePredicate extends SelfDescribing { boolean isActive(); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/matcher/000077500000000000000000000000001347002534600252355ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/matcher/AllParametersMatcher.java000066400000000000000000000054501347002534600321440ustar00rootroot00000000000000package org.jmock.internal.matcher; import static java.util.Arrays.asList; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.core.IsEqual; import org.jmock.internal.ParametersMatcher; public class AllParametersMatcher extends TypeSafeDiagnosingMatcher implements ParametersMatcher { private final Matcher[] elementMatchers; public AllParametersMatcher(Object[] expectedValues) { this.elementMatchers = equalMatchersFor(expectedValues); } @SuppressWarnings("unchecked") public AllParametersMatcher(List> parameterMatchers) { this.elementMatchers = parameterMatchers.toArray(new Matcher[0]); } public boolean isCompatibleWith(Object[] parameters) { return elementMatchers.length == parameters.length; } @Override public boolean matchesSafely(Object[] parameters, Description mismatch) { return matchesNumberOfParameters(parameters, mismatch) && matchesParameters(parameters, mismatch); } private boolean matchesNumberOfParameters(Object[] parameters, Description mismatch) { if (elementMatchers.length != parameters.length) { mismatch.appendText("wrong number of parameters: ") .appendValue(parameters); return false; } return true; } private boolean matchesParameters(Object[] parameters, Description mismatch) { boolean result = true; for (int i = 0; i < parameters.length; i++) { result &= matchesParameter(parameters[i], elementMatchers[i], mismatch, i); } return result; } private boolean matchesParameter(final Object value, final Matcher matcher, Description mismatch, int index) { mismatch.appendText("\n parameter " + index + " "); final boolean parameterMatches = matcher.matches(value); if (parameterMatches) { mismatch.appendText("matched: ").appendDescriptionOf(matcher); } else { mismatch.appendText("did not match: ") .appendDescriptionOf(matcher) .appendText(", because "); matcher.describeMismatch(value, mismatch); } return parameterMatches; } public void describeTo(Description description) { description.appendList("(", ", ",")", asList(elementMatchers)); } @SuppressWarnings("unchecked") private static Matcher[] equalMatchersFor(Object[] expectedValues) { Matcher[] matchers = new Matcher[expectedValues.length]; for (int i = 0; i < expectedValues.length; i++) { matchers[i] = new IsEqual(expectedValues[i]); } return matchers; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/matcher/MethodMatcher.java000066400000000000000000000014331347002534600306250ustar00rootroot00000000000000package org.jmock.internal.matcher; import java.lang.reflect.Method; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class MethodMatcher extends TypeSafeMatcher { private Method expectedMethod; public MethodMatcher(Method expectedMethod) { super(Method.class); this.expectedMethod = expectedMethod; } @Override public boolean matchesSafely(Method m) { return expectedMethod.equals(m); } @Override protected void describeMismatchSafely(Method m, Description mismatchDescription) { mismatchDescription.appendText("was ").appendText(m.getName()); } public void describeTo(Description description) { description.appendText(expectedMethod.getName()); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/matcher/MethodNameMatcher.java000066400000000000000000000015151347002534600314270ustar00rootroot00000000000000/** * */ package org.jmock.internal.matcher; import java.lang.reflect.Method; import java.util.regex.Pattern; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class MethodNameMatcher extends TypeSafeMatcher { Pattern namePattern; public MethodNameMatcher(String nameRegex) { namePattern = Pattern.compile(nameRegex); } @Override public boolean matchesSafely(Method method) { return namePattern.matcher(method.getName()).matches(); } @Override protected void describeMismatchSafely(Method item, Description mismatchDescription) { mismatchDescription.appendText("was method ").appendText(item.getName()); } public void describeTo(Description description) { description.appendText(namePattern.toString()); } }jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/matcher/MockObjectMatcher.java000066400000000000000000000007571347002534600314350ustar00rootroot00000000000000package org.jmock.internal.matcher; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; public class MockObjectMatcher extends BaseMatcher { private Object mockObject; public MockObjectMatcher(Object mockObject) { this.mockObject = mockObject; } public boolean matches(Object o) { return o == mockObject; } public void describeTo(Description description) { description.appendText(mockObject.toString()); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/matcher/ParametersMatcher.java000066400000000000000000000020111347002534600315010ustar00rootroot00000000000000package org.jmock.internal.matcher; import java.util.List; import org.hamcrest.Matcher; import org.hamcrest.collection.IsArray; import org.hamcrest.core.IsEqual; public class ParametersMatcher extends IsArray { public ParametersMatcher(Object[] expectedValues) { super(equalMatchersFor(expectedValues)); } @SuppressWarnings("unchecked") private static Matcher[] equalMatchersFor(Object[] expectedValues) { Matcher[] matchers = new Matcher[expectedValues.length]; for (int i = 0; i < expectedValues.length; i++) { matchers[i] = new IsEqual(expectedValues[i]); } return matchers; } @SuppressWarnings("unchecked") public ParametersMatcher(List> parameterMatchers) { super(parameterMatchers.toArray(new Matcher[0])); } @Override protected String descriptionStart() { return "("; } @Override protected String descriptionEnd() { return ")"; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/internal/package.html000066400000000000000000000002751347002534600260770ustar00rootroot00000000000000

This package contains internal implementation details. There are no guarantees given about the stability of these APIs between versions.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/000077500000000000000000000000001347002534600225445ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/AssertionErrorTranslator.java000066400000000000000000000013121347002534600304370ustar00rootroot00000000000000package org.jmock.lib; import org.hamcrest.StringDescription; import org.jmock.api.ExpectationError; import org.jmock.api.ExpectationErrorTranslator; /** * Translates {@link org.jmock.api.ExpectationError}s into * {@link java.lang.AssertionError}s that several * test frameworks, including JUnit 4 and TestNG, use to report * errors. * * @author npryce * */ public class AssertionErrorTranslator implements ExpectationErrorTranslator { public static final AssertionErrorTranslator INSTANCE = new AssertionErrorTranslator(); public Error translate(ExpectationError e) { return new AssertionError(StringDescription.toString(e)); } private AssertionErrorTranslator() {} } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/CamelCaseNamingScheme.java000066400000000000000000000025451347002534600275110ustar00rootroot00000000000000package org.jmock.lib; import org.jmock.api.MockObjectNamingScheme; /** * A naming scheme in which the implicit name for a mock object is * the mocked type's name with the first character in lower case. * E.g. A mock object of type HelloWorld would be named "helloWorld". * Initial acronyms are completely lowercased. For example, the type * HTTPClient would be named httpClient. * * This is the naming scheme used by default. * * @author npryce */ public class CamelCaseNamingScheme implements MockObjectNamingScheme { public static final CamelCaseNamingScheme INSTANCE = new CamelCaseNamingScheme(); public String defaultNameFor(Class typeToMock) { String simpleName = typeToMock.getSimpleName(); int lci = indexOfFirstLowerCaseLetter(simpleName); if (lci == 0) { return simpleName; } int capsEnd = (lci == 1 || lci == simpleName.length()) ? lci : lci - 1; String caps = simpleName.substring(0, capsEnd); String rest = simpleName.substring(capsEnd); return caps.toLowerCase() + rest; } private int indexOfFirstLowerCaseLetter(String simpleName) { int i = 0; while (i < simpleName.length() && !Character.isLowerCase(simpleName.charAt(i))) { i++; } return i; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/CurrentStateMatcher.java000066400000000000000000000026171347002534600273440ustar00rootroot00000000000000package org.jmock.lib; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.jmock.States; public class CurrentStateMatcher extends TypeSafeMatcher { private final String stateName; private final boolean expected; public CurrentStateMatcher(String stateName, boolean expected) { this.expected = expected; this.stateName = stateName; } @Override public boolean matchesSafely(States stateMachine) { return stateMachine.is(stateName).isActive() == expected; } @Override protected void describeMismatchSafely(States stateMachine, Description mismatchDescription) { mismatchDescription.appendText("was "); if (!stateMachine.is(stateName).isActive()) { mismatchDescription.appendText("not "); } mismatchDescription.appendText(stateName); } public void describeTo(Description description) { description.appendText("a state machine that ") .appendText(expected ? "is " : "is not ") .appendText(stateName); } public static Matcher isCurrently(String stateName) { return new CurrentStateMatcher(stateName, true); } public static Matcher isNotCurrently(String stateName) { return new CurrentStateMatcher(stateName, false); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/IdentityExpectationErrorTranslator.java000066400000000000000000000011511347002534600324660ustar00rootroot00000000000000package org.jmock.lib; import org.jmock.api.ExpectationError; import org.jmock.api.ExpectationErrorTranslator; /** * An {@link ExpectationErrorTranslator} that doesn't do any translation. * It returns the {@link ExpectationError} it is given. * * @author nat * */ public class IdentityExpectationErrorTranslator implements ExpectationErrorTranslator { public static final IdentityExpectationErrorTranslator INSTANCE = new IdentityExpectationErrorTranslator(); private IdentityExpectationErrorTranslator() {} public Error translate(ExpectationError e) { return e; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/JavaReflectionImposteriser.java000066400000000000000000000032261347002534600307140ustar00rootroot00000000000000package org.jmock.lib; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.api.Invocation.ExpectationMode; import org.jmock.api.Invokable; import org.jmock.internal.SearchingClassLoader; /** * An {@link org.jmock.api.Imposteriser} that uses the * {@link java.lang.reflect.Proxy} class of the Java Reflection API. * * @author npryce * */ public class JavaReflectionImposteriser implements Imposteriser { public static final Imposteriser INSTANCE = new JavaReflectionImposteriser(); public boolean canImposterise(Class type) { return type.isInterface(); } @SuppressWarnings("unchecked") public T imposterise(final Invokable mockObject, Class mockedType, Class... ancilliaryTypes) { final Class[] proxiedClasses = prepend(mockedType, ancilliaryTypes); final ClassLoader classLoader = SearchingClassLoader.combineLoadersOf(proxiedClasses); return (T)Proxy.newProxyInstance(classLoader, proxiedClasses, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return mockObject.invoke(new Invocation(ExpectationMode.LEGACY, proxy, method, args)); } }); } private Class[] prepend(Class first, Class... rest) { Class[] proxiedClasses = new Class[rest.length+1]; proxiedClasses[0] = first; System.arraycopy(rest, 0, proxiedClasses, 1, rest.length); return proxiedClasses; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/LastWordNamingScheme.java000066400000000000000000000037431347002534600274340ustar00rootroot00000000000000package org.jmock.lib; import static java.lang.Character.isLowerCase; import static java.lang.Character.isUpperCase; import static java.lang.Math.max; import org.jmock.api.MockObjectNamingScheme; /** * A naming scheme in which the implicit name for a mock object is * the last word of the mocked type's name in lower case. * E.g. A mock object of type HelloWorld would be named "world". * If the type name is an acronym it is completely lowercased. * For example, the type URL would be named "url". Digits and other * non-letter characters are left on the end of the word. For * example, the type NMEA0183 would be named "nmea0183". * * @author npryce */ public class LastWordNamingScheme implements MockObjectNamingScheme { public static MockObjectNamingScheme INSTANCE = new LastWordNamingScheme(); public String defaultNameFor(Class typeToMock) { String simpleName = typeToMock.getSimpleName(); int wordEnd = indexOfLastLetter(simpleName); int start; if (isUpperCase(simpleName.charAt(wordEnd))) { start = indexOfLastLowerCaseChar(simpleName, wordEnd)+1; } else { start = indexOfLastUpperCaseChar(simpleName, wordEnd); } return simpleName.substring(max(0,start)).toLowerCase(); } private int indexOfLastLetter(String simpleName) { int i = simpleName.length()-1; while (i > 0 && !Character.isLetter(simpleName.charAt(i))) { i--; } return i; } private int indexOfLastUpperCaseChar(String simpleName, int wordEnd) { int i = wordEnd; while (i >= 0 && isLowerCase(simpleName.charAt(i))) { i--; } return i; } private int indexOfLastLowerCaseChar(String simpleName, int wordEnd) { int i = wordEnd; while (i >= 0 && isUpperCase(simpleName.charAt(i))) { i--; } return i; } private LastWordNamingScheme() {} } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/RetroNamingScheme.java000066400000000000000000000012361347002534600267630ustar00rootroot00000000000000package org.jmock.lib; import org.jmock.api.MockObjectNamingScheme; /** * A naming scheme in which the implicit name for a mock object is * the mocked type's name prepend with "mock". * * E.g. A mock object of type HelloWorld would be called "mockHelloWorld". * * This was the naming scheme used at Connextra and in many early examples * of TDD with mock objects. * * @author npryce * */ public class RetroNamingScheme implements MockObjectNamingScheme { public static final RetroNamingScheme INSTANCE = new RetroNamingScheme(); public String defaultNameFor(Class typeToMock) { return "mock" + typeToMock.getSimpleName(); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/000077500000000000000000000000001347002534600240215ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/ActionSequence.java000066400000000000000000000020751347002534600275760ustar00rootroot00000000000000/* Copyright (c) 2000-2007 jMock.org */ package org.jmock.lib.action; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.ExpectationError; import org.jmock.api.Invocation; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Returns the next of a sequence of elements each time it is invoked. * * @author nat * */ public class ActionSequence implements Action { List actions; Iterator iterator; public ActionSequence(Action... actions) { this.actions = new ArrayList(Arrays.asList(actions)); this.iterator = this.actions.iterator(); } public Object invoke(Invocation invocation) throws Throwable { if (iterator.hasNext()) { return iterator.next().invoke(invocation); } throw ExpectationError.unexpected("no more actions available", invocation); } public void describeTo(Description description) { description.appendList("", ", and then ", "", actions); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/CustomAction.java000066400000000000000000000011401347002534600272700ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.lib.action; import org.hamcrest.Description; import org.jmock.api.Action; /** * A partial implementation of the {@link Action} interface that makes it convenient * to implement application-specific actions with inline anonymous classes. */ public abstract class CustomAction implements Action { private String description; public CustomAction(String description) { this.description = description; } public void describeTo(Description description) { description.appendText(this.description); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/DoAllAction.java000066400000000000000000000014671347002534600270250ustar00rootroot00000000000000package org.jmock.lib.action; import java.util.Arrays; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; /** * Performs multiple actions every time it is invoked. * * @author nat * */ public class DoAllAction implements Action { private final Action[] actions; public DoAllAction(Action... actions) { this.actions = actions.clone(); } public Object invoke(Invocation invocation) throws Throwable { Object result = null; for (int i = 0; i < actions.length; i++) { result = actions[i].invoke(invocation); } return result; } public void describeTo(Description description) { description.appendList("do all of ", ", ", "", Arrays.asList(actions)); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/ReturnEnumerationAction.java000066400000000000000000000016561347002534600315200ustar00rootroot00000000000000package org.jmock.lib.action; import static java.util.Collections.enumeration; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; /** * Returns an {@link Enumeration} over a collection. * * @author nat */ public class ReturnEnumerationAction implements Action { private Collection collection; public ReturnEnumerationAction(Collection collection) { this.collection = collection; } public ReturnEnumerationAction(Object... array) { this.collection = Arrays.asList(array); } public Enumeration invoke(Invocation invocation) throws Throwable { return enumeration(collection); } public void describeTo(Description description) { description.appendValueList("return enumeration over ", ", ", "", collection); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/ReturnIteratorAction.java000066400000000000000000000015451347002534600310200ustar00rootroot00000000000000package org.jmock.lib.action; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; /** * Returns an {@link Iterator} over a collection. * * @author nat */ public class ReturnIteratorAction implements Action { private Collection collection; public ReturnIteratorAction(Collection collection) { this.collection = collection; } public ReturnIteratorAction(Object... array) { this.collection = Arrays.asList(array); } public Iterator invoke(Invocation invocation) throws Throwable { return collection.iterator(); } public void describeTo(Description description) { description.appendValueList("return iterator over ", ", ", "", collection); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/ReturnValueAction.java000066400000000000000000000011611347002534600302750ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.lib.action; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; /** * Returns a value. * * @author nat * */ public class ReturnValueAction implements Action { private Object result; public ReturnValueAction(Object result) { this.result = result; } public Object invoke(Invocation invocation) throws Throwable { return result; } public void describeTo(Description description) { description.appendText("returns "); description.appendValue(result); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/ThrowAction.java000066400000000000000000000036621347002534600271340ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.lib.action; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; /** * Throws an exception. * * @author nat * */ public class ThrowAction implements Action { private Throwable throwable; public ThrowAction(Throwable throwable) { this.throwable = throwable; } public Object invoke(Invocation invocation) throws Throwable { if (isThrowingCheckedException()) { checkTypeCompatiblity(invocation.getInvokedMethod().getExceptionTypes()); } throwable.fillInStackTrace(); throw throwable; } public void describeTo(Description description) { description.appendText("throws "); description.appendValue(throwable); } private void checkTypeCompatiblity(Class[] allowedExceptionTypes) { for (int i = 0; i < allowedExceptionTypes.length; i++) { if (allowedExceptionTypes[i].isInstance(throwable)) return; } reportIncompatibleCheckedException(allowedExceptionTypes); } private void reportIncompatibleCheckedException(Class[] allowedTypes) { StringBuffer message = new StringBuffer(); message.append("tried to throw a "); message.append(throwable.getClass().getName()); message.append(" from a method that throws "); if (allowedTypes.length == 0) { message.append("no exceptions"); } else { for (int i = 0; i < allowedTypes.length; i++) { if (i > 0) message.append(","); message.append(allowedTypes[i].getName()); } } throw new IllegalStateException(message.toString()); } private boolean isThrowingCheckedException() { return !(throwable instanceof RuntimeException || throwable instanceof Error); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/VoidAction.java000066400000000000000000000010151347002534600267200ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.lib.action; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; /** * Returns nothing from a void method. */ public class VoidAction implements Action { public static final VoidAction INSTANCE = new VoidAction(); public Object invoke(Invocation invocation) throws Throwable { return null; } public void describeTo(Description description) { description.appendText("is void"); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/action/package.html000066400000000000000000000001341347002534600263000ustar00rootroot00000000000000

Actions that fake the behaviour of mocked invocations.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/000077500000000000000000000000001347002534600247265ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/Blitzer.java000066400000000000000000000043271347002534600272120ustar00rootroot00000000000000package org.jmock.lib.concurrent; import java.util.concurrent.*; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * A class that "blitzes" an object by calling it many times, from multiple * threads. Used for stress-testing synchronisation. * * @author nat */ public class Blitzer { /** * The default number of threads to run concurrently. */ public static final int DEFAULT_THREAD_COUNT = 2; private final ExecutorService executorService; private final int actionCount; public Blitzer(int actionCount) { this(actionCount, DEFAULT_THREAD_COUNT); } public Blitzer(int actionCount, int threadCount) { this(actionCount, threadCount, Executors.defaultThreadFactory()); } public Blitzer(int actionCount, int threadCount, ThreadFactory threadFactory) { this.actionCount = actionCount; this.executorService = Executors.newFixedThreadPool(threadCount, threadFactory); } public Blitzer(int actionCount, ExecutorService executorService) { this.actionCount = actionCount; this.executorService = executorService; } public int totalActionCount() { return actionCount; } public void blitz(final Runnable action) throws InterruptedException { spawnThreads(action).await(); } public void blitz(long timeoutMs, final Runnable action) throws InterruptedException, TimeoutException { if (!spawnThreads(action).await(timeoutMs, MILLISECONDS)) { throw new TimeoutException("timed out waiting for blitzed actions to complete successfully"); } } private CountDownLatch spawnThreads(final Runnable action) { final CountDownLatch finished = new CountDownLatch(actionCount); for (int i = 0; i < actionCount; i++) { executorService.execute(new Runnable() { public void run() { try { action.run(); } finally { finished.countDown(); } } }); } return finished; } public void shutdown() { executorService.shutdown(); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/DeterministicExecutor.java000066400000000000000000000033441347002534600321170ustar00rootroot00000000000000package org.jmock.lib.concurrent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; /** * An {@link Executor} that executes commands on the thread that calls * {@link #runPendingCommands() runPendingCommands} or {@link #runUntilIdle() runUntilIdle}. * This is useful when using Mock Objects to test code that spawns background tasks. * * @author nat */ public class DeterministicExecutor implements Executor { private List commands = new ArrayList(); public DeterministicExecutor() { super(); } /** * Returns whether this executor is idle -- has no pending background tasks waiting to be run. * * @return true if there are no background tasks to be run, false otherwise. * @see #runPendingCommands() * @see #runUntilIdle() */ public boolean isIdle() { return commands.isEmpty(); } /** * Runs all commands that are currently pending. If those commands also * schedule commands for execution, the scheduled commands will not * be executed until the next call to {@link #runPendingCommands()} or * {@link #runUntilIdle()}. */ public void runPendingCommands() { List commandsToRun = commands; commands = new ArrayList(); for (Runnable command: commandsToRun) { command.run(); } } /** * Runs executed commands until there are no commands pending execution, but * does not tick time forward. */ public void runUntilIdle() { while (!isIdle()) { runPendingCommands(); } } public void execute(Runnable command) { commands.add(command); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/DeterministicScheduler.java000066400000000000000000000214331347002534600322360ustar00rootroot00000000000000package org.jmock.lib.concurrent; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jmock.lib.concurrent.internal.DeltaQueue; /** * A {@link ScheduledExecutorService} that executes commands on the thread that calls * {@link #runNextPendingCommand() runNextPendingCommand}, {@link #runUntilIdle() runUntilIdle} or * {@link #tick(long, TimeUnit) tick}. Objects of this class can also be used * as {@link Executor}s or {@link ExecutorService}s if you just want to control background execution * and don't need to schedule commands, but it may be simpler to use a {@link DeterministicExecutor}. * * @author nat */ public class DeterministicScheduler implements ScheduledExecutorService { private final DeltaQueue> deltaQueue = new DeltaQueue>(); /** * Runs time forwards by a given duration, executing any commands scheduled for * execution during that time period, and any background tasks spawned by the * scheduled tasks. Therefore, when a call to tick returns, the executor * will be idle. * * @param duration * @param timeUnit */ public void tick(long duration, TimeUnit timeUnit) { long remaining = toTicks(duration, timeUnit); do { remaining = deltaQueue.tick(remaining); runUntilIdle(); } while (deltaQueue.isNotEmpty() && remaining > 0); } /** * Runs all commands scheduled to be executed immediately but does * not tick time forward. */ public void runUntilIdle() { while (!isIdle()) { runNextPendingCommand(); } } /** * Runs the next command scheduled to be executed immediately. */ public void runNextPendingCommand() { ScheduledTask scheduledTask = deltaQueue.pop(); scheduledTask.run(); if (!scheduledTask.isCancelled() && scheduledTask.repeats()) { deltaQueue.add(scheduledTask.repeatDelay, scheduledTask); } } /** * Reports whether scheduler is "idle": has no commands pending immediate execution. * * @return true if there are no commands pending immediate execution, * false if there are commands pending immediate execution. */ public boolean isIdle() { return deltaQueue.isEmpty() || deltaQueue.delay() > 0; } public void execute(Runnable command) { schedule(command, 0, TimeUnit.SECONDS); } public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { ScheduledTask task = new ScheduledTask(command); deltaQueue.add(toTicks(delay, unit), task); return task; } public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { ScheduledTask task = new ScheduledTask(callable); deltaQueue.add(toTicks(delay, unit), task); return task; } public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return scheduleWithFixedDelay(command, initialDelay, period, unit); } public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { ScheduledTask task = new ScheduledTask(toTicks(delay, unit), command); deltaQueue.add(toTicks(initialDelay, unit), task); return task; } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { throw blockingOperationsNotSupported(); } public List> invokeAll(Collection> tasks) throws InterruptedException { throw blockingOperationsNotSupported(); } public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { throw blockingOperationsNotSupported(); } public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { throw blockingOperationsNotSupported(); } public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw blockingOperationsNotSupported(); } public boolean isShutdown() { throw shutdownNotSupported(); } public boolean isTerminated() { throw shutdownNotSupported(); } public void shutdown() { throw shutdownNotSupported(); } public List shutdownNow() { throw shutdownNotSupported(); } public Future submit(Callable callable) { return schedule(callable, 0, TimeUnit.SECONDS); } public Future submit(Runnable command) { return submit(command, null); } public Future submit(Runnable command, T result) { return submit(new CallableRunnableAdapter(command, result)); } private final class CallableRunnableAdapter implements Callable { private final Runnable runnable; private final T result; public CallableRunnableAdapter(Runnable runnable, T result) { this.runnable = runnable; this.result = result; } @Override public String toString() { return runnable.toString(); } public T call() throws Exception { runnable.run(); return result; } } private final class ScheduledTask implements ScheduledFuture, Runnable { public final long repeatDelay; public final Callable command; private boolean isCancelled = false; private boolean isDone = false; private T futureResult; private Exception failure = null; public ScheduledTask(Callable command) { this.repeatDelay = -1; this.command = command; } public ScheduledTask(Runnable command) { this(-1, command); } public ScheduledTask(long repeatDelay, Runnable command) { this.repeatDelay = repeatDelay; this.command = new CallableRunnableAdapter(command, null); } @Override public String toString() { return command.toString() + " repeatDelay=" + repeatDelay; } public boolean repeats() { return repeatDelay >= 0; } public long getDelay(TimeUnit unit) { return unit.convert(deltaQueue.delay(this), TimeUnit.MILLISECONDS); } public int compareTo(Delayed o) { throw new UnsupportedOperationException("not supported"); } public boolean cancel(boolean mayInterruptIfRunning) { isCancelled = true; return deltaQueue.remove(this); } public T get() throws InterruptedException, ExecutionException { if (!isDone) { throw blockingOperationsNotSupported(); } if (failure != null) { throw new ExecutionException(failure); } return futureResult; } public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } public boolean isCancelled() { return isCancelled; } public boolean isDone() { return isDone; } public void run() { try { futureResult = command.call(); } catch (Exception e) { failure = e; } isDone = true; } } private long toTicks(long duration, TimeUnit timeUnit) { return TimeUnit.MILLISECONDS.convert(duration, timeUnit); } private UnsupportedSynchronousOperationException blockingOperationsNotSupported() { return new UnsupportedSynchronousOperationException("cannot perform blocking wait on a task scheduled on a " + DeterministicScheduler.class.getName()); } private UnsupportedOperationException shutdownNotSupported() { return new UnsupportedOperationException("shutdown not supported"); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/Synchroniser.java000066400000000000000000000066711347002534600302710ustar00rootroot00000000000000package org.jmock.lib.concurrent; import static org.hamcrest.StringDescription.asString; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeoutException; import org.jmock.api.Expectation; import org.jmock.api.Invocation; import org.jmock.api.InvocationDispatcher; import org.jmock.api.Invokable; import org.jmock.api.ThreadingPolicy; import org.jmock.internal.StateMachine; import org.jmock.internal.StatePredicate; import org.jmock.lib.concurrent.internal.FixedTimeout; import org.jmock.lib.concurrent.internal.InfiniteTimeout; import org.jmock.lib.concurrent.internal.Timeout; /** * A ThreadingPolicy that makes the Mockery thread-safe and helps tests * synchronise with background threads. * * @author Nat Pryce * @author olibye */ public class Synchroniser implements ThreadingPolicy { private final Object sync = new Object(); private Error firstError = null; private InvocationDispatcher invocationDispatcher; public Synchroniser() { invocationDispatcher = new UnsynchronisedInvocationDispatcher( new CopyOnWriteArrayList(), new CopyOnWriteArrayList()); } public Synchroniser(InvocationDispatcher dispatcher) { invocationDispatcher = dispatcher; } /** * Waits for a StatePredicate to become active. * * Warning: this will wait forever unless the test itself has a timeout. * * @param p * the StatePredicate to wait for * @throws InterruptedException */ public void waitUntil(StatePredicate p) throws InterruptedException { waitUntil(p, new InfiniteTimeout()); } /** * Waits up to a timeout for a StatePredicate to become active. Fails the test * if the timeout expires. * * @param p the StatePredicate to wait for * @param timeoutMs * the timeout in milliseconds * @throws InterruptedException */ public void waitUntil(StatePredicate p, long timeoutMs) throws InterruptedException { waitUntil(p, new FixedTimeout(timeoutMs)); } private void waitUntil(StatePredicate p, Timeout timeout) throws InterruptedException { synchronized (sync) { while (!p.isActive()) { try { sync.wait(timeout.timeRemaining()); } catch (TimeoutException e) { if (firstError != null) { throw firstError; } else { throw new AssertionError("timed out waiting for " + asString(p)); } } } } } public Invokable synchroniseAccessTo(final Invokable mockObject) { return new Invokable() { public Object invoke(Invocation invocation) throws Throwable { return synchroniseInvocation(mockObject, invocation); } }; } private Object synchroniseInvocation(Invokable mockObject, Invocation invocation) throws Throwable { synchronized (sync) { try { return mockObject.invoke(invocation); } catch (Error e) { if (firstError == null) { firstError = e; } throw e; } finally { sync.notifyAll(); } } } public InvocationDispatcher dispatcher() { return invocationDispatcher; } } SynchronisingInvocationDispatcherWrapper.java000066400000000000000000000025261347002534600357560ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrentpackage org.jmock.lib.concurrent; import org.hamcrest.Description; import org.jmock.api.Expectation; import org.jmock.api.Invocation; import org.jmock.api.InvocationDispatcher; import org.jmock.internal.StateMachine; /** * I synchronise my delegate. * This serialises access to the internal Expectation and StateMachine collections. * @author oliverbye * */ public class SynchronisingInvocationDispatcherWrapper implements InvocationDispatcher { private final InvocationDispatcher delegate; public SynchronisingInvocationDispatcherWrapper(InvocationDispatcher dispatcher) { delegate = dispatcher; } public synchronized StateMachine newStateMachine(String name) { return delegate.newStateMachine(name); } public synchronized void add(Expectation expectation) { delegate.add(expectation); } public synchronized void describeTo(Description description) { delegate.describeTo(description); } public synchronized void describeMismatch(Invocation invocation, Description description) { delegate.describeMismatch(invocation, description); } public synchronized boolean isSatisfied() { return delegate.isSatisfied(); } public synchronized Object dispatch(Invocation invocation) throws Throwable { return delegate.dispatch(invocation); } } UnsupportedSynchronousOperationException.java000066400000000000000000000006051347002534600360560ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrentpackage org.jmock.lib.concurrent; /** * Thrown to report that a {@link DeterministicScheduler} has been asked to perform * a blocking wait, which is not supported. * * @author nat * */ public class UnsupportedSynchronousOperationException extends UnsupportedOperationException { public UnsupportedSynchronousOperationException(String message) { super(message); } } UnsynchronisedInvocationDispatcher.java000066400000000000000000000105451347002534600345730ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrentpackage org.jmock.lib.concurrent; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.hamcrest.Description; import org.hamcrest.SelfDescribing; import org.jmock.api.Expectation; import org.jmock.api.ExpectationError; import org.jmock.api.Invocation; import org.jmock.api.InvocationDispatcher; import org.jmock.internal.StateMachine; public class UnsynchronisedInvocationDispatcher implements InvocationDispatcher { private final Collection expectations; private final Collection stateMachines; public UnsynchronisedInvocationDispatcher() { expectations = new ArrayList(); stateMachines = new ArrayList(); } public UnsynchronisedInvocationDispatcher(Collection theExpectations, Collection theStateMachines) { expectations = theExpectations; stateMachines = theStateMachines; } /* (non-Javadoc) * @see org.jmock.internal.InvocationDispatcher#newStateMachine(java.lang.String) */ public StateMachine newStateMachine(String name) { StateMachine stateMachine = new StateMachine(name); stateMachines.add(stateMachine); return stateMachine; } /* (non-Javadoc) * @see org.jmock.internal.InvocationDispatcher#add(org.jmock.api.Expectation) */ public void add(Expectation expectation) { expectations.add(expectation); } /* (non-Javadoc) * @see org.jmock.internal.InvocationDispatcher#describeTo(org.hamcrest.Description) */ public void describeTo(Description description) { describe(description, expectations); } /* (non-Javadoc) * @see org.jmock.internal.InvocationDispatcher#describeMismatch(org.jmock.api.Invocation, org.hamcrest.Description) */ public void describeMismatch(Invocation invocation, Description description) { describe(description, describedWith(expectations, invocation)); } private Iterable describedWith(Iterable expectations, final Invocation invocation) { final Iterator iterator = expectations.iterator(); return new Iterable() { public Iterator iterator() { return new Iterator() { public boolean hasNext() { return iterator.hasNext(); } public SelfDescribing next() { return new SelfDescribing() { public void describeTo(Description description) { iterator.next().describeMismatch(invocation, description); } }; } public void remove() { iterator.remove(); } }; } }; } private void describe(Description description, Iterable selfDescribingExpectations) { if (expectations.isEmpty()) { description.appendText("no expectations specified: did you...\n" + " - forget to start an expectation with a cardinality clause?\n" + " - call a mocked method to specify the parameter of an expectation?"); } else { description.appendList("expectations:\n ", "\n ", "", selfDescribingExpectations); if (!stateMachines.isEmpty()) { description.appendList("\nstates:\n ", "\n ", "", stateMachines); } } } /* (non-Javadoc) * @see org.jmock.internal.InvocationDispatcher#isSatisfied() */ public boolean isSatisfied() { for (Expectation expectation : expectations) { if (!expectation.isSatisfied()) { return false; } } return true; } /* (non-Javadoc) * @see org.jmock.internal.InvocationDispatcher#dispatch(org.jmock.api.Invocation) */ public Object dispatch(Invocation invocation) throws Throwable { for (Expectation expectation : expectations) { if (expectation.matches(invocation)) { return expectation.invoke(invocation); } } throw ExpectationError.unexpected("unexpected invocation", invocation); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/internal/000077500000000000000000000000001347002534600265425ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/internal/DeltaQueue.java000066400000000000000000000064371347002534600314550ustar00rootroot00000000000000package org.jmock.lib.concurrent.internal; public class DeltaQueue { private static class Node { public final T value; public long delay; public Node next = null; public Node(T value, long nanos) { this.value = value; this.delay = nanos; } } private Node head = null; public boolean isEmpty() { return head == null; } public boolean isNotEmpty() { return !isEmpty(); } public T next() { return head.value; } public long delay() { return head.delay; } public long delay(T element) { long ret = 0; Node next = head; while (next != null) { ret += next.delay; if (next.value.equals(element)) { break; } next = next.next; } if (next == null) { return -1; } return ret; } public void add(long delay, T value) { Node newNode = new Node(value, delay); Node prev = null; Node next = head; while (next != null && next.delay <= newNode.delay) { newNode.delay -= next.delay; prev = next; next = next.next; } if (prev == null) { head = newNode; } else { prev.next = newNode; } if (next != null) { next.delay -= newNode.delay; newNode.next = next; } } public long tick(long timeUnits) { if (head == null) { return 0L; } else if (head.delay >= timeUnits) { head.delay -= timeUnits; return 0L; } else { long leftover = timeUnits - head.delay; head.delay = 0L; return leftover; } } public T pop() { if (head.delay > 0) { throw new IllegalStateException("cannot pop the head element when it has a non-zero delay"); } T popped = head.value; head = head.next; return popped; } public boolean remove(T element) { Node prev = null; Node node = head; while (node != null && node.value != element) { prev = node; node = node.next; } if (node == null) { return false; } if (node.next != null) { node.next.delay += node.delay; } if (prev == null) { head = node.next; } else { prev.next = node.next; } return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()) .append("["); Node node = head; while (node != null) { if (node != head) { sb.append(", "); } sb.append("+") .append(node.delay) .append(": ") .append(node.value); node = node.next; } sb.append("]"); return sb.toString(); } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/internal/FixedTimeout.java000066400000000000000000000013761347002534600320220ustar00rootroot00000000000000package org.jmock.lib.concurrent.internal; import java.util.concurrent.TimeoutException; /** * A Timeout of fixed duration from the time the FixedTimeout object is * instantiated. * * @author nat */ public class FixedTimeout implements Timeout { private final long duration; private final long start; public FixedTimeout(long duration) { this.duration = duration; this.start = System.currentTimeMillis(); } public long timeRemaining() throws TimeoutException { long now = System.currentTimeMillis(); long timeLeft = duration - (now - start); if (timeLeft <= 0) { throw new TimeoutException("timed out after " + duration + " ms"); } return timeLeft; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/internal/InfiniteTimeout.java000066400000000000000000000004401347002534600325170ustar00rootroot00000000000000package org.jmock.lib.concurrent.internal; import java.util.concurrent.TimeoutException; /** * A Timeout that never times out. * * @author nat */ public class InfiniteTimeout implements Timeout { public long timeRemaining() throws TimeoutException { return 0L; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/internal/Timeout.java000066400000000000000000000005321347002534600310330ustar00rootroot00000000000000package org.jmock.lib.concurrent.internal; import java.util.concurrent.TimeoutException; public interface Timeout { /** * Returns the time remaining, to be passed to {@link Object#wait(long) wait} * or throws TimeoutException if the timeout has expired. */ public abstract long timeRemaining() throws TimeoutException; } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/concurrent/package.html000066400000000000000000000001261347002534600272060ustar00rootroot00000000000000

Classes to help test concurrent code with jMock.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/package.html000066400000000000000000000002131347002534600250210ustar00rootroot00000000000000

Implementations of the core interfaces that are used to adjust or extend jMock's basic functionality.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/script/000077500000000000000000000000001347002534600240505ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/script/ScriptedAction.java000066400000000000000000000063011347002534600276260ustar00rootroot00000000000000package org.jmock.lib.script; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; import bsh.EvalError; import bsh.Interpreter; import bsh.TargetError; /** *

An {@link Action} that executes a BeanShell script. * This makes it easy to implement custom actions, especially those that call back to objects * passed to the mocked method as parameters.

* *

To use a scripted action in an expectation, statically import the {@link #perform(String) perform} * method and call it within the will(...) clause of the expectation.

* *

The script can refer to the parameters of the mocked method by the names $0 (the first parameter), $1, $2, etc, * and to the mock object that has been invoked by the name $this. * You can define other script variables by calling the action's {@link #where(String, Object) where} method.

* *

For example:

*
 * allowing (sheep).accept(with(a(Visitor.class))); 
 *     will(perform("$0.visitSheep($this)");
 * 
* *

is equivalent to:

* *
 * allowing (sheep).accept(with(a(Visitor.class))); 
 *     will(perform("$0.visitSheep(s)").where("s", sheep);
 * 
* * * @author nat * */ public class ScriptedAction implements Action { private final Interpreter interpreter = new Interpreter(); private final String script; public ScriptedAction(String expression) { this.script = expression; this.interpreter.setStrictJava(true); } public Object invoke(Invocation invocation) throws Throwable { try { defineParameters(interpreter, invocation); return interpreter.eval(script); } catch (TargetError e) { throw e.getTarget(); } catch (EvalError e) { throw new IllegalArgumentException("could not interpret script", e); } } private void defineParameters(Interpreter interpreter, Invocation invocation) throws EvalError { interpreter.set("$this", invocation.getInvokedObject()); for (int i = 0; i < invocation.getParameterCount(); i++) { interpreter.set("$" + i, invocation.getParameter(i)); } } public void describeTo(Description description) { description.appendText("perform ").appendText(script); } /** * Creates an action that performs the given script. * * @param script * a BeanShell script. * @return * the new action. */ public static ScriptedAction perform(String script) { return new ScriptedAction(script); } /** * Defines a variable that can be referred to by the script. * * @param name * the name of the variable * @param value * the value of the variable * @return * the action, so that more variables can be defined if needed */ public ScriptedAction where(String name, Object value) { try { interpreter.set(name, value); } catch (EvalError e) { throw new IllegalArgumentException("invalid name binding", e); } return this; } } jmock-library-2.12.0/jmock/src/main/java/org/jmock/lib/script/package.html000066400000000000000000000002571347002534600263350ustar00rootroot00000000000000

Plugins that make it easier to write custom actions by scripting their behaviour with BeanShell.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/package.html000066400000000000000000000001301347002534600242510ustar00rootroot00000000000000

The jMock "Domain-Specific Embedded Language" API.

jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/000077500000000000000000000000001347002534600233245ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/ActionClause.java000066400000000000000000000002121347002534600265340ustar00rootroot00000000000000package org.jmock.syntax; import org.jmock.api.Action; public interface ActionClause { public abstract void will(Action action); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/ArgumentConstraintPhrases.java000066400000000000000000000002141347002534600313410ustar00rootroot00000000000000package org.jmock.syntax; import org.hamcrest.Matcher; public interface ArgumentConstraintPhrases { T with(Matcher matcher); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/CardinalityClause.java000066400000000000000000000010631347002534600275670ustar00rootroot00000000000000package org.jmock.syntax; import org.hamcrest.Matcher; public interface CardinalityClause { ReceiverClause exactly(int count); ReceiverClause atLeast(int count); ReceiverClause between(int minCount, int maxCount); ReceiverClause atMost(int count); T oneOf(T mockObject); T one(T mockObject); T allowing(T mockObject); MethodClause allowing(Matcher mockObjectMatcher); T ignoring(T mockObject); MethodClause ignoring(Matcher mockObjectMatcher); T never(T mockObject); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/MethodClause.java000066400000000000000000000003501347002534600265420ustar00rootroot00000000000000package org.jmock.syntax; import java.lang.reflect.Method; import org.hamcrest.Matcher; public interface MethodClause { ParametersClause method(Matcher methodMatcher); ParametersClause method(String nameRegex); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/ParametersClause.java000066400000000000000000000003001347002534600274200ustar00rootroot00000000000000package org.jmock.syntax; import org.hamcrest.Matcher; public interface ParametersClause extends MethodClause { void with(Matcher... parameterMatchers); void withNoArguments(); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/ReceiverClause.java000066400000000000000000000002551347002534600270720ustar00rootroot00000000000000package org.jmock.syntax; import org.hamcrest.Matcher; public interface ReceiverClause { T of(T mockObject); MethodClause of(Matcher objectMatcher); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/StatesClause.java000066400000000000000000000003171347002534600265700ustar00rootroot00000000000000package org.jmock.syntax; import org.jmock.internal.State; import org.jmock.internal.StatePredicate; public interface StatesClause { State is(String name); StatePredicate isNot(String name); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/WithClause.java000066400000000000000000000006701347002534600262420ustar00rootroot00000000000000package org.jmock.syntax; import org.hamcrest.Matcher; public interface WithClause { boolean booleanIs(Matcher matcher); byte byteIs(Matcher matcher); char charIs(Matcher matcher); short shortIs(Matcher matcher); int intIs(Matcher matcher); long longIs(Matcher matcher); float floatIs(Matcher matcher); double doubleIs(Matcher matcher); T is(Matcher matcher); } jmock-library-2.12.0/jmock/src/main/java/org/jmock/syntax/package.html000066400000000000000000000001471347002534600256070ustar00rootroot00000000000000

Interfaces that define jMock's Domain Specific Embedded Language.

jmock-library-2.12.0/jmock/src/main/java/overview.html000066400000000000000000000020221347002534600226340ustar00rootroot00000000000000 jMock 2 - A Lightweight Mock Object Library for Java

jMock 2 is a library for testing Java code using mock objects. Mock objects help you design and test the interactions between the objects in your programs.

jMock 2:

  • makes it quick and easy to define mock objects, so you don't break the rhythm of programming.
  • lets you define flexible constraints over object interactions, reducing the brittleness of your tests.
  • acts as a "domain-specific embedded language" for specifying expectations so it is easy to read and understand the intent of tests with mock objects.
  • uses real method calls to specify expectations, so code can be easily refactored in modern IDEs.
  • is easy to extend.

More information can be found on the jMock website (www.jmock.org).

jmock-library-2.12.0/jmock/src/test/000077500000000000000000000000001347002534600172165ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/000077500000000000000000000000001347002534600201375ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/000077500000000000000000000000001347002534600207265ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/000077500000000000000000000000001347002534600220315ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/000077500000000000000000000000001347002534600230105ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/000077500000000000000000000000001347002534600250765ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/AnyMethodAcceptanceTests.java000066400000000000000000000017361347002534600326320ustar00rootroot00000000000000package org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; public class AnyMethodAcceptanceTests extends TestCase { public interface AnotherType { void anotherMethod(); } Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); AnotherType anotherMock = context.mock(AnotherType.class, "anotherMock"); public void testElidingTheMethodMeansAnyMethodWithAnyArguments() { context.checking(new Expectations() {{ allowing (mock); }}); mock.method1(); mock.method2(); mock.method3(); mock.method4(); } public void testCanElideMethodsOfMoreThanOneMockObject() { context.checking(new Expectations() {{ ignoring (mock); ignoring (anotherMock); }}); mock.method1(); anotherMock.anotherMethod(); } } CascadedFailuresAcceptanceTests.java000066400000000000000000000053211347002534600340370ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; /* Acceptance test for issue JMOCK-30 (http://jira.codehaus.org/browse/JMOCK-30). */ public class CascadedFailuresAcceptanceTests extends TestCase { public interface MockedType { void realExpectationFailure(int i); void invocationCausedByExpectationFailure(); void anotherRealExpectationFailure(); } private Mockery context = new Mockery(); private MockedType mock = context.mock(MockedType.class, "mock"); private MockedType otherMock = context.mock(MockedType.class, "otherMock"); private void maskedExpectationFailure(MockedType mock1, MockedType mock2) { try { mock1.realExpectationFailure(2); } finally { mock2.invocationCausedByExpectationFailure(); } } @Override public void setUp() { context.checking(new Expectations() {{ allowing (mock).realExpectationFailure(1); }}); } public void testMockeryReportsFirstFailedMethod() { try { maskedExpectationFailure(mock, mock); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { assertSame("invoked object", mock, e.invocation.getInvokedObject()); assertEquals("invoked method", "realExpectationFailure", e.invocation.getInvokedMethod().getName() ); } } public void testMockeryReportsFirstFailedObject() { try { maskedExpectationFailure(mock, otherMock); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { assertSame("invoked object", mock, e.invocation.getInvokedObject()); assertEquals("invoked method", "realExpectationFailure", e.invocation.getInvokedMethod().getName() ); } } // See issue JMOCK-183 (http://jira.codehaus.org/browse/JMOCK-183). public void testVerifyReportsFirstFailure() { try { mock.realExpectationFailure(2); } catch (ExpectationError e) { /* swallowed */ } try { context.assertIsSatisfied(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { assertSame("invoked object", mock, e.invocation.getInvokedObject()); assertEquals("invoked method", "realExpectationFailure", e.invocation.getInvokedMethod().getName() ); } } } ConsecutiveCallsAcceptanceTests.java000066400000000000000000000016001347002534600341170ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; public class ConsecutiveCallsAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testCanEasilySpecifySequenceOfStubsForSameMethod() { context.checking(new Expectations() {{ atLeast(1).of (mock).returnString(); will(onConsecutiveCalls(returnValue("hello"), returnValue("bonjour"), returnValue("guten Tag"))); }}); assertEquals("hello", mock.returnString()); assertEquals("bonjour", mock.returnString()); assertEquals("guten Tag", mock.returnString()); } } DefineExpectationWithinExpectationsAcceptanceTests.java000066400000000000000000000023311347002534600400230ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; // See issue JMOCK-184 public class DefineExpectationWithinExpectationsAcceptanceTests extends TestCase { public interface MockedTypeA { void a(MockedTypeB b); } public interface MockedTypeB { void b(); } Mockery context = new Mockery(); MockedTypeA a = context.mock(MockedTypeA.class, "a"); public void testCanDefineExpectationsWithinExpectations() { context.checking(new Expectations() {{ oneOf (a).a(aNewMockWithExpectations()); }}); } private MockedTypeB aNewMockWithExpectations() { final MockedTypeB mock = context.mock(MockedTypeB.class); context.checking(new Expectations() {{ ignoring (mock); }}); return mock; } public void testCanStillIgnoreEntireMockObjectsBeforeAnotherExpectation() { final MockedTypeA a2 = context.mock(MockedTypeA.class, "a2"); context.checking(new Expectations() {{ ignoring(a2); oneOf (a).a(aNewMockWithExpectations()); }}); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/DoAllAcceptanceTests.java000066400000000000000000000036561347002534600317400ustar00rootroot00000000000000package org.jmock.test.acceptance; import java.util.ArrayList; import java.util.Collection; import junit.framework.TestCase; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Action; import org.jmock.api.Invocation; public class DoAllAcceptanceTests extends TestCase { public interface Collector { void addThingsTo(Collection collection); } Mockery context = new Mockery(); Collector collector = context.mock(Collector.class); public void testCanSpecifyMultipleStubsForOneInvocation() { final ArrayList list = new ArrayList(); context.checking(new Expectations() {{ exactly(1).of (collector).addThingsTo(with(same(list))); will(doAll(addElement("1"), addElement("2"), addElement("3"), addElement("4"))); }}); collector.addThingsTo(list); assertEquals("list length", 4, list.size()); for (int i = 0; i < list.size(); i++) { assertEquals("element "+(i+1), Integer.toString(i+1), list.get(i)); } } private Action addElement(String newElement) { return new AddElementAction(newElement); } public static class AddElementAction implements Action { private final String newElement; public AddElementAction(String newElement) { this.newElement = newElement; } @SuppressWarnings("unchecked") public Object invoke(Invocation invocation) throws Throwable { ((Collection)invocation.getParameter(0)).add(newElement); return null; } public void describeTo(Description description) { throw new UnsupportedOperationException("AddElementStub.describeTo not implemented"); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/ErrorMessagesAcceptanceTests.java000066400000000000000000000134251347002534600335210ustar00rootroot00000000000000package org.jmock.test.acceptance; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.Action; import org.jmock.api.ExpectationError; import org.jmock.api.Invocation; import org.jmock.lib.action.CustomAction; import org.jmock.test.unit.support.AssertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.hamcrest.StringDescription.asString; import static org.junit.Assert.assertThat; public class ErrorMessagesAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testShowsExpectedAndCurrentNumberOfCallsInErrorMessage() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); exactly(1).of (mock).method2(); atLeast(1).of (mock).method3(); allowing (mock).method4(); }}); mock.method2(); mock.method3(); mock.method4(); try { context.assertIsSatisfied(); } catch (ExpectationError e) { String message = StringDescription.toString(e); AssertThat.stringIncludes("should include expectation that has not been invoked at all", "method1", message); AssertThat.stringIncludes("should include expectation that has been fully satisfied", "method2", message); AssertThat.stringIncludes("should include expectation that has been satisfied but can still be invoked", "method3", message); AssertThat.stringIncludes("should include expectation that is allowed", "method4", message); } } // See issue JMOCK-132 public void testErrorMessageIncludesNotInvokedInsteadOfInvokedExactly0Times() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); }}); try { context.assertIsSatisfied(); } catch (ExpectationError e) { String message = StringDescription.toString(e); AssertThat.stringIncludes("should include 'never invoked'", "never invoked", message); } } // See issue JMOCK-153 public void testErrorMessageIncludesOnceInsteadOfExactly1Time() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); }}); try { context.assertIsSatisfied(); } catch (ExpectationError e) { String message = StringDescription.toString(e); AssertThat.stringIncludes("should include 'once'", "once", message); } } // See issue JMOCK-190 public void testCannotExpectToString() { try { context.checking(new Expectations() {{ allowing(mock).toString(); }}); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } // See issue JMOCK-190 public void testCannotExpectEquals() { try { context.checking(new Expectations() {{ allowing(mock).equals("any object"); }}); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } // See issue JMOCK-190 public void testCannotExpectHashCode() { try { context.checking(new Expectations() {{ allowing(mock).hashCode(); }}); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } public interface TypeThatMakesFinalizePublic { public void finalize(); } // See issue JMOCK-190 public void testCannotExpectFinalize() { final TypeThatMakesFinalizePublic mockWithFinalize = context.mock(TypeThatMakesFinalizePublic.class, "mockWithFinalize"); try { context.checking(new Expectations() {{ allowing(mockWithFinalize).finalize(); }}); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) {} } // See issue JMOCK-167 public void testDoesNotDescribeReturnValueForMethodsThatAreKnownToBeVoid() { context.checking(new Expectations() {{ oneOf (mock).doSomething(); }}); assertThat(asString(context), not(containsString("returns a default value"))); } public void testMismatchDescription() { context.checking(new Expectations() {{ oneOf (mock).doSomethingWith("foo"); oneOf (mock).doSomethingWith("x", "y"); will(doSomethingDescribedAs("ACTION")); }}); try { mock.doSomethingWith("X", "Y"); } catch (ExpectationError e) { String failure = asString(e); Integer actionIndex = failure.indexOf("ACTION"); Integer parameterMismatchIndex = failure.indexOf("parameter 0 did not match"); assertTrue("action should come before parameter mismatches in description", actionIndex < parameterMismatchIndex); } } public Action doSomethingDescribedAs(String name) { return new CustomAction(name) { public Object invoke(Invocation invocation) throws Throwable { return null; } }; } } ExpectationCountsAcceptanceTests.java000066400000000000000000000065401347002534600343400ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; @SuppressWarnings("unused") public class ExpectationCountsAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testOne() { context.checking(new Expectations() {{ oneOf (mock).doSomething(); }}); assertContextIsNotSatisfied(); mock.doSomething(); context.assertIsSatisfied(); assertAnotherInvocationFailsTheTest(); } public void testExpectsExactly() { context.checking(new Expectations() {{ exactly(2).of (mock).doSomething(); }}); assertContextIsNotSatisfied(); mock.doSomething(); assertContextIsNotSatisfied(); mock.doSomething(); context.assertIsSatisfied(); assertAnotherInvocationFailsTheTest(); } public void testExpectsAtLeast() { context.checking(new Expectations() {{ atLeast(2).of (mock).doSomething(); }}); assertContextIsNotSatisfied(); mock.doSomething(); assertContextIsNotSatisfied(); mock.doSomething(); context.assertIsSatisfied(); for (any_number of : times) { mock.doSomething(); context.assertIsSatisfied(); } } public void testExpectsAtMost() { context.checking(new Expectations() {{ atMost(2).of (mock).doSomething(); }}); context.assertIsSatisfied(); mock.doSomething(); context.assertIsSatisfied(); mock.doSomething(); assertAnotherInvocationFailsTheTest(); } public void testExpectsBetween() { context.checking(new Expectations() {{ between(2,3).of (mock).doSomething(); }}); assertContextIsNotSatisfied(); mock.doSomething(); assertContextIsNotSatisfied(); mock.doSomething(); context.assertIsSatisfied(); mock.doSomething(); context.assertIsSatisfied(); assertAnotherInvocationFailsTheTest(); } public void testAllows() { context.checking(new Expectations() {{ allowing (mock).doSomething(); }}); for (any_number of : times) { mock.doSomething(); context.assertIsSatisfied(); } } public void testNever() { context.checking(new Expectations() {{ never (mock).doSomething(); }}); context.assertIsSatisfied(); assertAnotherInvocationFailsTheTest(); } private void assertAnotherInvocationFailsTheTest() { try { mock.doSomething(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } private void assertContextIsNotSatisfied() { try { context.assertIsSatisfied(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } private class any_number {} static final any_number[] times = new any_number[4]; } ExpectationErrorCheckingAcceptanceTests.java000066400000000000000000000103371347002534600356110ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import java.util.ArrayList; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; public class ExpectationErrorCheckingAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testCannotSetAnExpectationOnAnObjectThatIsNotAMock() { final ArrayList list = new ArrayList(); try { context.checking(new Expectations() {{ exactly(1).of (list).add("a new element"); }}); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } } public void testCannotSetAnExpectationWithoutSpecifyingCardinality() { try { context.checking(new Expectations() {{ mock.doSomething(); }}); fail("should have thrown ExpectationError"); } catch (ExpectationError ex) { // expected } } public void testCannotSetAnExpectationWithoutSpecifyingCardinalityAfterPreviousExpectationsWithCardinality() { try { context.checking(new Expectations() {{ exactly(1).of (mock).doSomething(); mock.doSomething(); }}); fail("should have thrown ExpectationError"); } catch (ExpectationError ex) { // expected } } public void testCannotSetAnExpectationWithoutSpecifyingCardinalityAfterAnIncompleteExpectation() { try { context.checking(new Expectations() {{ exactly(1); mock.doSomething(); }}); fail("should have thrown ExpectationError"); } catch (ExpectationError ex) { // expected } } public void testCannotSetAnExpectationWithoutSpecifyingTheMockObject() { try { context.checking(new Expectations() {{ exactly(1); }}); fail("should have thrown IllegalStateException"); } catch (IllegalStateException ex) { // expected } } public void testCannotSetAnExpectationWithoutSpecifyingTheMockObjectBeforeOtherExpectations() { try { context.checking(new Expectations() {{ exactly(1); exactly(1).of (mock).doSomething(); }}); fail("should have thrown IllegalStateException"); } catch (IllegalStateException ex) { // expected } } public void testCannotSetAnExpectationWithoutSpecifyingTheMockObjectAfterOtherExpectations() { try { context.checking(new Expectations() {{ exactly(1).of (mock).doSomething(); exactly(1); }}); fail("should have thrown IllegalStateException"); } catch (IllegalStateException ex) { // expected } } public void testCannotSetExpectationWithoutSpecifyingTheMockObjectWhenSettingParameterConstraints() { try { context.checking(new Expectations() {{ mock.doSomethingWith(with(equal("1")), with(equal("2"))); }}); } catch (IllegalStateException e) { // exception } } public void testCannotInvokeAMethodOnAMockObjectIfNoExpectationsWereSet() { try { mock.doSomething(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } public void testMustSpecifyConstraintsForAllArguments() { try { context.checking(new Expectations() {{ exactly(1).of (mock).doSomethingWith("x", with(equal("y"))); }}); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testCanSpecifyNoExpectationsAtAll() { context.assertIsSatisfied(); } } ExpectationErrorTranslationAcceptanceTests.java000066400000000000000000000033261347002534600363740ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; import org.jmock.api.ExpectationErrorTranslator; public class ExpectationErrorTranslationAcceptanceTests extends TestCase { public class TranslatedError extends Error {} ExpectationErrorTranslator translator = new ExpectationErrorTranslator() { public Error translate(ExpectationError e) { return new TranslatedError(); } }; Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); @Override public void setUp() { context.setExpectationErrorTranslator(translator); } public void testMockeryCanTranslateExpectationErrorsIntoDifferentExceptionTypeWhenUnexpectedInvocationOccurs() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); }}); try { mock.method2(); } catch (TranslatedError e) { // expected } catch (ExpectationError e) { fail("should have translated ExpectationError into TranslatedError"); } } public void testMockeryCanTranslateExpectationErrorsIntoDifferentExceptionTypeWhenMockeryIsNotSatisfied() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); }}); try { context.assertIsSatisfied(); } catch (TranslatedError e) { // expected } catch (ExpectationError e) { fail("should have translated ExpectationError into TranslatedError"); } } } FlexibleExpectationsAcceptanceTests.java000066400000000000000000000061101347002534600347730ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import java.lang.reflect.Method; import junit.framework.TestCase; import org.hamcrest.Matcher; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; import org.jmock.internal.matcher.MethodNameMatcher; public class FlexibleExpectationsAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock1 = context.mock(MockedType.class, "mock1"); MockedType mock2 = context.mock(MockedType.class, "mock2"); public void testCanSpecifyFlexibleMethodMatchers() { context.checking(new Expectations() {{ allowing (anything()).method(withName("doSomething.*")); }}); mock1.doSomething(); mock1.doSomething(); mock2.doSomethingWith("x", "y"); try { mock1.method1(); fail("method1 should not have been expected"); } catch (ExpectationError e) { // expected } } public void testCanSpecifyMethodNameRegexDirectly() { context.checking(new Expectations() {{ allowing (anything()).method("doSomething.*"); }}); mock1.doSomething(); mock1.doSomething(); mock2.doSomethingWith("x", "y"); try { mock1.method1(); fail("method1 should not have been expected"); } catch (ExpectationError e) { // expected } } public void testCanSpecifyFlexibleArgumentMatchers() { context.checking(new Expectations() {{ allowing (anything()).method(withName("doSomethingWith")).with(equal("x"), equal("y")); allowing (anything()).method(withName("doSomethingWith")).with(equal("X"), equal("Y")); }}); mock1.doSomethingWith("x", "y"); mock1.doSomethingWith("X", "Y"); mock2.doSomethingWith("x", "y"); mock2.doSomethingWith("X", "Y"); try { mock1.doSomething(); fail("doSomething should not have been expected"); } catch (ExpectationError e) { // expected } } public void testCanSpecifyNoArguments() { context.checking(new Expectations() {{ allowing (anything()).method(withName("do.*")).withNoArguments(); allowing (anything()).method(withName("do.*")).with(equal("X"), equal("Y")); }}); mock1.doSomething(); mock1.doSomethingWith("X", "Y"); try { mock1.doSomethingWith("x", "y"); fail("doSomething should not have been expected"); } catch (ExpectationError e) { // expected } } public void testCanReturnDefaultValueFromFlexibleExpectation() { context.checking(new Expectations() {{ allowing (anything()).method(withName(".*")); }}); mock1.returnInt(); // should not fail } Matcher withName(String nameRegex) { return new MethodNameMatcher(nameRegex); } } HamcrestTypeSafetyAcceptanceTests.java000066400000000000000000000021201347002534600344330ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.number.OrderingComparison.greaterThan; import java.lang.reflect.Method; import junit.framework.TestCase; import org.hamcrest.Matcher; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.internal.matcher.MethodNameMatcher; public class HamcrestTypeSafetyAcceptanceTests extends TestCase { public interface MockedType { void m(String s); void m(int i); } Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testMatchersCanCopeWithDifferentArgumentTypes() { context.checking(new Expectations() {{ exactly(1).of (anything()).method(withName("m")).with(startsWith("x")); exactly(1).of (anything()).method(withName("m")).with(greaterThan(0)); }}); mock.m(1); // should not throw ClassCastException } Matcher withName(String nameRegex) { return new MethodNameMatcher(nameRegex); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/MockedType.java000066400000000000000000000005721347002534600300110ustar00rootroot00000000000000package org.jmock.test.acceptance; public interface MockedType { void doSomething(); void doSomethingWith(String s); void doSomethingWith(int s); void doSomethingWith(String x, String y); void doSomethingWithArray(String[] strings); void method1(); void method2(); void method3(); void method4(); String returnString(); int returnInt(); } NewStyleParameterMatchingAcceptanceTests.java000066400000000000000000000123021347002534600357400ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; import java.util.Collections; import java.util.List; import java.util.Set; import static org.hamcrest.Matchers.empty; public class NewStyleParameterMatchingAcceptanceTests extends TestCase { public interface AnInterface { void doSomethingWith(String s); void doSomethingWithBoth(String s1, String s2); void doSomethingWithBoth(boolean i1, boolean i2); void doSomethingWithBoth(byte i1, byte i2); void doSomethingWithBoth(short i1, short i2); void doSomethingWithBoth(char c1, char c2); void doSomethingWithBoth(int i1, int i2); void doSomethingWithBoth(long i1, long i2); void doSomethingWithBoth(float i1, float i2); void doSomethingWithBoth(double i1, double i2); void beSilly(List>> silly); } Mockery context = new Mockery(); AnInterface mock = context.mock(AnInterface.class, "mock"); public void testMatchesParameterValues() { context.checking(new Expectations() {{ oneOf (mock).doSomethingWith(with.is(equal("hello"))); oneOf (mock).doSomethingWith(with.is(equal("goodbye"))); }}); mock.doSomethingWith("hello"); mock.doSomethingWith("goodbye"); context.assertIsSatisfied(); } public void testDoesNotAllowUnexpectedParameterValues() { context.checking(new Expectations() {{ oneOf (mock).doSomethingWith(with.is(equal("hello"))); oneOf (mock).doSomethingWith(with.is(equal("goodbye"))); }}); try { mock.doSomethingWith("hello"); mock.doSomethingWith("Goodbye"); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } public void testAllOrNoneOfTheParametersMustBeSpecifiedByMatchers() { try { context.checking(new Expectations() {{ oneOf (mock).doSomethingWithBoth(with.is(equal("a-matcher")), "not-a-matcher"); }}); } catch (IllegalArgumentException expected) { } } // Test to show that issue JMOCK-160 is spurious public void testNotAllExpectationsOfSameMockMustUseMatchers() { context.checking(new Expectations() {{ oneOf (mock).doSomethingWithBoth(with.is(equal("x")), with.is(equal("y"))); oneOf (mock).doSomethingWith("z"); }}); mock.doSomethingWithBoth("x", "y"); mock.doSomethingWith("z"); context.assertIsSatisfied(); } // See issue JMOCK-161 public void testCanPassLiteralValuesToWithMethodToMeanEqualTo() { context.checking(new Expectations() {{ exactly(2).of (mock).doSomethingWithBoth(with.is(anything()), with("y")); }}); mock.doSomethingWithBoth("x", "y"); mock.doSomethingWithBoth("z", "y"); context.assertIsSatisfied(); } // See issue JMOCK-161 public void testCanPassLiteralPrimitiveValuesToWithMethodToMeanEqualTo() { context.checking(new Expectations() {{ exactly(2).of (mock).doSomethingWithBoth(with.booleanIs(anything()), with(true)); exactly(2).of (mock).doSomethingWithBoth(with.byteIs(anything()), with((byte)1)); exactly(2).of (mock).doSomethingWithBoth(with.shortIs(anything()), with((short)2)); exactly(2).of (mock).doSomethingWithBoth(with.charIs(anything()), with('x')); exactly(2).of (mock).doSomethingWithBoth(with.intIs(anything()), with(3)); exactly(2).of (mock).doSomethingWithBoth(with.longIs(anything()), with(4L)); exactly(2).of (mock).doSomethingWithBoth(with.floatIs(anything()), with(5.0f)); exactly(2).of (mock).doSomethingWithBoth(with.doubleIs(anything()), with(6.0)); }}); mock.doSomethingWithBoth(true, true); mock.doSomethingWithBoth(false, true); mock.doSomethingWithBoth((byte)1, (byte)1); mock.doSomethingWithBoth((byte)2, (byte)1); mock.doSomethingWithBoth((short)1, (short)2); mock.doSomethingWithBoth((short)2, (short)2); mock.doSomethingWithBoth('1', 'x'); mock.doSomethingWithBoth('2', 'x'); mock.doSomethingWithBoth(1, 3); mock.doSomethingWithBoth(2, 3); mock.doSomethingWithBoth(1L, 4L); mock.doSomethingWithBoth(2L, 4L); mock.doSomethingWithBoth(1.0f, 5.0f); mock.doSomethingWithBoth(2.0f, 5.0f); mock.doSomethingWithBoth(1.0, 6.0); mock.doSomethingWithBoth(2.0, 6.0); context.assertIsSatisfied(); } public void ridiculousJavaTypeName() { @SuppressWarnings("unused") final List>> silly = Collections.emptyList(); context.checking(new Expectations() {{ oneOf (mock).beSilly(with.>>>is(empty())); }}); } } NullAndNonNullAcceptanceTests.java000066400000000000000000000037061347002534600335250ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; public class NullAndNonNullAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class); public void testNullParameterMatcher() { context.checking(new Expectations() {{ allowing (mock).doSomethingWith(with(aNull(String.class))); }}); mock.doSomethingWith(null); try { mock.doSomethingWith("not null"); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } public void testNonNullParameterMatcher() { context.checking(new Expectations() {{ allowing (mock).doSomethingWith(with(aNonNull(String.class))); }}); mock.doSomethingWith("not null"); try { mock.doSomethingWith(null); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } public void testAnyParameterMatcher() { context.checking(new Expectations() {{ allowing (mock).doSomethingWith(with(any(String.class))); }}); mock.doSomethingWith("not null"); try { mock.doSomethingWith(null); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } // A defect in Hamcrest public void testNullArrayParameter() { context.checking(new Expectations() {{ allowing (mock).doSomethingWithArray(null); }}); mock.doSomethingWithArray(null); try { mock.doSomethingWithArray(new String[]{"not null"}); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } } OverrideExpectationsFromSetUpAcceptanceTests.java000066400000000000000000000025671347002534600366410ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.States; import org.jmock.api.ExpectationError; public class OverrideExpectationsFromSetUpAcceptanceTests extends TestCase { Mockery mockery = new Mockery(); MockedType mock = mockery.mock(MockedType.class, "mock"); States test = mockery.states("test").startsAs("settingUp"); @Override public void setUp() { mockery.checking(new Expectations() {{ allowing (mock).doSomethingWith(with(any(String.class))); when(test.is("settingUp")); }}); // These would be called by the object under test, during set-up mock.doSomethingWith("foo"); mock.doSomethingWith("bar"); test.become("ready"); } public void testSomething() { mockery.checking(new Expectations() {{ oneOf (mock).doSomethingWith("whee"); }}); try { // This would be called by the object under test, during the test. // It should be detected as a test failure, because the 'allowing' // expectations defined during set-up no longer apply mock.doSomethingWith("whoo"); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/PackageProtectedType.java000066400000000000000000000001101347002534600320000ustar00rootroot00000000000000package org.jmock.test.acceptance; interface PackageProtectedType { } ParameterMatchingAcceptanceTests.java000066400000000000000000000123551347002534600342550ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; public class ParameterMatchingAcceptanceTests extends TestCase { public interface AnInterface { void doSomethingWith(String s); void doSomethingWithBoth(String s1, String s2); void doSomethingWithBoth(boolean i1, boolean i2); void doSomethingWithBoth(byte i1, byte i2); void doSomethingWithBoth(short i1, short i2); void doSomethingWithBoth(char c1, char c2); void doSomethingWithBoth(int i1, int i2); void doSomethingWithBoth(long i1, long i2); void doSomethingWithBoth(float i1, float i2); void doSomethingWithBoth(double i1, double i2); } Mockery context = new Mockery(); AnInterface mock = context.mock(AnInterface.class, "mock"); public void testMatchesParameterValues() { context.checking(new Expectations() {{ exactly(1).of (mock).doSomethingWith(with(equal("hello"))); exactly(1).of (mock).doSomethingWith(with(equal("goodbye"))); }}); mock.doSomethingWith("hello"); mock.doSomethingWith("goodbye"); context.assertIsSatisfied(); } public void testDoesNotAllowUnexpectedParameterValues() { context.checking(new Expectations() {{ exactly(1).of (mock).doSomethingWith(with(equal("hello"))); exactly(1).of (mock).doSomethingWith(with(equal("goodbye"))); }}); try { mock.doSomethingWith("hello"); mock.doSomethingWith("Goodbye"); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } public void testAllOrNoneOfTheParametersMustBeSpecifiedByMatchers() { try { context.checking(new Expectations() {{ exactly(1).of (mock).doSomethingWithBoth(with(equal("a-matcher")), "not-a-matcher"); }}); } catch (IllegalArgumentException expected) { } } // Test to show that issue JMOCK-160 is spurious public void testNotAllExpectationsOfSameMockMustUseMatchers() { context.checking(new Expectations() {{ exactly(1).of (mock).doSomethingWithBoth(with(equal("x")), with(equal("y"))); exactly(1).of (mock).doSomethingWith("z"); }}); mock.doSomethingWithBoth("x", "y"); mock.doSomethingWith("z"); context.assertIsSatisfied(); } // See issue JMOCK-161 public void testCanPassLiteralValuesToWithMethodToMeanEqualTo() { context.checking(new Expectations() {{ exactly(2).of (mock).doSomethingWithBoth(with(any(String.class)), with("y")); }}); mock.doSomethingWithBoth("x", "y"); mock.doSomethingWithBoth("z", "y"); context.assertIsSatisfied(); } public void testCanPassLiteralPrimitiveValuesToWithMethodToMeanEqualTo() { context.checking(new Expectations() {{ exactly(2).of (mock).doSomethingWithBoth(with.booleanIs(any(boolean.class)), with(true)); exactly(2).of (mock).doSomethingWithBoth(with.byteIs(any(byte.class)), with((byte)1)); exactly(2).of (mock).doSomethingWithBoth(with.shortIs(any(short.class)), with((short)2)); exactly(2).of (mock).doSomethingWithBoth(with.charIs(any(char.class)), with('x')); exactly(2).of (mock).doSomethingWithBoth(with.intIs(any(int.class)), with(3)); exactly(2).of (mock).doSomethingWithBoth(with.longIs(any(long.class)), with(4L)); exactly(2).of (mock).doSomethingWithBoth(with.floatIs(any(float.class)), with(5.0f)); exactly(2).of (mock).doSomethingWithBoth(with.doubleIs(any(double.class)), with(6.0)); }}); mock.doSomethingWithBoth(true, true); mock.doSomethingWithBoth(false, true); mock.doSomethingWithBoth((byte)1, (byte)1); mock.doSomethingWithBoth((byte)2, (byte)1); mock.doSomethingWithBoth((short)1, (short)2); mock.doSomethingWithBoth((short)2, (short)2); mock.doSomethingWithBoth('1', 'x'); mock.doSomethingWithBoth('2', 'x'); mock.doSomethingWithBoth(1, 3); mock.doSomethingWithBoth(2, 3); mock.doSomethingWithBoth(1L, 4L); mock.doSomethingWithBoth(2L, 4L); mock.doSomethingWithBoth(1.0f, 5.0f); mock.doSomethingWithBoth(2.0f, 5.0f); mock.doSomethingWithBoth(1.0, 6.0); mock.doSomethingWithBoth(2.0, 6.0); context.assertIsSatisfied(); } // Checking that you can do with(any(...)) with primitive types, as asked on the mailing list public void testSpecifyingAnyValueOfPrimitiveType() { context.checking(new Expectations() {{ allowing (mock).doSomethingWithBoth(with.booleanIs(any(boolean.class)), with.booleanIs(any(boolean.class))); }}); mock.doSomethingWithBoth(true, true); mock.doSomethingWithBoth(true, false); mock.doSomethingWithBoth(false, true); mock.doSomethingWithBoth(false, false); } } PrimitiveParameterTypesAcceptanceTests.java000066400000000000000000000064041347002534600355160ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Test; public class PrimitiveParameterTypesAcceptanceTests { public interface MethodsWithPrimitiveTypes { void withBoolean(boolean b); void withByte(byte b); void withShort(short s); void withInt(int i); void withLong(long l); void withFloat(float f); void withDouble(double d); } public final Mockery context = new Mockery(); private final MethodsWithPrimitiveTypes mock = context.mock(MethodsWithPrimitiveTypes.class, "mock"); @Test public void canSetExpectationsWithMatchersForMethodsWithArgumentsOfPrimitiveTypes() { context.checking(new Expectations() {{ exactly(1).of (mock).withBoolean(with.booleanIs(equal(true))); exactly(1).of (mock).withByte(with.byteIs(equal((byte)10))); exactly(1).of (mock).withShort(with.shortIs(equal((short) 10))); exactly(1).of (mock).withInt(with.intIs(equal(10))); exactly(1).of (mock).withLong(with.longIs(equal(10L))); exactly(1).of (mock).withFloat(with.floatIs(equal(10.0f))); exactly(1).of (mock).withDouble(with.doubleIs(equal(10.0))); }}); mock.withBoolean(true); mock.withByte((byte)10); mock.withShort((short)10); mock.withInt(10); mock.withLong(10L); mock.withFloat(10.0f); mock.withDouble(10.0); context.assertIsSatisfied(); } @Test public void canSetExpectationsWithLiteralsForMethodsWithArgumentsOfPrimitiveTypes() { context.checking(new Expectations() {{ exactly(1).of (mock).withBoolean(true); exactly(1).of (mock).withByte((byte)10); exactly(1).of (mock).withShort((short)10); exactly(1).of (mock).withInt(10); exactly(1).of (mock).withLong(10L); exactly(1).of (mock).withFloat(10.0f); exactly(1).of (mock).withDouble(10.0); }}); mock.withBoolean(true); mock.withByte((byte)10); mock.withShort((short)10); mock.withInt(10); mock.withLong(10L); mock.withFloat(10.0f); mock.withDouble(10.0); context.assertIsSatisfied(); } /** * Will fail unless ExpectationsCreator has added generic overloaded byte code */ @Test public void testNonNullNativeIgnoringDocumentationParameterMatcher() { context.checking(new Expectations() {{ exactly(1).of(mock).withBoolean(with.booleanIs(anything())); exactly(1).of(mock).withByte(with.byteIs(anything())); exactly(1).of(mock).withShort(with.shortIs(anything())); exactly(1).of(mock).withInt(with.intIs(anything())); exactly(1).of(mock).withLong(with.longIs(anything())); exactly(1).of(mock).withFloat(with.floatIs(anything())); exactly(1).of(mock).withDouble(with.doubleIs(anything())); }}); mock.withBoolean(true); mock.withByte((byte)10); mock.withShort((short)10); mock.withInt(10); mock.withLong(10L); mock.withFloat(10.0f); mock.withDouble(10.0); context.assertIsSatisfied(); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/RecordingAcceptanceTests.java000066400000000000000000000065521347002534600326570ustar00rootroot00000000000000package org.jmock.test.acceptance; import static java.util.Arrays.asList; import static org.hamcrest.StringDescription.asString; import static org.junit.Assert.assertThat; import junit.framework.TestCase; import org.hamcrest.Matcher; import org.hamcrest.text.StringContainsInOrder; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; public class RecordingAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testRecordsActualInvocations() { context.checking(new Expectations() {{ allowing (same(mock)); }}); mock.doSomething(); mock.doSomethingWith("foo"); mock.doSomethingWith("x", "y"); assertThat(asString(context), containsInOrder( "what happened before this:", "mock.doSomething()", "mock.doSomethingWith(\"foo\")", "mock.doSomethingWith(\"x\", \"y\")")); } static class ExampleException extends RuntimeException {} public void testRecordsInvocationsThatThrowExceptions() { context.checking(new Expectations() {{ allowing (mock).doSomething(); will(throwException(new ExampleException())); }}); try { mock.doSomething(); fail("no exception thrown"); } catch (ExampleException expected) {} assertThat(asString(context), containsInOrder( "what happened before this:", "mock.doSomething()")); } public void testDoesNotRecordUnexpectedInvocations() { context.checking(new Expectations() {{ allowing (mock).doSomethingWith("foo"); }}); try { mock.doSomethingWith("bar"); } catch (ExpectationError expected) {} assertThat(asString(context), containsInOrder( "what happened before this:", "nothing")); } public void testReportsRecordedInvocationsWhenUnexpectedInvocationReceived() { context.checking(new Expectations() {{ oneOf (mock).doSomethingWith("x"); oneOf (mock).doSomethingWith("y"); }}); mock.doSomethingWith("y"); try { mock.doSomethingWith("z"); fail("should have reported unexpected invocation"); } catch (ExpectationError e) { assertThat(asString(e), containsInOrder( "what happened before this:", "mock.doSomethingWith(\"y\")" )); } } public void testReportsRecordedInvocationsWhenNotSatisfied() { context.checking(new Expectations() {{ oneOf (mock).doSomethingWith("x"); oneOf (mock).doSomethingWith("y"); }}); mock.doSomethingWith("y"); try { context.assertIsSatisfied(); fail("should not be satisfied"); } catch (ExpectationError e) { assertThat(asString(e), containsInOrder( "what happened before this:", "mock.doSomethingWith(\"y\")" )); } } private Matcher containsInOrder(String... strings) { return new StringContainsInOrder(asList(strings)); } } ReturningIteratorsAcceptanceTests.java000066400000000000000000000035101347002534600345250ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import java.util.Enumeration; import java.util.Iterator; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; public class ReturningIteratorsAcceptanceTests extends TestCase { public interface Iterators { Iterator i(); Enumeration e(); } Mockery context = new Mockery(); Iterators iterators = context.mock(Iterators.class); public void testReturnsIteratorsOverCollectionOfValues() { context.checking(new Expectations() {{ allowing (iterators).i(); will(returnIterator("a", "b", "c")); }}); assertIteratorOverSequence(iterators.i(), "a", "b", "c"); // We get a new iterator every time assertIteratorOverSequence(iterators.i(), "a", "b", "c"); } public void testReturnsEnumerationsOverCollectionOfValues() { context.checking(new Expectations() {{ allowing (iterators).e(); will(returnEnumeration("x", "y", "z")); }}); assertEnumerationOverSequence(iterators.e(), "x", "y", "z"); // We get a new iterator every time assertEnumerationOverSequence(iterators.e(), "x", "y", "z"); } private void assertIteratorOverSequence(Iterator e, T... values) { for (int i = 0; i < values.length; i++) { assertEquals("element " + i, values[i], e.next()); } assertTrue("at end", !e.hasNext()); } private void assertEnumerationOverSequence(Enumeration e, T... values) { for (int i = 0; i < values.length; i++) { assertEquals("element " + i, values[i], e.nextElement()); } assertTrue("at end", !e.hasMoreElements()); } } ReturningValuesAcceptanceTests.java000066400000000000000000000146731347002534600340240ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.acceptance; import java.util.Date; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; public class ReturningValuesAcceptanceTests extends TestCase { public interface ReturnTypes { String returnString(); boolean returnBoolean(); byte returnByte(); char returnChar(); short returnShort(); int returnInt(); long returnLong(); float returnFloat(); double returnDouble(); void voidMethod(); } private Mockery context = new Mockery(); private ReturnTypes mock = context.mock(ReturnTypes.class, "mock"); public void testCanReturnObjectReferences() { // ensure string is not interned final String result = new String("RESULT"); context.checking(new Expectations() {{ allowing(mock).returnString(); will(returnValue(result)); }}); assertSame("should be same result", result, mock.returnString()); } public void testCanReturnNullObjectReferences() { context.checking(new Expectations() {{ allowing(mock).returnString(); will(returnValue(null)); }}); assertNull("should be null", mock.returnString()); } public void testCanReturnBooleanValues() { context.checking(new Expectations() {{ exactly(1).of(mock).returnBoolean(); will(returnValue(true)); exactly(1).of(mock).returnBoolean(); will(returnValue(false)); }}); assertTrue("should be true", mock.returnBoolean()); assertFalse("should be false", mock.returnBoolean()); } public void testCanReturnByteValues() { final byte result = 123; context.checking(new Expectations() {{ allowing(mock).returnByte(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnByte()); } public void testCanReturnCharValues() { final char result = '\u1234'; context.checking(new Expectations() {{ allowing(mock).returnChar(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnChar()); } public void testCanReturnShortValues() { final short result = 12345; context.checking(new Expectations() {{ allowing(mock).returnShort(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnShort()); } public void testCanReturnIntValues() { final int result = 1234567890; context.checking(new Expectations() {{ allowing(mock).returnInt(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnInt()); } public void testCanReturnLongValues() { final long result = 1234567890124356789L; context.checking(new Expectations() {{ allowing(mock).returnLong(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnLong()); } public void testCanReturnFloatValues() { final float result = 12345.67890f; context.checking(new Expectations() {{ allowing(mock).returnFloat(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnFloat(), 0.0); } public void testCanReturnDoubleValues() { final double result = 1234567890.1234567890; context.checking(new Expectations() {{ allowing (mock).returnDouble(); will(returnValue(result)); }}); assertEquals("should be same result", result, mock.returnDouble(), 0.0); } public void testWillReturnADefaultValueIfNoResultExplicitlySpecified() { context.checking(new Expectations() {{ allowing (mock).returnInt(); }}); // This will not throw a NullPointerException mock.returnInt(); } public class Something {} public interface AnInterfaceThatReturnsSomething { Something returnSomething(); } public void testReturnsNullAsTheDefaultValueForUnregisteredType() { final AnInterfaceThatReturnsSomething returningMock = context.mock(AnInterfaceThatReturnsSomething.class, "returningMock"); context.checking(new Expectations() {{ allowing (returningMock).returnSomething(); }}); Something defaultResult = returningMock.returnSomething(); assertNull("returned null", defaultResult); } public void testCanDefineDefaultReturnValuesForUnregisteredTypes() { final AnInterfaceThatReturnsSomething returningMock = context.mock(AnInterfaceThatReturnsSomething.class, "returningMock"); Something expectedDefaultResult = new Something(); context.setDefaultResultForType(Something.class, expectedDefaultResult); context.checking(new Expectations() {{ allowing (returningMock).returnSomething(); }}); Something defaultResult = returningMock.returnSomething(); assertSame("returned the default result", expectedDefaultResult, defaultResult); } public void testCanChangeDefaultReturnValueForRegisteredType() { String newDefaultString = "hoo-hee-haa-haa"; context.setDefaultResultForType(String.class, newDefaultString); context.checking(new Expectations() {{ allowing (mock).returnString(); }}); assertSame("returned the default result", newDefaultString, mock.returnString()); } public void testReportsTypeMismatchOfResults() { try { context.checking(new Expectations() {{ allowing (mock).returnString(); will(returnValue(new Date())); }}); mock.returnString(); fail("Should have thrown IllegalStateException"); } catch (IllegalStateException expected) { } } public void testReportsTypeMismatchWhenValuesReturnedFromVoidMethods() { context.checking(new Expectations() {{ allowing (mock).voidMethod(); will(returnValue("wrong result")); }}); try { mock.voidMethod(); fail("Should have thrown IllegalStateException"); } catch (IllegalStateException expected) { } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/SequenceAcceptanceTests.java000066400000000000000000000104531347002534600325060ustar00rootroot00000000000000package org.jmock.test.acceptance; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.api.ExpectationError; import org.jmock.test.unit.support.AssertThat; public class SequenceAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); public void testCanConstrainInvocationsToOccurInOrder() { final Sequence s = context.sequence("s"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); oneOf (mock).method2(); inSequence(s); }}); try { mock.method2(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } public void testAllowsInvocationsInSequence() { final Sequence s = context.sequence("s"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); oneOf (mock).method2(); inSequence(s); }}); mock.method1(); mock.method2(); } public void testCanSkipAllowedInvocationsInSequence() { final Sequence s = context.sequence("s"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); allowing (mock).method2(); inSequence(s); oneOf (mock).method3(); inSequence(s); }}); mock.method1(); mock.method3(); } public void testSequencesAreIndependentOfOneAnother() { final Sequence s = context.sequence("s"); final Sequence t = context.sequence("t"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); oneOf (mock).method2(); inSequence(s); oneOf (mock).method3(); inSequence(t); oneOf (mock).method4(); inSequence(t); }}); mock.method1(); mock.method3(); mock.method2(); mock.method4(); } public void testExpectationIncludesSequenceInDescription() { final Sequence s = context.sequence("s"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); }}); try { mock.method2(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { AssertThat.stringIncludes("error message", "in sequence s", StringDescription.toString(e)); } } public void testAnExpectationCanBeInMoreThanOneSequence() { final Sequence s = context.sequence("s"); final Sequence t = context.sequence("t"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); oneOf (mock).method2(); inSequence(t); oneOf (mock).method3(); inSequence(s); inSequence(t); }}); mock.method1(); try { mock.method3(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { AssertThat.stringIncludes("error message", "in sequence s", StringDescription.toString(e)); AssertThat.stringIncludes("error message", "in sequence t", StringDescription.toString(e)); } } // See issue JMOCK-142 public void testHasShortcutForIncludingExpectationInMultipleSequences() { final Sequence s = context.sequence("s"); final Sequence t = context.sequence("t"); context.checking(new Expectations() {{ oneOf (mock).method1(); inSequence(s); oneOf (mock).method2(); inSequence(t); oneOf (mock).method3(); inSequences(s, t); }}); mock.method1(); try { mock.method3(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { AssertThat.stringIncludes("error message", "in sequence s", StringDescription.toString(e)); AssertThat.stringIncludes("error message", "in sequence t", StringDescription.toString(e)); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/StatesAcceptanceTest.java000066400000000000000000000055111347002534600320150ustar00rootroot00000000000000package org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.States; import org.jmock.api.ExpectationError; import org.jmock.test.unit.support.AssertThat; public class StatesAcceptanceTest extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); States readiness = context.states("readiness"); public void testCanConstrainExpectationsToOccurWithinAGivenState() { context.checking(new Expectations() {{ allowing (mock).method1(); when(readiness.is("ready")); allowing (mock).doSomething(); then(readiness.is("ready")); }}); try { mock.method1(); fail("should have thrown ExpectationError"); } catch (ExpectationError expected) {} } public void testAllowsExpectationsToOccurInCorrectState() { context.checking(new Expectations() {{ allowing (mock).method1(); when(readiness.is("ready")); allowing (mock).doSomething(); then(readiness.is("ready")); }}); mock.doSomething(); mock.method1(); } public void testCanStartInASpecificState() { context.checking(new Expectations() {{ allowing (mock).method1(); when(readiness.is("ready")); }}); readiness.startsAs("ready"); mock.method1(); } public void testErrorMessagesIncludeCurrentStates() { readiness.startsAs("ethelred"); States fruitiness = context.states("fruitiness"); fruitiness.startsAs("apple"); context.checking(new Expectations() {{ allowing (mock).method1(); when(readiness.is("ready")); }}); try { mock.method1(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { String message = e.toString(); AssertThat.stringIncludes("should describe readiness state", "readiness is ethelred", message); AssertThat.stringIncludes("should describe fruitiness state", "fruitiness is apple", message); } } private static class TestException extends RuntimeException {} public void testSwitchesStateWhenMethodThrowsAnException() { context.checking(new Expectations() {{ oneOf (mock).method1(); will(throwException(new TestException())); then(readiness.is("ready")); oneOf (mock).method2(); when(readiness.is("ready")); }}); try { mock.method1(); } catch (TestException e) { } mock.method2(); } } ThrowingExceptionsAcceptanceTests.java000066400000000000000000000044341347002534600345240ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; public class ThrowingExceptionsAcceptanceTests extends TestCase { public static class CheckedException extends Exception {} public static class UncheckedException extends RuntimeException {} public static class AnError extends Error {} public static class IncompatibleCheckedException extends Exception {} public interface Throwing { void doSomething() throws CheckedException; } Mockery context = new Mockery(); Throwing mock = context.mock(Throwing.class, "mock"); public void testCanThrowCheckedExceptions() throws Exception { context.checking(new Expectations() {{ allowing (mock).doSomething(); will(throwException(new CheckedException())); }}); try { mock.doSomething(); fail("should have thrown CheckedException"); } catch (CheckedException ex) { // expected } } public void testCanThrowUncheckedExceptions() throws Exception { context.checking(new Expectations() {{ allowing (mock).doSomething(); will(throwException(new UncheckedException())); }}); try { mock.doSomething(); fail("should have thrown UncheckedException"); } catch (UncheckedException ex) { // expected } } public void testCanThrowErrors() throws Exception { context.checking(new Expectations() {{ allowing (mock).doSomething(); will(throwException(new AnError())); }}); try { mock.doSomething(); fail("should have thrown AnError"); } catch (AnError ex) { // expected } } public void testCannotThrowUndeclaredCheckedExceptions() throws Exception { context.checking(new Expectations() {{ allowing (mock).doSomething(); will(throwException(new IncompatibleCheckedException())); }}); try { mock.doSomething(); fail("should have thrown IllegalStateException"); } catch (IllegalStateException ex) { // expected } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptance/UniqueNamesAcceptanceTest.java000066400000000000000000000020161347002534600330010ustar00rootroot00000000000000package org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Mockery; import org.jmock.test.unit.support.AssertThat; public class UniqueNamesAcceptanceTest extends TestCase { Mockery context = new Mockery(); public void testCannotHaveTwoMockObjectsWithTheSameName() { context.mock(MockedType.class, "name"); try { context.mock(MockedType.class, "name"); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException e) { AssertThat.stringIncludes("should mention name", "name", e.getMessage()); } } public void testCannotHaveTwoMockObjectsWithTheSameDefaultName() { context.mock(MockedType.class); try { context.mock(MockedType.class); fail("should have thrown IllegalArgumentException"); } catch (IllegalArgumentException e) { AssertThat.stringIncludes("should mention name", "name", e.getMessage()); } } } UnorderedExpectationsAcceptanceTests.java000066400000000000000000000056701347002534600352020ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.api.ExpectationError; public class UnorderedExpectationsAcceptanceTests extends TestCase { Mockery context = new Mockery(); MockedType mock = context.mock(MockedType.class, "mock"); private void setUpUnorderedExpectations() { context.checking(new Expectations() {{ exactly(1).of (mock).method1(); exactly(1).of (mock).method2(); exactly(1).of (mock).method3(); }}); } public void testAllowsExpectedInvocationsInAnyOrder() { setUpUnorderedExpectations(); mock.method1(); mock.method2(); mock.method3(); context.assertIsSatisfied(); setUpUnorderedExpectations(); mock.method1(); mock.method3(); mock.method2(); context.assertIsSatisfied(); setUpUnorderedExpectations(); mock.method2(); mock.method1(); mock.method3(); context.assertIsSatisfied(); setUpUnorderedExpectations(); mock.method2(); mock.method3(); mock.method1(); context.assertIsSatisfied(); setUpUnorderedExpectations(); mock.method3(); mock.method1(); mock.method2(); context.assertIsSatisfied(); setUpUnorderedExpectations(); mock.method3(); mock.method2(); mock.method1(); context.assertIsSatisfied(); } public void testDoesNotAllowTooManyInvocationsOfExpectedMethods() { setUpUnorderedExpectations(); mock.method1(); try { mock.method1(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } public void testDoesNotAllowInvocationsOfUnexpectedMethods() { setUpUnorderedExpectations(); try { mock.method4(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } public void testAllExpectationsMustBeSatisfied() { setUpUnorderedExpectations(); try { context.assertIsSatisfied(); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } public void testMatchesMethodsInFirstInFirstOutOrder() { context.checking(new Expectations() {{ exactly(1).of (mock).returnString(); will(returnValue("1")); exactly(1).of (mock).returnString(); will(returnValue("2")); exactly(1).of (mock).returnString(); will(returnValue("3")); }}); assertEquals("1", mock.returnString()); assertEquals("2", mock.returnString()); assertEquals("3", mock.returnString()); } } WarnAboutMultipleThreadsAcceptanceTests.java000066400000000000000000000041561347002534600356130ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/acceptancepackage org.jmock.test.acceptance; import static org.junit.Assert.assertThat; import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import org.hamcrest.Matchers; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.lib.concurrent.Blitzer; import junit.framework.TestCase; @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) public class WarnAboutMultipleThreadsAcceptanceTests extends TestCase { BlockingQueue exceptionsOnBackgroundThreads = new LinkedBlockingQueue(); private ThreadFactory exceptionCapturingThreadFactory = new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { try { exceptionsOnBackgroundThreads.put(e); } catch (InterruptedException e1) { throw new ThreadDeath(); } } }); return t; } }; Blitzer blitzer = new Blitzer(1, Executors.newFixedThreadPool(1, exceptionCapturingThreadFactory)); public void testKillsThreadsThatTryToCallMockeryThatIsNotThreadSafe() throws InterruptedException { Mockery mockery = new Mockery(); final MockedType mock = mockery.mock(MockedType.class, "mock"); mockery.checking(new Expectations() {{ allowing (mock).doSomething(); }}); blitzer.blitz(new Runnable() { public void run() { mock.doSomething(); } }); Throwable exception = exceptionsOnBackgroundThreads.take(); assertThat(exception.getMessage(), Matchers.containsString("the Mockery is not thread-safe")); } @Override public void tearDown() { blitzer.shutdown(); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/000077500000000000000000000000001347002534600237675ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/MockeryTests.java000066400000000000000000000016721347002534600272740ustar00rootroot00000000000000package org.jmock.test.unit; import junit.framework.TestCase; import org.jmock.Mockery; import org.jmock.test.unit.support.DummyInterface; public class MockeryTests extends TestCase { public interface AnotherInterface {} public void testNamesMockObjectAfterMockedTypeIfNoNameSpecified() { Mockery mockery = new Mockery(); assertEquals("dummyInterface", mockery.mock(DummyInterface.class).toString()); assertEquals("anotherInterface", mockery.mock(AnotherInterface.class).toString()); } public void testNamesMockObjectAfterExplicitNameIfNameIsSpecified() { Mockery mockery = new Mockery(); assertEquals("firstMock", mockery.mock(DummyInterface.class, "firstMock").toString()); assertEquals("secondMock", mockery.mock(AnotherInterface.class, "secondMock").toString()); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/api/000077500000000000000000000000001347002534600245405ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/api/InvocationTests.java000066400000000000000000000273331347002534600305470ustar00rootroot00000000000000/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.api; import java.lang.reflect.Method; import java.util.Arrays; import junit.framework.TestCase; import org.jmock.api.Invocation; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.MethodFactory; public class InvocationTests extends TestCase { final Object INVOKED = new Object() { @Override public String toString() { return "INVOKED"; } }; final String METHOD_NAME = "methodName"; final Class[] ARG_TYPES = new Class[]{int.class, boolean.class}; final Class RETURN_TYPE = String.class; final Object[] ARG_VALUES = {new Integer(0), Boolean.TRUE}; final Class[] EXCEPTION_TYPES = new Class[]{InterruptedException.class, SecurityException.class}; MethodFactory methodFactory; Method method; public InvocationTests( String name ) { super(name); } @Override public void setUp() throws Exception { methodFactory = new MethodFactory(); method = methodFactory.newMethod(METHOD_NAME, ARG_TYPES, RETURN_TYPE, EXCEPTION_TYPES); } public void testCanBeConstructedFromAMethodObject() throws Exception { Invocation invocation = new Invocation(INVOKED, method, ARG_VALUES); assertSame("invoked object", INVOKED, invocation.getInvokedObject()); assertEquals("invoked method", method, invocation.getInvokedMethod()); assertEquals("name", method.getName(), invocation.getInvokedMethod().getName()); assertEquals("parameter types", Arrays.asList(method.getParameterTypes()), Arrays.asList(invocation.getInvokedMethod().getParameterTypes())); assertEquals("return type", method.getReturnType(), invocation.getInvokedMethod().getReturnType()); assertEquals("parameter count", ARG_VALUES.length, invocation.getParameterCount()); assertEquals("parameter values", Arrays.asList(ARG_VALUES), Arrays.asList(invocation.getParametersAsArray())); } public void testConstructorInterpretsNullParameterValueArrayAsZeroArguments() { Invocation invocation = new Invocation(INVOKED, method); assertEquals("expected no parameters values", 0, invocation.getParameterCount()); } public void testTestsForEqualityOnTargetAndMethodSignatureAndArguments() { Invocation invocation1 = new Invocation(INVOKED, method, ARG_VALUES); Invocation invocation2 = new Invocation(INVOKED, method, ARG_VALUES); Invocation differentTarget = new Invocation("OTHER TARGET", method, ARG_VALUES); Invocation differentMethod = new Invocation(INVOKED, methodFactory.newMethod("OTHER_" + METHOD_NAME, ARG_TYPES, RETURN_TYPE, EXCEPTION_TYPES), ARG_VALUES); Invocation differentArgValues = new Invocation(INVOKED, method, new Object[]{new Integer(1), Boolean.FALSE}); assertTrue("should be equal to itself", invocation1.equals(invocation1)); assertTrue("identical calls should be equal", invocation1.equals(invocation2)); assertFalse("should not be equal to object that is not an Invocation", invocation1.equals(new Object())); assertFalse("should not be equal to null", invocation1.equals(null)); assertFalse("should not be equal if different invoked object", invocation1.equals(differentTarget)); assertFalse("should not be equal if different method", invocation1.equals(differentMethod)); assertFalse("should not be equal if different argumentValues", invocation1.equals(differentArgValues)); } public void testFollowsEqualsHashcodeProtocol() { Invocation invocation1 = new Invocation(INVOKED, method, ARG_VALUES); Invocation invocation2 = new Invocation(INVOKED, method, ARG_VALUES); assertEquals("should have equal hash codes", invocation1.hashCode(), invocation2.hashCode()); } public void testToStringWithTwoArguments() throws Exception { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethod(METHOD_NAME, new Class[]{String.class, String.class}, void.class, EXCEPTION_TYPES), new Object[]{"arg1", "arg2"}); String result = invocation.toString(); AssertThat.stringIncludes("Should contain object name", INVOKED.toString(), result); AssertThat.stringIncludes("Should contain method name", METHOD_NAME, result); AssertThat.stringIncludes("Should contain firstArg", "arg1", result); AssertThat.stringIncludes("Should contain second Arg", "arg2", result); } public void testToStringWithStringArray() throws Exception { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethod(METHOD_NAME, new Class[]{String[].class}, void.class, EXCEPTION_TYPES), new Object[]{new String[]{"arg1", "arg2"}}); String result = invocation.toString(); AssertThat.stringIncludes("Should contain method name", METHOD_NAME, result); AssertThat.stringIncludes("Should contain args as an array", "[\"arg1\", \"arg2\"]", result); } public void testToStringWithPrimitiveArray() throws Exception { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethod(METHOD_NAME, new Class[]{long[].class}, void.class, EXCEPTION_TYPES), new Object[]{new long[]{1, 2}}); String result = invocation.toString(); AssertThat.stringIncludes("Should contain invokedMethod name", METHOD_NAME, result); AssertThat.stringIncludes("Should contain args as an array", "[<1L>, <2L>]", result); } public void testMethodToStringWithNullArg() throws Exception { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethod(METHOD_NAME, new Class[]{String.class}, void.class, EXCEPTION_TYPES), new Object[]{null}); String result = invocation.toString(); AssertThat.stringIncludes("Should contain invokedMethod name", METHOD_NAME, result); AssertThat.stringIncludes("Should contain firstArg", "null", result); } public void testMethodToStringWithObjectArg() throws Exception { final String argAsString = "TO_STRING_RESULT"; Object arg = new Object() { @Override public String toString() { return argAsString; } }; Invocation invocation = new Invocation(INVOKED, methodFactory.newMethod(METHOD_NAME, new Class[]{String.class}, void.class, EXCEPTION_TYPES), new Object[]{arg}); String result = invocation.toString(); AssertThat.stringIncludes("Should contain invokedMethod name", METHOD_NAME, result); AssertThat.stringIncludes("Should contain firstArg", argAsString, result); } public void testReturnTypeCheckFailsIfReturningValueFromVoidMethod() { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethodReturning(void.class)); try { invocation.checkReturnTypeCompatibility("string result"); } catch (IllegalStateException ex) { AssertThat.stringIncludes("should describe error", "tried to return a value from a void method", ex.getMessage()); return; } fail("should have failed"); } public void testReturnTypeCheckFailsIfReturnedValueIsIncompatible() { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethodReturning(int.class)); try { invocation.checkReturnTypeCompatibility("string result"); } catch (IllegalStateException ex) { AssertThat.stringIncludes("expected return type", int.class.toString(), ex.getMessage()); AssertThat.stringIncludes("returned value type", String.class.getName(), ex.getMessage()); return; } fail("should have failed"); } public void testReturnTypeCheckFailsWhenReturningNullFromMethodWithPrimitiveReturnType() { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethodReturning(int.class)); try { invocation.checkReturnTypeCompatibility(null); } catch (IllegalStateException ex) { AssertThat.stringIncludes("expected return type", int.class.toString(), ex.getMessage()); AssertThat.stringIncludes("null", String.valueOf((Object)null), ex.getMessage()); return; } fail("should have failed"); } public void testReturnTypeCheckAllowsReturningBoxedTypeFromMethodWithPrimitiveReturnType() { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethodReturning(int.class)); invocation.checkReturnTypeCompatibility(new Integer(0)); } public void testReturnTypeCheckAllowsReturningNullFromMethodWithNonPrimitiveReturnType() { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethodReturning(String.class)); invocation.checkReturnTypeCompatibility(null); } public void testReturnTypeCheckAllowsReturningNullFromVoidMethod() { Invocation invocation = new Invocation(INVOKED, methodFactory.newMethodReturning(void.class)); invocation.checkReturnTypeCompatibility(null); } public interface TargetInterface { public String doSomething(String arg) throws TargetException; } public static class TargetException extends Exception {} public static class Target implements TargetInterface { public String receivedArg = null; public String result = null; public TargetException exception = null; public String doSomething(String arg) throws TargetException { receivedArg = arg; if (exception != null) { throw exception; } else { return result; } } } public void testCanApplyInvocationToAnotherObject() throws Throwable { Target target = new Target(); target.result = "result"; Invocation invocation = new Invocation("receiver", TargetInterface.class.getMethod("doSomething", String.class), new Object[]{"arg"}); String actualResult = (String)invocation.applyTo(target); assertEquals("received argument", "arg", target.receivedArg); assertEquals("result returned from apply", target.result, actualResult); } public void testUnwrapsInvocationTargetExceptionsFromAppliedInvocation() throws Throwable { Target target = new Target(); target.exception = new TargetException(); Invocation invocation = new Invocation("receiver", TargetInterface.class.getMethod("doSomething", String.class), new Object[]{"arg"}); try { invocation.applyTo(target); fail("should have thrown TargetException"); } catch (TargetException ex) { // expected } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/auto/000077500000000000000000000000001347002534600247375ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/auto/internal/000077500000000000000000000000001347002534600265535ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/auto/internal/MockomaticTests.java000066400000000000000000000060441347002534600325330ustar00rootroot00000000000000package org.jmock.test.unit.auto.internal; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertThat; import junit.framework.TestCase; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.States; import org.jmock.auto.Auto; import org.jmock.auto.Mock; import org.jmock.auto.internal.Mockomatic; import org.jmock.test.acceptance.MockedType; public class MockomaticTests extends TestCase { Mockery mockery = new Mockery(); Mockomatic mockomatic = new Mockomatic(mockery); public static class ObjectWithPublicAndPrivateFields { public @Mock MockedType publicMock; private @Mock MockedType privateMock; public MockedType privateMock() { return privateMock; } } public void testCreatesMockObjectsNamedAfterTheField() { ObjectWithPublicAndPrivateFields example = new ObjectWithPublicAndPrivateFields(); mockomatic.fillIn(example); assertThat("created public mock", example.publicMock, notNullValue()); assertThat("named public mock after field", example.publicMock.toString(), equalTo("publicMock")); assertThat("created private mock", example.privateMock(), notNullValue()); assertThat("named private mock after field", example.privateMock().toString(), equalTo("privateMock")); } public static class BaseClass { public @Mock MockedType mockInBaseClass; } public static class DerivedClass extends BaseClass { public @Mock MockedType mockInDerivedClass; } public void testCreatesMockObjectsInAllClassesInInheritanceHierarchy() { DerivedClass example = new DerivedClass(); mockomatic.fillIn(example); assertThat("created mock in base class", example.mockInBaseClass, notNullValue()); assertThat("created mock in derived class", example.mockInDerivedClass, notNullValue()); } public static class WantsStates { public @Auto States stateMachine; } public void testCreatesStateMachinesNamedAfterTheField() { WantsStates example = new WantsStates(); mockomatic.fillIn(example); assertThat("created state machine", example.stateMachine, notNullValue()); assertThat("named state machine after field", example.stateMachine.toString(), startsWith("stateMachine ")); } public static class WantsSequence { public @Auto Sequence aSequence; } public void testCreatesSequencesNamedAfterTheField() { WantsSequence example = new WantsSequence(); mockomatic.fillIn(example); assertThat("created sequence", example.aSequence, notNullValue()); assertThat("named sequence after field", example.aSequence.toString(), equalTo("aSequence")); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/000077500000000000000000000000001347002534600256035ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/AllDeclaredFieldsTests.java000066400000000000000000000035741347002534600327650ustar00rootroot00000000000000package org.jmock.test.unit.internal; import junit.framework.TestCase; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; import org.jmock.internal.AllDeclaredFields; import java.lang.reflect.Field; import java.util.Collection; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class AllDeclaredFieldsTests extends TestCase { public void testReturnsEmptyListWhenNoFields() { assertThat(AllDeclaredFields.in(NoDeclaredFields.class), isEmpty()); } @SuppressWarnings("unchecked") public void testReturnsFieldsForClassWithNoParent() { assertThat(AllDeclaredFields.in(TwoDeclaredFields.class), containsInAnyOrder(aFieldCalled("field1"), aFieldCalled("field2"))); } @SuppressWarnings("unchecked") public void testReturnsFieldsForClassWithParent() { assertThat(AllDeclaredFields.in(WithInheritedFields.class), containsInAnyOrder(aFieldCalled("field1"), aFieldCalled("field2"), aFieldCalled("field3"), aFieldCalled("field4"))); } private Matcher aFieldCalled(String name) { return new FeatureMatcher(equalTo(name), "field with name", "field") { @Override protected String featureValueOf(Field actual) { return actual.getName(); } }; } private Matcher> isEmpty() { return empty(); } public static class NoDeclaredFields {} @SuppressWarnings("UnusedDeclaration") public static class TwoDeclaredFields { public int field1; @SuppressWarnings("unused") private String field2; } @SuppressWarnings("UnusedDeclaration") public static class WithInheritedFields extends TwoDeclaredFields { protected char field3; TestCase field4; } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/CardinalityTests.java000066400000000000000000000053041347002534600317360ustar00rootroot00000000000000package org.jmock.test.unit.internal; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.internal.Cardinality; import org.jmock.test.unit.support.AssertThat; public class CardinalityTests extends TestCase { public void testDescribesOnceCardinality() { AssertThat.stringIncludes("should describe exact invocation count", "once", StringDescription.toString(new Cardinality(1, 1))); } public void testDescribesExactCardinality() { AssertThat.stringIncludes("should describe exact invocation count", "exactly 2", StringDescription.toString(new Cardinality(2, 2))); } public void testDescribesAtLeastCount() { AssertThat.stringIncludes("should describe at-least invocation count", "at least 2", StringDescription.toString(new Cardinality(2, Integer.MAX_VALUE))); } public void testDescribesAtMostCount() { AssertThat.stringIncludes("should describe at-most invocation count", "at most 2", StringDescription.toString(new Cardinality(0, 2))); } public void testDescribesBetweenCount() { AssertThat.stringIncludes("should describe between invocation count", "2 to 4", StringDescription.toString(new Cardinality(2, 4))); } public void testDescribesNeverCount() { AssertThat.stringIncludes("should describe 'never' invocation count", "never", StringDescription.toString(new Cardinality(0,0))); } public void testDescribesAnyNumberCount() { final Cardinality allowed = new Cardinality(0, Integer.MAX_VALUE); AssertThat.stringIncludes("should describe 'allowed' invocation count", "allowed", StringDescription.toString(allowed)); AssertThat.stringExcludes("should not include 'expected' in description", "expected", StringDescription.toString(allowed)); } public void testHasARequiredAndMaximumNumberOfExpectedInvocations() throws Throwable { Cardinality cardinality = new Cardinality(2, 3); assertTrue(cardinality.allowsMoreInvocations(0)); assertFalse(cardinality.isSatisfied(0)); assertTrue(cardinality.allowsMoreInvocations(1)); assertFalse(cardinality.isSatisfied(1)); assertTrue(cardinality.allowsMoreInvocations(2)); assertTrue(cardinality.isSatisfied(2)); assertFalse(cardinality.allowsMoreInvocations(3)); assertTrue(cardinality.isSatisfied(3)); } } ChangeStateSideEffectTests.java000066400000000000000000000023201347002534600335170ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internalpackage org.jmock.test.unit.internal; import junit.framework.TestCase; import org.hamcrest.Description; import org.hamcrest.StringDescription; import org.jmock.internal.ChangeStateSideEffect; import org.jmock.internal.State; public class ChangeStateSideEffectTests extends TestCase { FakeState state = new FakeState(); ChangeStateSideEffect sideEffect = new ChangeStateSideEffect(state); public void testActivatesTheGivenState() { state.isActive = false; sideEffect.perform(); assertTrue("state should be active", state.isActive); } public void testDescribesItselfInTermsOfTheActivatedState() { state.descriptionText = "the-new-state"; assertEquals("description", "then the-new-state", StringDescription.toString(sideEffect)); } class FakeState implements State { public boolean isActive = false; public void activate() { isActive = true; } public boolean isActive() { return isActive; } public String descriptionText; public void describeTo(Description description) { description.appendText(descriptionText); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/FailingExampleTestCase.java000066400000000000000000000014351347002534600327720ustar00rootroot00000000000000package org.jmock.test.unit.internal; /** * This class is not meant to run as a standalone test, * but rather as input to other tests. * * @author Steve Freeman 2012 http://www.jmock.org */ public abstract class FailingExampleTestCase extends VerifyingTestCase { public static final Exception tearDownException = new Exception("tear down"); public static final Exception testException = new Exception("test"); public FailingExampleTestCase(String testName) { super(testName); } @Override public void tearDown() throws Exception { throw tearDownException; } public void testDoesNotThrowException() throws Exception { // no op } public void testThrowsExpectedException() throws Exception { throw testException; } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/FormattingTests.java000066400000000000000000000006721347002534600316100ustar00rootroot00000000000000package org.jmock.test.unit.internal; import org.jmock.internal.Formatting; import junit.framework.TestCase; public class FormattingTests extends TestCase { public void testFormatsTimesAsSingularAndPlural() { assertEquals("0 times", Formatting.times(0)); assertEquals("1 time", Formatting.times(1)); assertEquals("2 times", Formatting.times(2)); assertEquals("99 times", Formatting.times(99)); } } InStateOrderingConstraintTests.java000066400000000000000000000027631347002534600345300ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internalpackage org.jmock.test.unit.internal; import junit.framework.TestCase; import org.hamcrest.Description; import org.hamcrest.StringDescription; import org.jmock.internal.StatePredicate; import org.jmock.internal.InStateOrderingConstraint; public class InStateOrderingConstraintTests extends TestCase { FakeStatePredicate statePredicate = new FakeStatePredicate(); InStateOrderingConstraint orderingConstraint = new InStateOrderingConstraint(statePredicate); public void testAllowsInvocationWhenStateIsActive() { statePredicate.isActive = true; assertTrue("should allow invocation when state predicate is true", orderingConstraint.allowsInvocationNow()); statePredicate.isActive = false; assertTrue("should not allow invocation when state predicate is false", !orderingConstraint.allowsInvocationNow()); } public void testDescribesItselfInTermsOfTheStatePredicatesDescription() { statePredicate.descriptionText = "the-predicate"; assertEquals("description", "when the-predicate", StringDescription.toString(orderingConstraint)); } class FakeStatePredicate implements StatePredicate { public boolean isActive; public boolean isActive() { return isActive; } public String descriptionText; public void describeTo(Description description) { description.appendText(descriptionText); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/InvocationDispatcherTests.java000066400000000000000000000247561347002534600336270ustar00rootroot00000000000000package org.jmock.test.unit.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.jmock.api.Expectation; import org.jmock.api.ExpectationError; import org.jmock.api.Invocation; import org.jmock.api.InvocationDispatcher; import org.jmock.internal.StateMachine; import org.jmock.lib.concurrent.SynchronisingInvocationDispatcherWrapper; import org.jmock.lib.concurrent.UnsynchronisedInvocationDispatcher; import org.jmock.test.unit.support.MethodFactory; import org.jmock.test.unit.support.MockExpectation; import junit.framework.TestCase; public class InvocationDispatcherTests extends TestCase { // Avoid multi threaeding tests deadlocking // Adjust timeout for debugging private static final TimeUnit TIMEOUT_UNIT = TimeUnit.SECONDS; private static final int TIMEOUT = 2; MethodFactory methodFactory = new MethodFactory(); Invocation invocation = new Invocation( "invokedObject", methodFactory.newMethod("invokedMethod"), Invocation.NO_PARAMETERS); static final boolean NOT_RELEVANT = true; public void testInvokesFirstMatchingExpectationInGroup() throws Throwable { MockExpectation expectation1 = new MockExpectation(false, NOT_RELEVANT, NOT_RELEVANT); MockExpectation expectation2 = new MockExpectation(true, NOT_RELEVANT, NOT_RELEVANT); MockExpectation expectation3 = new MockExpectation(true, NOT_RELEVANT, NOT_RELEVANT); UnsynchronisedInvocationDispatcher dispatcher = new UnsynchronisedInvocationDispatcher(); dispatcher.add(expectation1); dispatcher.add(expectation2); dispatcher.add(expectation3); expectation1.shouldNotBeInvoked(); expectation2.shouldBeInvokedWith(invocation); expectation3.shouldNotBeInvoked(); dispatcher.dispatch(invocation); assertTrue("expectation2 should have been invoked", expectation2.wasInvoked); } public void testThrowsExpectationErrorIfNoExpectationsMatchAnInvocation() throws Throwable { MockExpectation expectation1 = new MockExpectation(false, NOT_RELEVANT, NOT_RELEVANT); MockExpectation expectation2 = new MockExpectation(false, NOT_RELEVANT, NOT_RELEVANT); MockExpectation expectation3 = new MockExpectation(false, NOT_RELEVANT, NOT_RELEVANT); UnsynchronisedInvocationDispatcher dispatcher = new UnsynchronisedInvocationDispatcher(); dispatcher.add(expectation1); dispatcher.add(expectation2); dispatcher.add(expectation3); expectation1.shouldNotBeInvoked(); expectation2.shouldNotBeInvoked(); expectation3.shouldNotBeInvoked(); try { dispatcher.dispatch(invocation); fail("should have thrown ExpectationError"); } catch (ExpectationError e) { // expected } } public void testIsSatisfiedOnlyIfAllExpectationsAreSatisfied() { UnsynchronisedInvocationDispatcher dispatcherAll = new UnsynchronisedInvocationDispatcher(); dispatcherAll.add(new MockExpectation(NOT_RELEVANT, true, NOT_RELEVANT)); dispatcherAll.add(new MockExpectation(NOT_RELEVANT, true, NOT_RELEVANT)); assertTrue("should be satisfied if all expectations are satisfied", dispatcherAll.isSatisfied()); UnsynchronisedInvocationDispatcher dispatcher1 = new UnsynchronisedInvocationDispatcher(); dispatcher1.add(new MockExpectation(NOT_RELEVANT, true, NOT_RELEVANT)); dispatcher1.add(new MockExpectation(NOT_RELEVANT, false, NOT_RELEVANT)); assertFalse("should not be satisfied if first expectation is not satisfied", dispatcher1.isSatisfied()); UnsynchronisedInvocationDispatcher dispatcher2 = new UnsynchronisedInvocationDispatcher(); dispatcher2.add(new MockExpectation(NOT_RELEVANT, false, NOT_RELEVANT)); dispatcher2.add(new MockExpectation(NOT_RELEVANT, true, NOT_RELEVANT)); assertFalse("should not be satisfied if second expectation is not satisfied", dispatcher2.isSatisfied()); UnsynchronisedInvocationDispatcher dispatcherNone = new UnsynchronisedInvocationDispatcher(); dispatcherNone.add(new MockExpectation(NOT_RELEVANT, false, NOT_RELEVANT)); dispatcherNone.add(new MockExpectation(NOT_RELEVANT, true, NOT_RELEVANT)); assertFalse("should not be satisfied if no expectations are satisfied", dispatcherNone.isSatisfied()); } /** * Resolves issue 104 * * @throws Throwable */ public void testUnsynchronisedInvocationDispatcherHandlesAddingExpectationsWhileOtherTestsDispatch() throws Throwable { final CyclicBarrier barrier = new CyclicBarrier(2); MockExpectation expectation1 = new MockExpectation(true, NOT_RELEVANT, NOT_RELEVANT); MockExpectation expectation2 = new MockExpectation(false, NOT_RELEVANT, NOT_RELEVANT); Collection expectations = new CriticalSectionForcingCollectionWrapper<>( new CopyOnWriteArrayList(), barrier); Collection stateMachines = new CriticalSectionForcingCollectionWrapper<>( new ArrayList(), barrier); final UnsynchronisedInvocationDispatcher dispatcher = new UnsynchronisedInvocationDispatcher(expectations, stateMachines); new Thread(new Runnable() { @Override public void run() { try { barrier.await(TIMEOUT, TIMEOUT_UNIT); barrier.await(TIMEOUT, TIMEOUT_UNIT); // now the expectation one has been added dispatcher.dispatch(invocation); barrier.await(TIMEOUT, TIMEOUT_UNIT); } catch (Throwable e) { // will throw a ConcurrentModification Exception unless a multithreaded strategy // is used throw new RuntimeException(e); } } }, "Concurrent Dispatch").start(); // expect dispatch dispatcher.add(expectation1); // await is satisfied check dispatcher.add(expectation2); barrier.await(TIMEOUT, TIMEOUT_UNIT); expectation1.shouldBeInvokedWith(invocation); assertTrue("expectation1 should have been invoked", expectation1.wasInvoked); } public void testSynchronisedInvocationDispatcherBlocksAddingExpectationsWhileOtherTestsDispatch() throws Throwable { final CyclicBarrier barrier = new CyclicBarrier(2); MockExpectation expectation1 = new MockExpectation(true, NOT_RELEVANT, NOT_RELEVANT); MockExpectation expectation2 = new MockExpectation(false, NOT_RELEVANT, NOT_RELEVANT); // intentionally use array list as the wrapper should synchronise access final InvocationDispatcher dispatcher = new SynchronisingInvocationDispatcherWrapper( new UnsynchronisedInvocationDispatcher(new ArrayList(), new ArrayList())); // expect dispatch dispatcher.add(expectation1); new Thread(new Runnable() { @Override public void run() { try { dispatcher.dispatch(invocation); barrier.await(); } catch (Throwable e) { throw new RuntimeException(e); } } }, "Concurrent Dispatch").start(); // await until dispatch barrier.await(); dispatcher.add(expectation2); expectation1.shouldBeInvokedWith(invocation); assertTrue("expectation1 should have been invoked", expectation1.wasInvoked); } private class CriticalSectionForcingCollectionWrapper implements Collection { private final Collection delegate; private final CyclicBarrier barrier; CriticalSectionForcingCollectionWrapper(Collection delegate, CyclicBarrier barrier) { this.delegate = delegate; this.barrier = barrier; } private void await() { try { // we want the expectation check to have got the iterator // but not progressed checking barrier.await(TIMEOUT, TIMEOUT_UNIT); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (BrokenBarrierException e) { throw new RuntimeException(e); } catch (TimeoutException e) { throw new RuntimeException(e); } } public int size() { return delegate.size(); } public boolean isEmpty() { return delegate.isEmpty(); } public boolean contains(Object o) { return delegate.contains(o); } public Iterator iterator() { Iterator reply = delegate.iterator(); await(); // expectation add follows this await(); // wait for add to complete return reply; } public Object[] toArray() { return delegate.toArray(); } public U[] toArray(U[] a) { return delegate.toArray(a); } public boolean add(T e) { // Make sure iterator is called before adding await(); boolean reply = delegate.add(e); // Make sure iterator returns after adding await(); return reply; } public boolean remove(Object o) { return delegate.remove(o); } public boolean containsAll(Collection c) { return delegate.containsAll(c); } public boolean addAll(Collection c) { return delegate.addAll(c); } public boolean removeAll(Collection c) { return delegate.removeAll(c); } public boolean retainAll(Collection c) { return delegate.retainAll(c); } public void clear() { delegate.clear(); } public boolean equals(Object o) { return delegate.equals(o); } public int hashCode() { return delegate.hashCode(); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/InvocationDiverterTests.java000066400000000000000000000041531347002534600333120ustar00rootroot00000000000000package org.jmock.test.unit.internal; import junit.framework.TestCase; import org.jmock.api.Invocation; import org.jmock.internal.InvocationDiverter; import org.jmock.test.unit.support.StubInvokable; public class InvocationDiverterTests extends TestCase { public interface TargetInterface { void doSomething(); } public class Target implements TargetInterface { public boolean wasInvoked = false; public void doSomething() { wasInvoked = true; } } public interface OtherInterface { void doSomethingElse(); } Target target = new Target(); StubInvokable next = new StubInvokable(); InvocationDiverter diverter = new InvocationDiverter(TargetInterface.class, target, next); public void testAppliesInvocationToGivenObjectIfInvokedMethodDeclaredInGivenClass() throws Throwable { Invocation invocation = new Invocation("invokedObject", TargetInterface.class.getMethod("doSomething"), Invocation.NO_PARAMETERS); diverter.invoke(invocation); assertTrue("target should have been invoked", target.wasInvoked); assertTrue("next should not have been invoked", !next.wasInvoked); } public void testPassesInvocationToNextIfInvocationNotDeclaredInGivenClass() throws Throwable { Invocation invocation = new Invocation("invokedObject", OtherInterface.class.getMethod("doSomethingElse"), Invocation.NO_PARAMETERS); diverter.invoke(invocation); assertTrue("target should not have been invoked", !target.wasInvoked); assertTrue("next should have been invoked", next.wasInvoked); } public void testDelegatesToStringToNext() { next.toStringResult = "next.toStringResult"; assertEquals(next.toStringResult, diverter.toString()); } } InvocationExpectationTests.java000066400000000000000000000273531347002534600337410ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internalpackage org.jmock.test.unit.internal; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.sameInstance; import java.lang.reflect.Method; import junit.framework.TestCase; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.jmock.api.Invocation; import org.jmock.internal.Cardinality; import org.jmock.internal.InvocationExpectation; import org.jmock.internal.OrderingConstraint; import org.jmock.internal.SideEffect; import org.jmock.internal.matcher.AllParametersMatcher; import org.jmock.lib.action.ReturnValueAction; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.MethodFactory; import org.jmock.test.unit.support.MockAction; public class InvocationExpectationTests extends TestCase { MethodFactory methodFactory = new MethodFactory(); InvocationExpectation expectation = new InvocationExpectation(); Object targetObject = "targetObject"; Method method = methodFactory.newMethod("method"); public Matcher mockMatcher(final T expected, final boolean result) { return new BaseMatcher() { public boolean matches(Object actual) { assertTrue("expected " + expected + ", was " + actual, equalTo(expected).matches(actual)); return result; } public void describeTo(Description description) { } }; } public void testMatchesAnythingByDefault() { assertTrue("should match", expectation.matches( new Invocation(new Object(), methodFactory.newMethod("method"), Invocation.NO_PARAMETERS))); assertTrue("should match", expectation.matches( new Invocation(new Object(), methodFactory.newMethod("anotherMethod"), new Object[]{1,2,3,4}))); } public void testCanConstrainTargetObject() { Object anotherObject = "anotherObject"; expectation.setObjectMatcher(sameInstance(targetObject)); assertTrue("should match", expectation.matches(new Invocation(targetObject, method, Invocation.NO_PARAMETERS))); assertTrue("should not match", !expectation.matches(new Invocation(anotherObject, method, Invocation.NO_PARAMETERS))); } public void testCanConstrainMethod() { Method anotherMethod = methodFactory.newMethod("anotherMethod"); expectation.setMethodMatcher(equalTo(method)); assertTrue("should match", expectation.matches(new Invocation(targetObject, method, Invocation.NO_PARAMETERS))); assertTrue("should not match", !expectation.matches(new Invocation(targetObject, anotherMethod, Invocation.NO_PARAMETERS))); } public void testCanConstrainArguments() { Object[] args = {1,2,3,4}; Object[] differentArgs = {5,6,7,8}; Object[] differentArgCount = {1,2,3}; Object[] noArgs = null; expectation.setParametersMatcher(new AllParametersMatcher(args)); assertTrue("should match", expectation.matches(new Invocation(targetObject, method, args))); assertTrue("should not match", !expectation.matches(new Invocation(targetObject, method, differentArgs))); assertTrue("should not match", !expectation.matches(new Invocation(targetObject, method, differentArgCount))); assertTrue("should not match", !expectation.matches(new Invocation(targetObject, method, noArgs))); } public void testDoesNotMatchIfMatchingCountMatcherDoesNotMatch() throws Throwable { Invocation invocation = new Invocation("targetObject", methodFactory.newMethod("method"), Invocation.NO_PARAMETERS); int maxInvocationCount = 3; expectation.setCardinality(new Cardinality(0, maxInvocationCount)); int i; for (i = 0; i < maxInvocationCount; i++) { assertTrue("should match after " + i +" invocations", expectation.matches(invocation)); expectation.invoke(invocation); } assertFalse("should not match after " + i + " invocations", expectation.matches(invocation)); } public void testMustMeetTheRequiredInvocationCountButContinuesToMatch() throws Throwable { Invocation invocation = new Invocation("targetObject", methodFactory.newMethod("method")); int requiredInvocationCount = 3; expectation.setCardinality(new Cardinality(requiredInvocationCount, Integer.MAX_VALUE)); int i; for (i = 0; i < requiredInvocationCount; i++) { assertTrue("should match after " + i +" invocations", expectation.matches(invocation)); assertFalse("should not be satisfied after " + i +" invocations", expectation.isSatisfied()); expectation.invoke(invocation); } assertTrue("should match after " + i +" invocations", expectation.matches(invocation)); assertTrue("should be satisfied after " + i +" invocations", expectation.isSatisfied()); } public void testPerformsActionWhenInvoked() throws Throwable { final Method stringReturningMethod = methodFactory.newMethod("tester", new Class[0], String.class, new Class[0]); Invocation invocation = new Invocation(targetObject, stringReturningMethod, Invocation.NO_PARAMETERS); MockAction action = new MockAction(); action.expectInvoke = true; action.expectedInvocation = invocation; action.result = "result"; expectation.setAction(action); Object actualResult = expectation.invoke(invocation); assertSame("actual result", action.result, actualResult); assertTrue("action1 was invoked", action.wasInvoked); } public void testPerformsSideEffectsWhenInvoked() throws Throwable { FakeSideEffect sideEffect1 = new FakeSideEffect(); FakeSideEffect sideEffect2 = new FakeSideEffect(); expectation.addSideEffect(sideEffect1); expectation.addSideEffect(sideEffect2); Invocation invocation = new Invocation("targetObject", methodFactory.newMethod("method")); expectation.invoke(invocation); assertTrue("side effect 1 should have been performed", sideEffect1.wasPerformed); assertTrue("side effect 2 should have been performed", sideEffect2.wasPerformed); } public void testDescriptionIncludesSideEffects() { FakeSideEffect sideEffect1 = new FakeSideEffect(); FakeSideEffect sideEffect2 = new FakeSideEffect(); sideEffect1.descriptionText = "side-effect-1"; sideEffect2.descriptionText = "side-effect-2"; expectation.addSideEffect(sideEffect1); expectation.addSideEffect(sideEffect2); String description = StringDescription.toString(expectation); AssertThat.stringIncludes("should include description of sideEffect1", sideEffect1.descriptionText, description); AssertThat.stringIncludes("should include description of sideEffect2", sideEffect2.descriptionText, description); } public void testReturnsNullIfHasNoActionsWhenInvoked() throws Throwable { Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS); Object actualResult = expectation.invoke(invocation); assertNull("should have returned null", actualResult); } public void testFailsIfActionReturnsAnIncompatibleValue() throws Throwable { final Method stringReturningMethod = methodFactory.newMethod("tester", new Class[0], String.class, new Class[0]); Invocation invocation = new Invocation(targetObject, stringReturningMethod, Invocation.NO_PARAMETERS); ReturnValueAction action = new ReturnValueAction(new Integer(666)); expectation.setAction(action); try { expectation.invoke(invocation); fail("Should have thrown an IllegalStateException"); } catch (IllegalStateException expected) { AssertThat.stringIncludes("Shows returned type", "java.lang.Integer", expected.getMessage()); AssertThat.stringIncludes("Shows expected return type", "java.lang.String", expected.getMessage()); } } /** * @see CardinalityTests.testHasARequiredAndMaximumNumberOfExpectedInvocations */ public void testHasARequiredAndMaximumNumberOfExpectedInvocations() throws Throwable { Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS); expectation.setCardinality(new Cardinality(1, 1)); assertTrue(expectation.allowsMoreInvocations()); assertFalse(expectation.isSatisfied()); expectation.invoke(invocation); expectation.invoke(invocation); assertFalse(expectation.allowsMoreInvocations()); assertTrue(expectation.isSatisfied()); } public void testMatchesIfAllOrderingConstraintsMatch() { FakeOrderingConstraint orderingConstraint1 = new FakeOrderingConstraint(); FakeOrderingConstraint orderingConstraint2 = new FakeOrderingConstraint(); expectation.addOrderingConstraint(orderingConstraint1); expectation.addOrderingConstraint(orderingConstraint2); Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS); orderingConstraint1.allowsInvocationNow = true; orderingConstraint2.allowsInvocationNow = true; assertTrue(expectation.matches(invocation)); orderingConstraint1.allowsInvocationNow = true; orderingConstraint2.allowsInvocationNow = false; assertFalse(expectation.matches(invocation)); orderingConstraint1.allowsInvocationNow = false; orderingConstraint2.allowsInvocationNow = true; assertFalse(expectation.matches(invocation)); orderingConstraint1.allowsInvocationNow = false; orderingConstraint2.allowsInvocationNow = false; assertFalse(expectation.matches(invocation)); } public void testDescriptionIncludesCardinality() { final Cardinality cardinality = new Cardinality(2, 2); expectation.setCardinality(cardinality); AssertThat.stringIncludes("should include cardinality description", StringDescription.toString(cardinality), StringDescription.toString(expectation)); } public void testDescribesNumberOfInvocationsReceived() throws Throwable { Invocation invocation = new Invocation(targetObject, method, Invocation.NO_PARAMETERS); expectation.setCardinality(new Cardinality(2,3)); AssertThat.stringIncludes("should describe as not invoked", "never invoked", StringDescription.toString(expectation)); expectation.invoke(invocation); AssertThat.stringIncludes("should describe as invoked 1 time", "invoked 1 time", StringDescription.toString(expectation)); expectation.invoke(invocation); expectation.invoke(invocation); AssertThat.stringIncludes("should describe as invoked 3 times", "invoked 3 times", StringDescription.toString(expectation)); } public static class FakeOrderingConstraint implements OrderingConstraint { public boolean allowsInvocationNow; public boolean allowsInvocationNow() { return allowsInvocationNow; } public String descriptionText; public void describeTo(Description description) { description.appendText(descriptionText); } } class FakeSideEffect implements SideEffect { public boolean wasPerformed = false; public void perform() { wasPerformed = true; } public String descriptionText; public void describeTo(Description description) { description.appendText(descriptionText); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/MockObjectTestCase.java000066400000000000000000000105611347002534600321250ustar00rootroot00000000000000package org.jmock.test.unit.internal; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.States; import org.jmock.api.Imposteriser; import org.jmock.api.MockObjectNamingScheme; import org.jmock.auto.internal.Mockomatic; import org.jmock.internal.ExpectationBuilder; import org.jmock.lib.AssertionErrorTranslator; /** * A {@link junit.framework.TestCase} that supports testing with mock objects. * It wraps a {@link org.jmock.Mockery} and automatically asserts that * all expectations have been met at the end of the test before * {@link junit.framework.TestCase#tearDown()} is called. * * @author npryce */ public abstract class MockObjectTestCase extends VerifyingTestCase { private final Mockery context = new Mockery(); public MockObjectTestCase() { super(); initialise(); } public MockObjectTestCase(String name) { super(name); initialise(); } private void initialise() { context.setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE); addVerifier(new Runnable() { public void run() { context.assertIsSatisfied(); } }); Mockomatic mockomatic = new Mockomatic(context); mockomatic.fillIn(this); } public Mockery context() { return context; } /** * Sets the result returned for the given type when no return value has been explicitly * specified in the expectation. * * @param type * The type for which to return result. * @param result * The value to return when a method of return type type * is invoked for which an explicit return value has has not been specified. */ public void setDefaultResultForType(Class type, Object result) { context.setDefaultResultForType(type, result); } /** * Changes the imposteriser used to adapt mock objects to the mocked type. * * The default imposteriser allows a test to mock interfaces but not * classes, so you'll have to plug a different imposteriser into the * Mockery if you want to mock classes. */ public void setImposteriser(Imposteriser imposteriser) { context.setImposteriser(imposteriser); } /** * Changes the naming scheme used to generate names for mock objects that * have not been explicitly named in the test. * * The default naming scheme names mock objects by lower-casing the first * letter of the class name, so a mock object of type BananaSplit will be * called "bananaSplit" if it is not explicitly named in the test. */ public void setNamingScheme(MockObjectNamingScheme namingScheme) { context.setNamingScheme(namingScheme); } /** * Specify expectations upon the mock objects in the test. * */ public void checking(ExpectationBuilder expectations) { context.checking(expectations); } /** * Create a mock object of type T with an explicit name. * * @param typeToMock * The type to be mocked * @param name * The name of the new mock object that is used to identify the mock object * in error messages * @return * A new mock object of type */ public T mock(Class typeToMock, String name) { return context.mock(typeToMock, name); } /** * Create a mock object of type T with a name derived from its type. * * @param typeToMock * The type to be mocked * @return * A new mock object of type */ public T mock(Class typeToMock) { return context.mock(typeToMock); } /** * Returns a new sequence that is used to constrain the order in which * expectations can occur. * * @param name * The name of the sequence. * @return * A new sequence with the given name. */ public Sequence sequence(String name) { return context.sequence(name); } /** * Returns a new state machine that is used to constrain the order in which * expectations can occur. * * @param name * The name of the state machine. * @return * A new state machine with the given name. */ public States states(String name) { return context.states(name); } } ProxiedObjectIdentityTests.java000066400000000000000000000054331347002534600336720ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internalpackage org.jmock.test.unit.internal; import java.lang.reflect.Method; import junit.framework.TestCase; import org.jmock.api.Invocation; import org.jmock.internal.FakeObjectMethods; import org.jmock.internal.ProxiedObjectIdentity; import org.jmock.test.acceptance.MockedType; import org.jmock.test.unit.support.StubInvokable; public class ProxiedObjectIdentityTests extends TestCase { String name = "name"; StubInvokable next = new StubInvokable(); FakeObjectMethods id = new ProxiedObjectIdentity(next); Object invokedObject = "invokedObject"; Object otherObject = "otherObject"; public ProxiedObjectIdentityTests() { next.toStringResult = name; } public void testImplementsEqualsByComparingReferences() throws Throwable { Method equals = Object.class.getMethod("equals", Object.class); assertEquals("should equal same object", Boolean.TRUE, id.invoke(new Invocation(invokedObject, equals, invokedObject))); assertEquals("should not equal another object", Boolean.FALSE, id.invoke(new Invocation(invokedObject, equals, otherObject))); assertEquals("should not equal null", Boolean.FALSE, id.invoke(new Invocation(invokedObject, equals, (Object)null))); } public void testImplementsHashCodeToReturnIdentityHashCode() throws Throwable { Method hashCode = Object.class.getMethod("hashCode"); assertEquals(System.identityHashCode(invokedObject), id.invoke(new Invocation(invokedObject, hashCode))); } public void testDelegatesToStringToNextInvokable() throws Throwable { Method toString = Object.class.getMethod("toString"); assertEquals("an Invocation of toString", next.toStringResult, id.invoke(new Invocation(invokedObject, toString))); assertEquals("directly invoked toString", next.toStringResult, id.toString()); } public void testPassesOtherInvocationsToNextInvokable() throws Throwable { Method doSomething = MockedType.class.getMethod("doSomething"); id.invoke(new Invocation(invokedObject, doSomething)); assertTrue("should have invoked next", next.wasInvoked); } public static class ClassOverridingToString { @Override public String toString() { return "a different toString"; } } public void testPerformsObjectMethodsEvenWhenTheyAreOverridden() throws Throwable { Method overriddenToString = ClassOverridingToString.class.getMethod("toString"); assertEquals("an Invocation of overridden toString", next.toStringResult, id.invoke(new Invocation(invokedObject, overriddenToString))); } } ReturnDefaultCollectionTests.java000066400000000000000000000071031347002534600342130ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internalpackage org.jmock.test.unit.internal; import org.hamcrest.Matcher; import org.jmock.internal.ReturnDefaultValueAction; import org.junit.Test; import javax.xml.ws.handler.LogicalMessageContext; import java.beans.beancontext.BeanContext; import java.beans.beancontext.BeanContextServices; import java.util.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.jmock.test.unit.internal.ReturnDefaultValueActionTests.invocationReturning; /** * @author Steve Freeman 2013 http://www.jmock.org * https://github.com/jmock-developers/jmock-library/issues/9 */ public class ReturnDefaultCollectionTests { abstract static class AbstractCollection implements Collection {} private static final Matcher IS_PROXY_CLASS = hasProperty("canonicalName", containsString("Proxy")); private final ReturnDefaultValueAction action = new ReturnDefaultValueAction(); @SuppressWarnings("unchecked") @Test public void returnsANewInstanceForEachCall() throws Throwable { final ArrayList firstInstance = returnedArrayList(); firstInstance.add(new Object()); assertThat(returnedArrayList(), is(empty())); } @Test public void returnsNewInstanceOfIterableClasses() throws Throwable { returnsInstanceForType(ArrayList.class, ArrayList.class); returnsInstanceForType(PriorityQueue.class, PriorityQueue.class); } @Test public void returnsNewInstanceOfMapClasses() throws Throwable { returnsInstanceForType(HashMap.class, HashMap.class); returnsInstanceForType(Properties.class, Properties.class); } @Test public void returnsNewInstanceConformingToCollectionInterface() throws Throwable { returnsInstanceForType(List.class, LinkedList.class); returnsInstanceForType(Set.class, TreeSet.class); returnsInstanceForType(NavigableSet.class, TreeSet.class); returnsInstanceForType(SortedSet.class, TreeSet.class); returnsInstanceForType(Queue.class, LinkedList.class); returnsInstanceForType(Deque.class, LinkedList.class); } // https://github.com/jmock-developers/jmock-library/issues/46 @Test public void imposterisesBeanContextTypesToAvoidMissingTypesInAndroid() throws Throwable { assertThat(action.invoke(invocationReturning(BeanContext.class)).getClass(), IS_PROXY_CLASS); assertThat(action.invoke(invocationReturning(BeanContextServices.class)).getClass(), IS_PROXY_CLASS); } @Test public void returnsNewInstanceConformingToMapType() throws Throwable { returnsInstanceForType(Map.class, TreeMap.class); returnsInstanceForType(SortedMap.class, TreeMap.class); returnsInstanceForType(NavigableMap.class, TreeMap.class); } @Test public void imposterisesUnsupportedMapTypes() throws Throwable { assertThat(action.invoke(invocationReturning(LogicalMessageContext.class)).getClass(), IS_PROXY_CLASS); } @Test public void returnsNullForAbstractCollections() throws Throwable { assertThat(action.invoke(invocationReturning(AbstractCollection.class)), is(nullValue())); } private void returnsInstanceForType(Class declaredType, Class expectedType) throws Throwable { assertThat( action.invoke(invocationReturning(declaredType)), instanceOf(expectedType)); } @SuppressWarnings("unchecked") private ArrayList returnedArrayList() throws Throwable { return (ArrayList) action.invoke(invocationReturning(ArrayList.class)); } } ReturnDefaultValueActionTests.java000066400000000000000000000120631347002534600343330ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.internal; import org.hamcrest.StringDescription; import org.jmock.api.Imposteriser; import org.jmock.api.Invocation; import org.jmock.internal.ReturnDefaultValueAction; import org.jmock.lib.JavaReflectionImposteriser; import org.jmock.test.unit.support.MethodFactory; import org.junit.Test; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.*; public class ReturnDefaultValueActionTests { static final Object[] NO_ARG_VALUES = new Object[0]; static final MethodFactory METHOD_FACTORY = new MethodFactory(); private final ReturnDefaultValueAction action = new ReturnDefaultValueAction(); @Test public void writesDescriptionToStringBuffer() { assertThat(StringDescription.toString(action), containsString("returns a default value")); } @Test public void returnsUsefulDefaultResultsForBasicTypes() throws Throwable { returnsValueForType(boolean.class, Boolean.FALSE); returnsValueForType(void.class, null); returnsValueForType(byte.class, (byte) 0); returnsValueForType(short.class, (short) 0); returnsValueForType(int.class, 0); returnsValueForType(long.class, 0L); returnsValueForType(char.class, '\0'); returnsValueForType(float.class, 0.0F); returnsValueForType(double.class, 0.0); returnsValueForType(Boolean.class, Boolean.FALSE); returnsValueForType(Byte.class, (byte) 0); returnsValueForType(Short.class, (short) 0); returnsValueForType(Integer.class, 0); returnsValueForType(Long.class, 0L); returnsValueForType(Character.class, '\0'); returnsValueForType(Float.class, 0.0F); returnsValueForType(Double.class, 0.0); returnsValueForType(String.class, ""); assertNotNull("return value for Object return type", action.invoke(invocationReturning(Object.class))); } @Test public void returnsEmptyArrayForAllArrayTypes() throws Throwable { final int[] defaultArrayForPrimitiveType = (int[])action.invoke(invocationReturning(int[].class)); assertEquals("empty array", 0, defaultArrayForPrimitiveType.length); Object[] defaultArrayForReferenceType = (Object[])action.invoke(invocationReturning(Object[].class)); assertEquals("should be empty array", 0, defaultArrayForReferenceType.length); } // Inspired by http://www.c2.com/cgi/wiki?JavaNullProxy @Test public void imposteriserThatCanImposteriseReturnTypeReturnsNewMockObjectWithSameReturnDefaultValueAction() throws Throwable { final int intResult = -1; final Imposteriser imposteriser = new JavaReflectionImposteriser() { @Override public boolean canImposterise(Class c) { return c == ReturnsAnInt.class; } }; final ReturnDefaultValueAction imposterised = new ReturnDefaultValueAction(imposteriser); imposterised.addResult(int.class, intResult); final ReturnsAnInt result = (ReturnsAnInt)imposterised.invoke(invocationReturning(ReturnsAnInt.class)); assertEquals(intResult, result.returnInt()); assertNull("imposteriser cannot imposterise a Runnable", imposterised.invoke(invocationReturning(Runnable.class))); } @Test public void defaultResultsCanBeExplicitlyOverriddenByType() throws Throwable { final int newDefaultIntResult = 20; final String newDefaultStringResult = "hello"; action.addResult(String.class, newDefaultStringResult); action.addResult(int.class, newDefaultIntResult); assertEquals("registered value for string result type", newDefaultStringResult, action.invoke(invocationReturning(String.class))); assertEquals("registered value for int result type", newDefaultIntResult, action.invoke(invocationReturning(int.class))); } @Test public void anExplicitlyRegisteredResultOverridesThePreviousResultForTheSameType() throws Throwable { action.addResult(String.class, "result1"); action.addResult(String.class, "result2"); assertEquals("result2", action.invoke(invocationReturning(String.class))); } @Test public void invocationWithAnUnsupportedReturnTypeReturnsNull() throws Throwable { assertNull(action.invoke(invocationReturning(UnsupportedReturnType.class))); } private void returnsValueForType(Class resultType, Object resultValue) throws Throwable { assertEquals("for type: " + resultType.getSimpleName(), resultValue, action.invoke(invocationReturning(resultType))); } public static Invocation invocationReturning(Class resultType) { return new Invocation("INVOKED-OBJECT", METHOD_FACTORY.newMethodReturning(resultType), NO_ARG_VALUES); } private static class UnsupportedReturnType { } private static interface ReturnsAnInt { int returnInt(); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/StateMachineTests.java000066400000000000000000000121241347002534600320360ustar00rootroot00000000000000package org.jmock.test.unit.internal; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.States; import org.jmock.internal.StateMachine; public class StateMachineTests extends TestCase { States stateMachine = new StateMachine("stateMachineName"); public void testIsInitiallyInNoState() { for (String state : anyState) { assertFalse("should not report being in state " + state, stateMachine.is(state).isActive()); assertTrue("should report not being in state " + state, stateMachine.isNot(state).isActive()); } } public void testCanEnterAState() { String state = "A"; Set otherStates = except(anyState, state); stateMachine.is(state).activate(); assertTrue("should report being in state " + state, stateMachine.is(state).isActive()); assertFalse("should not report not being in state " + state, stateMachine.isNot(state).isActive()); for (String otherState : otherStates) { assertFalse("should not report being in state " + otherState, stateMachine.is(otherState).isActive()); assertTrue("should report not being in state " + otherState, stateMachine.isNot(otherState).isActive()); } } public void testCanChangeState() { String state = "B"; Set otherStates = except(anyState, state); stateMachine.is("A").activate(); stateMachine.is(state).activate(); assertTrue("should report being in state " + state, stateMachine.is(state).isActive()); assertFalse("should not report not being in state " + state, stateMachine.isNot(state).isActive()); for (String otherState : otherStates) { assertFalse("should not report being in state " + otherState, stateMachine.is(otherState).isActive()); assertTrue("should report not being in state " + otherState, stateMachine.isNot(otherState).isActive()); } } public void testCanBePutIntoAnInitialState() { String initialState = "A"; Set otherStates = except(anyState, initialState); stateMachine.startsAs(initialState); assertTrue("should report being in state " + initialState, stateMachine.is(initialState).isActive()); assertFalse("should not report not being in state " + initialState, stateMachine.isNot(initialState).isActive()); for (String otherState : otherStates) { assertFalse("should not report being in state " + otherState, stateMachine.is(otherState).isActive()); assertTrue("should report not being in state " + otherState, stateMachine.isNot(otherState).isActive()); } } public void testCanBePutIntoANewState() { String nextState = "B"; Set otherStates = except(anyState, nextState); stateMachine.startsAs("A"); stateMachine.become(nextState); assertTrue("should report being in state " + nextState, stateMachine.is(nextState).isActive()); assertFalse("should not report not being in state " + nextState, stateMachine.isNot(nextState).isActive()); for (String otherState : otherStates) { assertFalse("should not report being in state " + otherState, stateMachine.is(otherState).isActive()); assertTrue("should report not being in state " + otherState, stateMachine.isNot(otherState).isActive()); } } public void testDescribesItselfAsNameAndCurrentState() { assertEquals("description with no current state", "stateMachineName has no current state", StringDescription.toString(stateMachine)); stateMachine.is("stateName").activate(); assertEquals("description with a current state", "stateMachineName is stateName", StringDescription.toString(stateMachine)); assertEquals("description with a current state from toString", "stateMachineName is stateName", stateMachine.toString()); } public void testHasSelfDescribingStates() { assertEquals("stateMachineName is A", StringDescription.toString(stateMachine.is("A"))); assertEquals("stateMachineName is not A", StringDescription.toString(stateMachine.isNot("A"))); } private Set except(Set s, T e) { Set result = new HashSet(s); result.remove(e); return result; } private final Set anyState = new HashSet() {{ add("A"); add("B"); add("C"); add("D"); }}; } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/VerifyingTestCase.java000066400000000000000000000027511347002534600320510ustar00rootroot00000000000000/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.internal; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; /** * A {@link junit.framework.TestCase} that verifies postconditions after the * test has run and before the fixture has been torn down. * * @since 1.0 */ public abstract class VerifyingTestCase extends TestCase { private List verifiers = new ArrayList(); public VerifyingTestCase() { super(); } public VerifyingTestCase( String name ) { super(name); } /* This is virtually a copy/paste of the same invokedMethod in the TestCase class to allow * overriding of runTest in the normal manner. * * @see junit.framework.TestCase#runBare() */ @Override public void runBare() throws Throwable { Throwable exception= null; setUp(); try { runTest(); verify(); } catch (Throwable running) { exception= running; } finally { try { tearDown(); } catch (Throwable tearingDown) { if (exception == null) exception= tearingDown; } } if (exception != null) throw exception; } public void verify() { for (Runnable verifier : verifiers) { verifier.run(); } } public void addVerifier(Runnable verifier) { verifiers.add(verifier); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/internal/VerifyingTestCaseTests.java000066400000000000000000000052431347002534600330730ustar00rootroot00000000000000/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.internal; import junit.framework.TestCase; public class VerifyingTestCaseTests extends TestCase { public static class ExampleTestCase extends VerifyingTestCase { public ExampleTestCase() { setName("testMethod"); } public void testMethod() { // Success! } } public void testCanBeConstructedWithAName() { String name = "NAME"; VerifyingTestCase testCase = new VerifyingTestCase(name) { }; assertEquals("name", name, testCase.getName()); } private boolean verifierWasRun = false; public void testRunsVerifiersAfterTest() throws Throwable { ExampleTestCase testCase = new ExampleTestCase(); testCase.addVerifier(new Runnable() { public void run() { verifierWasRun = true; } }); testCase.runBare(); assertTrue(verifierWasRun); } public void testOverridingRunTestDoesNotAffectVerification() throws Throwable { ExampleTestCase testCase = new ExampleTestCase() { @Override public void runTest() { } }; testCase.addVerifier(new Runnable() { public void run() { verifierWasRun = true; } }); testCase.runBare(); assertTrue(verifierWasRun); } public void testOverridingSetUpAndTearDownDoesNotAffectVerification() throws Throwable { ExampleTestCase testCase = new ExampleTestCase() { @Override public void setUp() { } @Override public void tearDown() { } }; testCase.addVerifier(new Runnable() { public void run() { verifierWasRun = true; } }); testCase.runBare(); assertTrue(verifierWasRun); } public void testThrowsTestExceptionRatherThanTearDownException() throws Throwable { try { new FailingExampleTestCase("testThrowsExpectedException") {}.runBare(); fail("should have thrown exception"); } catch (Exception actual) { assertSame(FailingExampleTestCase.testException, actual); } } public void testThrowsTearDownExceptionWhenNoTestException() throws Throwable { try { new FailingExampleTestCase("testDoesNotThrowException") {}.runBare(); fail("should have thrown exception"); } catch (Exception actual) { assertSame(FailingExampleTestCase.tearDownException, actual); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/000077500000000000000000000000001347002534600245355ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/AbstractMatcherTest.java000066400000000000000000000060321347002534600313100ustar00rootroot00000000000000/* Copyright (c) 2000-2006 hamcrest.org */ package org.jmock.test.unit.lib; import junit.framework.TestCase; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import org.junit.Assert; /** * Need this source from hamcrest to break the circular dependency with JMock. * * org.hamcrest.JMock1Matchers depends on org.jmock.core.Constraint * org.jmock.test.unit.lib.CurrentStateMatcherTests used to depend on org.hamcrest.AbstractMatcherTest * @author byeo * */ public abstract class AbstractMatcherTest extends TestCase { /** * Create an instance of the Matcher so some generic safety-net tests can be * run on it. */ protected abstract Matcher createMatcher(); public static void assertMatches(Matcher matcher, T arg) { assertMatches("Expected match, but mismatched", matcher, arg); } public static void assertMatches(String message, Matcher matcher, T arg) { if (!matcher.matches(arg)) { Assert.fail(message + " because: '" + mismatchDescription(matcher, arg) + "'"); } } public static void assertDoesNotMatch(Matcher c, T arg) { assertDoesNotMatch("Unexpected match", c, arg); } public static void assertDoesNotMatch(String message, Matcher c, T arg) { Assert.assertFalse(message, c.matches(arg)); } public static void assertDescription(String expected, Matcher matcher) { Description description = new StringDescription(); description.appendDescriptionOf(matcher); Assert.assertEquals("Expected description", expected, description .toString().trim()); } public static void assertMismatchDescription(String expected, Matcher matcher, T arg) { Assert.assertFalse("Precondition: Matcher should not match item.", matcher.matches(arg)); Assert.assertEquals("Expected mismatch description", expected, mismatchDescription(matcher, arg)); } public static void assertNullSafe(Matcher matcher) { try { matcher.matches(null); } catch (Exception e) { Assert.fail("Matcher was not null safe"); } } public static void assertUnknownTypeSafe(Matcher matcher) { try { matcher.matches(new UnknownType()); } catch (Exception e) { Assert.fail("Matcher was not unknown type safe"); } } public static String mismatchDescription(Matcher matcher, T arg) { Description description = new StringDescription(); matcher.describeMismatch(arg, description); return description.toString().trim(); } public void testIsNullSafe() { assertNullSafe(createMatcher()); } public void testCopesWithUnknownTypes() { assertUnknownTypeSafe(createMatcher()); } public static class UnknownType { } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/CamelCaseNamingSchemeTests.java000066400000000000000000000023201347002534600325140ustar00rootroot00000000000000package org.jmock.test.unit.lib; import java.net.URL; import junit.framework.TestCase; import org.jmock.api.MockObjectNamingScheme; import org.jmock.lib.CamelCaseNamingScheme; import org.jmock.test.unit.support.DummyInterface; public class CamelCaseNamingSchemeTests extends TestCase { MockObjectNamingScheme namingScheme = CamelCaseNamingScheme.INSTANCE; public void testNamesMocksByLowerCasingFirstCharacterOfTypeName() { assertEquals("runnable", namingScheme.defaultNameFor(Runnable.class)); assertEquals("dummyInterface", namingScheme.defaultNameFor(DummyInterface.class)); } public interface GPSReceiver {} public interface HTTPClient {}; public interface UDPDatagram {}; public void testReturnsGoodNamesForClassesThatStartWithAcronyms() { assertEquals("gpsReceiver", namingScheme.defaultNameFor(GPSReceiver.class)); assertEquals("httpClient", namingScheme.defaultNameFor(HTTPClient.class)); assertEquals("udpDatagram", namingScheme.defaultNameFor(UDPDatagram.class)); } public void testReturnsGoodNamesForClassesThatAreEntirelyAcronyms() { assertEquals("url", namingScheme.defaultNameFor(URL.class)); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/CurrentStateMatcherTests.java000066400000000000000000000041261347002534600323550ustar00rootroot00000000000000package org.jmock.test.unit.lib; import static org.hamcrest.StringDescription.asString; import static org.jmock.lib.CurrentStateMatcher.isCurrently; import static org.jmock.lib.CurrentStateMatcher.isNotCurrently; import org.hamcrest.Matcher; import org.jmock.States; import org.jmock.internal.StateMachine; public class CurrentStateMatcherTests extends AbstractMatcherTest { States stateMachine = new StateMachine("stateMachine"); Matcher isCurrentlyS = isCurrently("S"); Matcher isNotCurrentlyS = isNotCurrently("S"); public void testMatchesStateMachineCurrentlyInNamedState() { stateMachine.become("S"); assertTrue("should match", isCurrently("S").matches(stateMachine)); assertTrue("should not match", !isNotCurrently("S").matches(stateMachine)); } public void testDoesNotMatchStateMachineCurrentlyInOtherState() { stateMachine.become("T"); assertTrue("should not match", !isCurrently("S").matches(stateMachine)); assertTrue("should match", isNotCurrently("S").matches(stateMachine)); } public void testDoesNotMatchStateMachineInAnonymousInitialState() { assertTrue("should not match", !isCurrently("S").matches(stateMachine)); assertTrue("should match", isNotCurrently("S").matches(stateMachine)); } public void testDoesNotMatchNull() { assertTrue("should not match", !isCurrentlyS.matches(null)); } public void testDoesNotMatchOtherTypesOfObject() { assertTrue("should not match", !isCurrentlyS.matches("something else")); } public void testHasReadableDescription() { assertEquals("a state machine that is S", asString(isCurrently("S"))); assertEquals("a state machine that is not S", asString(isNotCurrently("S"))); } public void testHasReadableDescriptionWhenPassedToAssertThat() { stateMachine.become("X"); assertMismatchDescription("was not S", isCurrently("S"), stateMachine); } @Override protected Matcher createMatcher() { return isCurrentlyS; } } IdentityExpectationErrorTranslatorTests.java000066400000000000000000000007201347002534600354240ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/libpackage org.jmock.test.unit.lib; import junit.framework.TestCase; import org.jmock.api.ExpectationError; import org.jmock.lib.IdentityExpectationErrorTranslator; public class IdentityExpectationErrorTranslatorTests extends TestCase{ public void testReturnsTheErrorAsItsOwnTranslation() { ExpectationError e = ExpectationError.unexpected(null, null); assertSame(e, IdentityExpectationErrorTranslator.INSTANCE.translate(e)); } } JavaReflectionImposteriserTests.java000066400000000000000000000052301347002534600336460ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/libpackage org.jmock.test.unit.lib; import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.Date; import junit.framework.TestCase; import org.jmock.api.Invocation; import org.jmock.api.Invokable; import org.jmock.internal.CaptureControl; import org.jmock.lib.JavaReflectionImposteriser; import org.jmock.lib.action.VoidAction; import org.jmock.test.unit.support.SyntheticEmptyInterfaceClassLoader; public class JavaReflectionImposteriserTests extends TestCase { JavaReflectionImposteriser imposteriser = new JavaReflectionImposteriser(); Invokable mockObject = new Invokable() { public Object invoke(Invocation invocation) throws Throwable { return null; } }; public void testCanOnlyImposteriseInterfaces() { assertTrue("should report that it can imposterise interfaces", imposteriser.canImposterise(Runnable.class)); assertTrue("should report that it cannot imposterise classes", !imposteriser.canImposterise(Date.class)); assertTrue("should report that it cannot imposterise primitive types", !imposteriser.canImposterise(int.class)); assertTrue("should report that it cannot imposterise void", !imposteriser.canImposterise(void.class)); } public void testCanMockTypesFromADynamicClassLoader() throws ClassNotFoundException { ClassLoader interfaceClassLoader = new SyntheticEmptyInterfaceClassLoader(); Class interfaceClass = interfaceClassLoader .loadClass("$UniqueTypeName$"); Object o = imposteriser.imposterise(mockObject, interfaceClass, new Class[0]); assertTrue(interfaceClass.isInstance(o)); } public void testCanSimultaneouslyMockTypesFromMultipleClassLoaders() throws ClassNotFoundException { Class interfaceClass1 = (new SyntheticEmptyInterfaceClassLoader()) .loadClass("$UniqueTypeName1$"); Class interfaceClass2 = CaptureControl.class; Object o = imposteriser.imposterise(mockObject, interfaceClass1, interfaceClass2); assertTrue(interfaceClass1.isInstance(o)); assertTrue(interfaceClass2.isInstance(o)); } public void testCanImposteriseAClassInASignedJarFile() throws Exception { File signedJarFile = new File("../testjar/target/signed.jar"); assertTrue("Signed JAR file does not exist (use Ant to build it)", signedJarFile.exists()); URL jarURL = signedJarFile.toURI().toURL(); // ignore closable loader as we might be in java 6 @SuppressWarnings("resource") URLClassLoader loader = new URLClassLoader(new URL[] { jarURL }); Class typeInSignedJar = loader .loadClass("org.jmock.testjar.TypeInSignedJar"); Object o = imposteriser.imposterise(new VoidAction(), typeInSignedJar); assertTrue(typeInSignedJar.isInstance(o)); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/LastWordNamingSchemeTests.java000066400000000000000000000036201347002534600324420ustar00rootroot00000000000000package org.jmock.test.unit.lib; import java.lang.reflect.InvocationHandler; import java.net.URL; import java.util.Collection; import java.util.ListIterator; import junit.framework.TestCase; import org.jmock.api.MockObjectNamingScheme; import org.jmock.lib.LastWordNamingScheme; public class LastWordNamingSchemeTests extends TestCase { MockObjectNamingScheme namingScheme = LastWordNamingScheme.INSTANCE; public void testNamesMocksByLowercasingTheLastWordOfTheTypeName() { assertEquals("iterator", namingScheme.defaultNameFor(ListIterator.class)); assertEquals("handler", namingScheme.defaultNameFor(InvocationHandler.class)); } public void testLowercasesEntireNameIfItContainsOnlyOneWord() { assertEquals("runnable", namingScheme.defaultNameFor(Runnable.class)); assertEquals("collection", namingScheme.defaultNameFor(Collection.class)); } public interface X {} public void testLowercasesNameContainingSingleUpperCaseLetter() { assertEquals("x", namingScheme.defaultNameFor(X.class)); } public interface y {} public void testLowercasesNameContainingSingleLowerCaseLetter() { assertEquals("y", namingScheme.defaultNameFor(y.class)); } public void testLowercasesEntireNameIfItContainsOnlyCapitals() { assertEquals("url", namingScheme.defaultNameFor(URL.class)); } public interface Party1999 {} public interface NMEA0183 {} // standard for sending GPS data over serial lines public void testAllowsNamesToEndInNumbers() { assertEquals("party1999", namingScheme.defaultNameFor(Party1999.class)); assertEquals("nmea0183", namingScheme.defaultNameFor(NMEA0183.class)); } public interface TelnetURL {} public void testReturnsTrailingAcronymInLowerCase() { assertEquals("url", namingScheme.defaultNameFor(TelnetURL.class)); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/RetroNamingSchemeTests.java000066400000000000000000000011311347002534600317710ustar00rootroot00000000000000package org.jmock.test.unit.lib; import junit.framework.TestCase; import org.jmock.api.MockObjectNamingScheme; import org.jmock.lib.RetroNamingScheme; import org.jmock.test.unit.support.DummyInterface; public class RetroNamingSchemeTests extends TestCase { public void testNamesMocksByLowerCasingFirstCharacterOfTypeName() { MockObjectNamingScheme namingScheme = RetroNamingScheme.INSTANCE; assertEquals("mockRunnable", namingScheme.defaultNameFor(Runnable.class)); assertEquals("mockDummyInterface", namingScheme.defaultNameFor(DummyInterface.class)); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/000077500000000000000000000000001347002534600260125ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/ActionSequenceTests.java000066400000000000000000000075471347002534600326230ustar00rootroot00000000000000/* Copyright (c) 2000-20047 jMock.org */ package org.jmock.test.unit.lib.action; import java.lang.reflect.Method; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Action; import org.jmock.api.ExpectationError; import org.jmock.api.Invocation; import org.jmock.lib.action.ActionSequence; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.MethodFactory; import org.jmock.test.unit.support.MockAction; public class ActionSequenceTests extends TestCase { private Object invokedObject = "INVOKED_OBJECT"; private MethodFactory methodFactory = new MethodFactory(); private Method invokedMethod = methodFactory.newMethodReturning(String.class); private Invocation invocation = new Invocation(invokedObject, invokedMethod); @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not! public void testInvokesActionsInOrder() throws Throwable { final int sequenceLength = 4; MockAction[] actions = new MockAction[sequenceLength]; for (int i = 0; i < sequenceLength; i++) { actions[i] = new MockAction(); actions[i].result = "RESULT-" + i; if (i > 0) actions[i].previous = actions[i-1]; } Invocation[] invocations = new Invocation[actions.length]; for (int i = 0; i < sequenceLength; i++) { invocations[i] = new Invocation(invokedObject, invokedMethod); } ActionSequence sequence = new ActionSequence((Action[])actions); for (int current = 0; current < actions.length; current++) { reset(actions); actions[current].expectInvoke = true; actions[current].expectedInvocation = invocation; Object result = sequence.invoke(invocation); assertSame("should be result of actions[" + current + "]", actions[current].result, result); } } @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not! public void testFailsIfInvokedMoreTimesThanThereAreActionsInTheSequence() throws Throwable { MockAction[] actions = new MockAction[]{new MockAction(), new MockAction()}; ActionSequence sequence = new ActionSequence((Action[])actions); for (int i = 0; i < actions.length; i++) sequence.invoke(invocation); try { sequence.invoke(invocation); fail("should have thrown IllegalStateException"); } catch (ExpectationError ex) { AssertThat.stringIncludes("should describe error", "no more actions", ex.getMessage()); return; } } @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not! public void testDescribesItselfAsSequenceOfActions() throws Throwable { MockAction[] actions = new MockAction[]{new MockAction(), new MockAction()}; ActionSequence sequence = new ActionSequence((Action[])actions); String sequenceDescription = StringDescription.toString(sequence); for (int i = 0; i < actions.length; i++) { AssertThat.stringIncludes("should include action " + i, actions[i].descriptionText, sequenceDescription); if (i > 0) { int h = i - 1; assertTrue("description of action " + h + " should be before that of action " + i, sequenceDescription.indexOf(actions[h].descriptionText) < sequenceDescription.indexOf(actions[i].descriptionText)); } } } private void reset( MockAction[] actions ) { for (int i = 0; i < actions.length; i++) { actions[i].expectInvoke = false; } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/CustomActionTests.java000066400000000000000000000016131347002534600323110ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.lib.action; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Invocation; import org.jmock.lib.action.CustomAction; public class CustomActionTests extends TestCase { static class ConcreteSideEffect extends CustomAction { public ConcreteSideEffect( String description ) { super(description); } public Object invoke( Invocation invocation ) throws Throwable { return null; } } public void testAppendsGivenDescription() { String description = "DESCRIPTION"; CustomAction sideEffect = new ConcreteSideEffect(description); StringDescription buf = new StringDescription(); sideEffect.describeTo(buf); assertEquals("should be description", description, buf.toString()); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/DoAllActionTests.java000066400000000000000000000043041347002534600320320ustar00rootroot00000000000000package org.jmock.test.unit.lib.action; import java.lang.reflect.Method; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.lib.action.DoAllAction; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.MethodFactory; import org.jmock.test.unit.support.MockAction; public class DoAllActionTests extends TestCase { private Object invokedObject = "INVOKED_OBJECT"; private MethodFactory methodFactory = new MethodFactory(); private Method invokedMethod = methodFactory.newMethodReturning(String.class); private Invocation invocation = new Invocation(invokedObject, invokedMethod); private MockAction[] actions = new MockAction[4]; private DoAllAction doAllAction; @Override @SuppressWarnings("cast") // Eclipse gives warning if there is a cast and if there is not! public void setUp() { for (int i = 0; i < actions.length; i++) { actions[i] = new MockAction(); actions[i].descriptionText = "actions["+i+"]"; actions[i].result = actions[i].descriptionText+".result"; actions[i].expectedInvocation = invocation; if (i > 0) actions[i].previous = actions[i-1]; } doAllAction = new DoAllAction((Action[])actions); } public void testPerformsAllActionsInOrder() throws Throwable { doAllAction.invoke(invocation); for (MockAction action : actions) { assertTrue(action.descriptionText + " should have been invoked", action.wasInvoked); } } public void testReturnsResultOfLastAction() throws Throwable { Object expectedResult = actions[actions.length-1].result; Object actualResult = doAllAction.invoke(invocation); assertEquals("result", expectedResult, actualResult); } public void testDescribesAllActionsInDescription() { String description = StringDescription.toString(doAllAction); AssertThat.stringIncludes("description should contain list of actions", "actions[0], actions[1], actions[2], actions[3]", description); } } ReturnEnumerationActionTests.java000066400000000000000000000042741347002534600344540ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/actionpackage org.jmock.test.unit.lib.action; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.lib.action.ReturnEnumerationAction; public class ReturnEnumerationActionTests extends TestCase { private static final Object[] resultElements = {"0", "1", "2", "3"}; public void testReturnsIteratorOverContentsOfCollection() throws Throwable { Collection collection = collectionOf(resultElements); ReturnEnumerationAction action = new ReturnEnumerationAction(collection); assertEnumerationOverSequence(action.invoke(ANY_INVOCATION), resultElements); } public void testReturnsNewIteratorOnEachInvocation() throws Throwable { Collection collection = collectionOf(resultElements); ReturnEnumerationAction action = new ReturnEnumerationAction(collection); assertEnumerationOverSequence(action.invoke(ANY_INVOCATION), resultElements); assertEnumerationOverSequence(action.invoke(ANY_INVOCATION), resultElements); assertEnumerationOverSequence(action.invoke(ANY_INVOCATION), resultElements); } public void testCanReturnIteratorOverArray() throws Throwable { ReturnEnumerationAction action = new ReturnEnumerationAction(resultElements); assertEnumerationOverSequence(action.invoke(ANY_INVOCATION), resultElements); } public void testHasAReadableDescription() { Action action = new ReturnEnumerationAction(resultElements); assertEquals("return enumeration over \"0\", \"1\", \"2\", \"3\"", StringDescription.toString(action)); } private Collection collectionOf(T... values) { return Arrays.asList(values); } private void assertEnumerationOverSequence(Enumeration e, T[] values) { for (int i = 0; i < values.length; i++) { assertEquals("element " + i, values[i], e.nextElement()); } } private static final Invocation ANY_INVOCATION = null; } ReturnIteratorActionTests.java000066400000000000000000000042141347002534600337510ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/actionpackage org.jmock.test.unit.lib.action; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.lib.action.ReturnIteratorAction; public class ReturnIteratorActionTests extends TestCase { private static final Object[] resultElements = {"0", "1", "2", "3"}; public void testReturnsIteratorOverContentsOfCollection() throws Throwable { Collection collection = collectionOf(resultElements); ReturnIteratorAction action = new ReturnIteratorAction(collection); assertIteratorOverSequence(action.invoke(ANY_INVOCATION), resultElements); } public void testReturnsNewIteratorOnEachInvocation() throws Throwable { Collection collection = collectionOf(resultElements); ReturnIteratorAction action = new ReturnIteratorAction(collection); assertIteratorOverSequence(action.invoke(ANY_INVOCATION), resultElements); assertIteratorOverSequence(action.invoke(ANY_INVOCATION), resultElements); assertIteratorOverSequence(action.invoke(ANY_INVOCATION), resultElements); } public void testCanReturnIteratorOverArray() throws Throwable { Action action = new ReturnIteratorAction(resultElements); assertIteratorOverSequence((Iterator)action.invoke(ANY_INVOCATION), resultElements); } public void testHasAReadableDescription() { Action action = new ReturnIteratorAction(resultElements); assertEquals("return iterator over \"0\", \"1\", \"2\", \"3\"", StringDescription.toString(action)); } private Collection collectionOf(T... values) { return Arrays.asList(values); } private void assertIteratorOverSequence(Iterator iterator, T[] values) { for (int i = 0; i < values.length; i++) { assertEquals("element " + i, values[i], iterator.next()); } } private static final Invocation ANY_INVOCATION = null; } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/ReturnValueActionTests.java000066400000000000000000000034101347002534600333100ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.lib.action; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Invocation; import org.jmock.lib.action.ReturnValueAction; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.MethodFactory; public class ReturnValueActionTests extends TestCase { static final String RESULT = "result"; MethodFactory methodFactory; Object invokedObject; Class invokedObjectClass; Invocation invocation; ReturnValueAction returnValueAction; @Override public void setUp() { methodFactory = new MethodFactory(); invokedObject = "INVOKED-OBJECT"; invokedObjectClass = Void.class; returnValueAction = new ReturnValueAction(RESULT); } public void testReturnsValuePassedToConstructor() throws Throwable { invocation = new Invocation(invokedObject, methodFactory.newMethodReturning(RESULT.getClass())); assertSame("Should be the same result object", RESULT, returnValueAction .invoke(invocation)); } public void testIncludesValueInDescription() { String description = StringDescription.toString(returnValueAction); AssertThat.stringIncludes("contains result in description", RESULT.toString(), description); AssertThat.stringIncludes("contains 'returns' in description", "returns", description); } public void testCanReturnNullReference() throws Throwable { invocation = new Invocation(invokedObject, methodFactory.newMethodReturning(String.class)); returnValueAction = new ReturnValueAction(null); assertNull("should return null", returnValueAction.invoke(invocation)); } }jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/ThrowActionTests.java000066400000000000000000000115301347002534600321410ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.lib.action; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Invocation; import org.jmock.lib.action.ThrowAction; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.DummyThrowable; import org.jmock.test.unit.support.MethodFactory; public class ThrowActionTests extends TestCase { static final Throwable THROWABLE = new DummyThrowable(); static final Class[] EXCEPTION_TYPES = {DummyThrowable.class}; MethodFactory methodFactory; Invocation invocation; ThrowAction throwAction; @Override public void setUp() { methodFactory = new MethodFactory(); invocation = new Invocation("INVOKED-OBJECT", methodFactory.newMethod("methodName", MethodFactory.NO_ARGUMENTS, void.class, EXCEPTION_TYPES)); throwAction = new ThrowAction(THROWABLE); } public void testThrowsThrowableObjectPassedToConstructorWhenInvoked() { try { throwAction.invoke(invocation); } catch (Throwable t) { assertSame("Should be the same throwable", THROWABLE, t); } } public void testIncludesDetailsOfThrowableInDescription() { String description = StringDescription.toString(throwAction); assertTrue("contains class of thrown object in description", description.indexOf(THROWABLE.toString()) >= 0); assertTrue("contains 'throws' in description", description.indexOf("throws") >= 0); } public static class ExpectedExceptionType1 extends Exception { private static final long serialVersionUID = 1L; } public static class ExpectedExceptionType2 extends Exception { private static final long serialVersionUID = 1L; } public void testDoesNotAllowThrowingIncompatibleCheckedException() throws Throwable { Class[] expectedExceptionTypes = {ExpectedExceptionType1.class, ExpectedExceptionType2.class}; Invocation incompatibleInvocation = new Invocation("INVOKED-OBJECT", methodFactory.newMethod("methodName", MethodFactory.NO_ARGUMENTS, void.class, expectedExceptionTypes)); try { throwAction.invoke(incompatibleInvocation); } catch (IllegalStateException ex) { String message = ex.getMessage(); for (int i = 0; i < expectedExceptionTypes.length; i++) { AssertThat.stringIncludes("should include name of expected exception types", expectedExceptionTypes[i].getName(), message); } AssertThat.stringIncludes("should include name of thrown exception type", THROWABLE.getClass().getName(), message); return; } fail("should have failed"); } public void testGivesInformativeErrorMessageIfAttemptToThrowCheckedExceptionFromMethodWithNoExceptions() throws Throwable { Invocation incompatibleInvocation = new Invocation("INVOKED-OBJECT", methodFactory.newMethod("methodName", MethodFactory.NO_ARGUMENTS, void.class, MethodFactory.NO_EXCEPTIONS)); try { throwAction.invoke(incompatibleInvocation); } catch (IllegalStateException ex) { String message = ex.getMessage(); AssertThat.stringIncludes("should include name of thrown exception type", THROWABLE.getClass().getName(), message); AssertThat.stringIncludes("should describe that the method doesn't allow any exceptions", "no exceptions", message); return; } fail("should have failed"); } public void testDoesNotCheckTypeCompatiblityOfUncheckedExceptions() throws Throwable { throwAction = new ThrowAction(new RuntimeException()); try { throwAction.invoke(invocation); } catch (RuntimeException ex) { return; } fail("should have thrown a RuntimeException"); } public void testDoesNotCheckTypeCompatiblityOfErrors() throws Throwable { throwAction = new ThrowAction(new Error()); try { throwAction.invoke(invocation); } catch (AssertionFailedError err) { throw err; } catch (Error ex) { return; } fail("should have thrown an Error"); } public void testSetsStackTraceWhenExceptionIsThrown() { try { throwAction.invoke(invocation); } catch (Throwable t) { StackTraceElement[] stackTrace = t.getStackTrace(); assertEquals("thrown from ThrowAction object", throwAction.getClass().getName(), stackTrace[0].getClassName()); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/action/VoidActionTests.java000066400000000000000000000020301347002534600317320ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.lib.action; import junit.framework.TestCase; import org.hamcrest.StringDescription; import org.jmock.api.Invocation; import org.jmock.lib.action.VoidAction; import org.jmock.test.unit.support.AssertThat; import org.jmock.test.unit.support.MethodFactory; public class VoidActionTests extends TestCase { Invocation invocation; VoidAction voidAction; @Override public void setUp() { MethodFactory methodFactory = new MethodFactory(); invocation = new Invocation("INVOKED-OBJECT", methodFactory.newMethodReturning(void.class), new Object[0]); voidAction = new VoidAction(); } public void testReturnsNullWhenInvoked() throws Throwable { assertNull("Should return null", new VoidAction().invoke(invocation)); } public void testIncludesVoidInDescription() { AssertThat.stringIncludes("contains 'void' in description", "void", StringDescription.toString(voidAction)); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrent/000077500000000000000000000000001347002534600267175ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrent/BlitzerTests.java000066400000000000000000000047521347002534600322300ustar00rootroot00000000000000package org.jmock.test.unit.lib.concurrent; import static java.lang.System.getenv; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import org.jmock.lib.concurrent.Blitzer; import org.junit.After; import junit.framework.TestCase; public class BlitzerTests extends TestCase { private static final String BLITZER_THREADS = "blitzerThreads"; private static final String BLITZER_ACTIONS = "blitzerActions"; private static final String BLITZER_TIMEOUT = "blitzerTimeout"; int threadCount = getIntEnvVar(BLITZER_THREADS, "3"); int actionCount = getIntEnvVar(BLITZER_ACTIONS, "12"); int timeout = getIntEnvVar(BLITZER_TIMEOUT, "100"); private int getIntEnvVar(String envVarName, String defaultValue) { return Integer.parseInt(getenv().containsKey(envVarName) ? getenv(envVarName) : defaultValue); } ThreadFactory quietThreadFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { // ignore it } }); return thread; } }; Blitzer blitzer = new Blitzer(actionCount, threadCount, quietThreadFactory); @After public void cleanUp() { blitzer.shutdown(); } public void testRunsTheActionMultipleTimesOnMultipleThreads() throws InterruptedException { final AtomicInteger actualActionCount = new AtomicInteger(); blitzer.blitz(new Runnable() { public void run() { actualActionCount.incrementAndGet(); } }); assertThat(actualActionCount.get(), equalTo(actionCount)); } public void testActionsCanFailWithoutDeadlockingTheTestThread() throws InterruptedException, TimeoutException { blitzer.blitz(timeout, new Runnable() { public void run() { throw new RuntimeException("boom!"); } }); // thread reaches here and does not time out } public void testReportsTheTotalNumberOfActions() { assertThat(blitzer.totalActionCount(), equalTo(actionCount)); } } DeterministicExecutorTests.java000066400000000000000000000046511347002534600350560ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrentpackage org.jmock.test.unit.lib.concurrent; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.api.Action; import org.jmock.lib.concurrent.DeterministicExecutor; import org.jmock.test.unit.internal.MockObjectTestCase; public class DeterministicExecutorTests extends MockObjectTestCase { DeterministicExecutor scheduler = new DeterministicExecutor(); Runnable commandA = mock(Runnable.class, "commandA"); Runnable commandB = mock(Runnable.class, "commandB"); Runnable commandC = mock(Runnable.class, "commandC"); Runnable commandD = mock(Runnable.class, "commandD"); public void testRunsPendingCommands() { scheduler.execute(commandA); scheduler.execute(commandB); final Sequence executionOrder = sequence("executionOrder"); checking(new Expectations() {{ oneOf (commandA).run(); inSequence(executionOrder); oneOf (commandB).run(); inSequence(executionOrder); }}); scheduler.runPendingCommands(); } public void testCanLeaveCommandsSpawnedByExecutedCommandsPendingForLaterExecution() { scheduler.execute(commandA); scheduler.execute(commandB); final Sequence executionOrder = sequence("executionOrder"); checking(new Expectations() {{ oneOf (commandA).run(); inSequence(executionOrder); will(schedule(commandC)); oneOf (commandB).run(); inSequence(executionOrder); will(schedule(commandD)); never (commandC).run(); never (commandD).run(); }}); scheduler.runPendingCommands(); } public void testCanRunCommandsSpawnedByExecutedCommandsUntilNoCommandsArePending() { scheduler.execute(commandA); scheduler.execute(commandB); final Sequence executionOrder = sequence("executionOrder"); checking(new Expectations() {{ oneOf (commandA).run(); inSequence(executionOrder); will(schedule(commandC)); oneOf (commandB).run(); inSequence(executionOrder); will(schedule(commandD)); oneOf (commandC).run(); inSequence(executionOrder); oneOf (commandD).run(); inSequence(executionOrder); }}); scheduler.runUntilIdle(); } protected Action schedule(final Runnable command) { return ScheduleOnExecutorAction.schedule(scheduler, command); } } DeterministicSchedulerTests.java000066400000000000000000000264001347002534600351720ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrentpackage org.jmock.test.unit.lib.concurrent; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.jmock.Expectations; import org.jmock.Sequence; import org.jmock.api.Action; import org.jmock.lib.concurrent.DeterministicScheduler; import org.jmock.lib.concurrent.UnsupportedSynchronousOperationException; import org.jmock.test.unit.internal.MockObjectTestCase; public class DeterministicSchedulerTests extends MockObjectTestCase { DeterministicScheduler scheduler = new DeterministicScheduler(); Runnable commandA = mock(Runnable.class, "commandA"); Runnable commandB = mock(Runnable.class, "commandB"); Runnable commandC = mock(Runnable.class, "commandC"); Runnable commandD = mock(Runnable.class, "commandD"); @SuppressWarnings("unchecked") Callable callableA = mock(Callable.class, "callableA"); public void testRunsPendingCommandsUntilIdle() { scheduler.execute(commandA); scheduler.execute(commandB); final Sequence executionOrder = sequence("executionOrder"); checking(new Expectations() {{ oneOf (commandA).run(); inSequence(executionOrder); oneOf (commandB).run(); inSequence(executionOrder); }}); assertFalse(scheduler.isIdle()); scheduler.runUntilIdle(); assertTrue(scheduler.isIdle()); } public void testCanRunCommandsSpawnedByExecutedCommandsUntilIdle() { scheduler.execute(commandA); scheduler.execute(commandB); final Sequence executionOrder = sequence("executionOrder"); checking(new Expectations() {{ oneOf (commandA).run(); inSequence(executionOrder); will(schedule(commandC)); oneOf (commandB).run(); inSequence(executionOrder); will(schedule(commandD)); oneOf (commandC).run(); inSequence(executionOrder); oneOf (commandD).run(); inSequence(executionOrder); }}); scheduler.runUntilIdle(); } public void testCanScheduleCommandAndReturnFuture() throws InterruptedException, ExecutionException { Future future = scheduler.submit(commandA); checking(new Expectations() {{ oneOf (commandA).run(); }}); assertTrue("future should not be done before running the task", !future.isDone()); scheduler.runUntilIdle(); assertTrue("future should be done after running the task", future.isDone()); assertNull("result of future should be null", future.get()); } public void testCanScheduleCommandAndResultAndReturnFuture() throws InterruptedException, ExecutionException { Future future = scheduler.submit(commandA, "result1"); checking(new Expectations() {{ oneOf (commandA).run(); }}); scheduler.runUntilIdle(); assertThat(future.get(), equalTo("result1")); } public void testCanScheduleCallableAndReturnFuture() throws Exception { Future future = scheduler.submit(callableA); checking(new Expectations() {{ oneOf (callableA).call(); will(returnValue("result2")); }}); scheduler.runUntilIdle(); assertThat(future.get(), equalTo("result2")); } public void testScheduledCallablesCanReturnNull() throws Exception { checking(new Expectations() {{ oneOf (callableA).call(); will(returnValue(null)); }}); Future future = scheduler.submit(callableA); scheduler.runUntilIdle(); assertNull(future.get()); } public void testSimpleGetDelay() throws Exception { ScheduledFuture task1 = scheduler.schedule(commandA, 10, TimeUnit.SECONDS); scheduler.tick(1, TimeUnit.SECONDS); assertEquals(9, task1.getDelay(TimeUnit.SECONDS)); } public void testGetDelayWithManyScheduledTasks() throws Exception { ScheduledFuture task1 = scheduler.schedule(commandA, 10, TimeUnit.SECONDS); ScheduledFuture task2 = scheduler.schedule(commandA, 20, TimeUnit.SECONDS); ScheduledFuture task3 = scheduler.schedule(commandA, 15, TimeUnit.SECONDS); scheduler.tick(5, TimeUnit.SECONDS); assertEquals(5, task1.getDelay(TimeUnit.SECONDS)); assertEquals(15, task2.getDelay(TimeUnit.SECONDS)); assertEquals(10, task3.getDelay(TimeUnit.SECONDS)); } public void testGetDelayOnPassedTasks() throws Exception { final Throwable thrown = new IllegalStateException(); ScheduledFuture task1 = scheduler.schedule(commandA, 1, TimeUnit.MILLISECONDS); checking(new Expectations() {{ oneOf (commandA).run(); will(throwException(thrown)); }}); scheduler.tick(2, TimeUnit.MILLISECONDS); assertEquals(-1, task1.getDelay(TimeUnit.MILLISECONDS)); } public class ExampleException extends Exception {} public void testExceptionThrownByScheduledCallablesIsThrownFromFuture() throws Exception { final Throwable thrown = new ExampleException(); checking(new Expectations() {{ oneOf (callableA).call(); will(throwException(thrown)); }}); Future future = scheduler.submit(callableA); scheduler.runUntilIdle(); try { future.get(); fail("should have thrown ExecutionException"); } catch (ExecutionException expected) { assertThat(expected.getCause(), sameInstance(thrown)); } } public void testCanScheduleCommandsToBeExecutedAfterADelay() { scheduler.schedule(commandA, 10, TimeUnit.SECONDS); scheduler.tick(9, TimeUnit.SECONDS); checking(new Expectations() {{ oneOf (commandA).run(); }}); scheduler.tick(1, TimeUnit.SECONDS); } public void testTickingTimeForwardRunsAllCommandsScheduledDuringThatTimePeriod() { scheduler.schedule(commandA, 1, TimeUnit.MILLISECONDS); scheduler.schedule(commandB, 2, TimeUnit.MILLISECONDS); checking(new Expectations() {{ oneOf (commandA).run(); oneOf (commandB).run(); }}); scheduler.tick(3, TimeUnit.MILLISECONDS); } public void testTickingTimeForwardRunsCommandsExecutedByScheduledCommands() { scheduler.schedule(commandA, 1, TimeUnit.MILLISECONDS); scheduler.schedule(commandD, 2, TimeUnit.MILLISECONDS); checking(new Expectations() {{ oneOf (commandA).run(); will(schedule(commandB)); oneOf (commandB).run(); will(schedule(commandC)); oneOf (commandC).run(); oneOf (commandD).run(); }}); scheduler.tick(3, TimeUnit.MILLISECONDS); } public void testCanExecuteCommandsThatRepeatWithFixedDelay() { scheduler.scheduleWithFixedDelay(commandA, 2L, 3L, TimeUnit.SECONDS); checking(new Expectations() {{ exactly(3).of(commandA).run(); }}); scheduler.tick(8L, TimeUnit.SECONDS); } public void testCanExecuteCommandsThatRepeatAtFixedRateButAssumesThatCommandsTakeNoTimeToExecute() { scheduler.scheduleAtFixedRate(commandA, 2L, 3L, TimeUnit.SECONDS); checking(new Expectations() {{ exactly(3).of(commandA).run(); }}); scheduler.tick(8L, TimeUnit.SECONDS); } public void testCanCancelScheduledCommands() { final boolean dontCare = true; ScheduledFuture future = scheduler.schedule(commandA, 1, TimeUnit.SECONDS); assertFalse(future.isCancelled()); future.cancel(dontCare); assertTrue(future.isCancelled()); checking(new Expectations() {{ never (commandA); }}); scheduler.tick(2, TimeUnit.SECONDS); } public void testCancellingARunningCommandStopsItFromRunningAgain() { DeterministicScheduler deterministicScheduler = new DeterministicScheduler(); ObjectThatCancelsARepeatingTask objectThatCancelsARepeatingTask = new ObjectThatCancelsARepeatingTask(deterministicScheduler); objectThatCancelsARepeatingTask.scheduleATaskThatWillCancelItself(1, TimeUnit.SECONDS); deterministicScheduler.tick(2,TimeUnit.SECONDS); assertThat("cancelling runnable run count", objectThatCancelsARepeatingTask.runCount(), is(1)); } public static class ObjectThatCancelsARepeatingTask { private final ScheduledExecutorService scheduler; private ScheduledFuture scheduledFuture; private final AtomicInteger counter = new AtomicInteger(); public ObjectThatCancelsARepeatingTask(ScheduledExecutorService scheduler) { this.scheduler = scheduler; } public void scheduleATaskThatWillCancelItself(int interval, TimeUnit unit){ scheduledFuture = scheduler.scheduleAtFixedRate( new CancellingRunnable(), interval,interval,unit); } public int runCount(){ return counter.get(); } private class CancellingRunnable implements Runnable{ @Override public void run() { scheduledFuture.cancel(true); counter.incrementAndGet(); } } } static final int TIMEOUT_IGNORED = 1000; public void testCanScheduleCallablesAndGetTheirResultAfterTheyHaveBeenExecuted() throws Exception { checking(new Expectations() {{ oneOf (callableA).call(); will(returnValue("A")); }}); ScheduledFuture future = scheduler.schedule(callableA, 1, TimeUnit.SECONDS); assertTrue("is not done", !future.isDone()); scheduler.tick(1, TimeUnit.SECONDS); assertTrue("is done", future.isDone()); assertThat(future.get(), equalTo("A")); assertThat(future.get(TIMEOUT_IGNORED, TimeUnit.SECONDS), equalTo("A")); } public void testCannotBlockWaitingForFutureResultOfScheduledCallable() throws Exception { ScheduledFuture future = scheduler.schedule(callableA, 1, TimeUnit.SECONDS); try { future.get(); fail("should have thrown UnsupportedSynchronousOperationException"); } catch (UnsupportedSynchronousOperationException expected) {} try { future.get(TIMEOUT_IGNORED, TimeUnit.SECONDS); fail("should have thrown UnsupportedSynchronousOperationException"); } catch (UnsupportedSynchronousOperationException expected) {} } private Action schedule(final Runnable command) { return ScheduleOnExecutorAction.schedule(scheduler, command); } } ScheduleOnExecutorAction.java000066400000000000000000000017361347002534600344200ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrentpackage org.jmock.test.unit.lib.concurrent; import java.util.concurrent.Executor; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; public class ScheduleOnExecutorAction implements Action { private final Executor executor; private final Runnable command; public ScheduleOnExecutorAction(Executor executor, Runnable command) { this.command = command; this.executor = executor; } public Object invoke(Invocation invocation) throws Throwable { executor.execute(command); return null; } public void describeTo(Description description) { description.appendText("execute ") .appendValue(command) .appendText(" on ") .appendValue(executor); } public static Action schedule(final Executor executor, final Runnable command) { return new ScheduleOnExecutorAction(executor, command); } }jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrent/internal/000077500000000000000000000000001347002534600305335ustar00rootroot00000000000000DeltaQueueTests.java000066400000000000000000000127221347002534600344040ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/concurrent/internalpackage org.jmock.test.unit.lib.concurrent.internal; import org.jmock.lib.concurrent.internal.DeltaQueue; import junit.framework.TestCase; public class DeltaQueueTests extends TestCase { DeltaQueue deltaQueue = new DeltaQueue(); String elementA = "a"; String elementB = "b"; String elementC = "c"; public void testIsCreatedEmpty() { assertTrue("is empty", deltaQueue.isEmpty()); } public void testCanScheduleAnElement() { final long delay = 10L; deltaQueue.add(delay, elementA); assertTrue("is not empty", !deltaQueue.isEmpty()); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", delay, deltaQueue.delay()); } public void testTicksDownTimeUntilScheduledElement() { deltaQueue.add(10L, elementA); assertEquals(0L, deltaQueue.tick(1L)); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", 9L, deltaQueue.delay()); assertEquals(0L, deltaQueue.tick(4L)); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", 5L, deltaQueue.delay()); assertEquals(0L, deltaQueue.tick(4L)); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", 1L, deltaQueue.delay()); assertEquals(0L, deltaQueue.tick(1L)); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", 0L, deltaQueue.delay()); } public void testReturnsTimeAfterElementIfTickGreaterThanDelay() { deltaQueue.add(10L, elementA); assertEquals(5L, deltaQueue.tick(15L)); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", 0L, deltaQueue.delay()); } public void testCanPopElementWhenDelayIsZero() { deltaQueue.add(10L, elementA); deltaQueue.tick(10L); assertSame("popped", elementA, deltaQueue.pop()); assertTrue("is empty", deltaQueue.isEmpty()); } public void testCanScheduleMultipleElementsInAnyOrder() { deltaQueue.add(10L, elementB); deltaQueue.add(5L, elementA); deltaQueue.add(12L, elementC); assertSame("next", elementA, deltaQueue.next()); assertEquals("delay", 5L, deltaQueue.delay()); deltaQueue.tick(5L); assertSame("popped A", elementA, deltaQueue.pop()); assertSame("next", elementB, deltaQueue.next()); assertEquals("delay", 5L, deltaQueue.delay()); deltaQueue.tick(5L); assertSame("popped B", elementB, deltaQueue.pop()); assertSame("next", elementC, deltaQueue.next()); assertEquals("delay", 2L, deltaQueue.delay()); deltaQueue.tick(2L); assertSame("popped C", elementC, deltaQueue.pop()); assertTrue("is empty", deltaQueue.isEmpty()); } public void testReportsScheduleAsString() { deltaQueue.add(10L, elementB); deltaQueue.add(5L, elementA); deltaQueue.add(12L, elementC); assertEquals("DeltaQueue[+5: a, +5: b, +2: c]", deltaQueue.toString()); } public void testTickingDownAnEmptyDeltaQueueDoesNothingButConsumesAllOfTheTickedTime() { assertEquals(0L, deltaQueue.tick(1L)); assertEquals(0L, deltaQueue.tick(2L)); assertEquals(0L, deltaQueue.tick(19L)); } public void testElementsScheduledWithSameDelayAreExecutedInTheOrderThatTheyWereScheduled() { deltaQueue.add(1L, elementA); deltaQueue.add(1L, elementB); deltaQueue.add(1L, elementC); deltaQueue.tick(1L); assertSame(elementA, deltaQueue.pop()); assertSame(elementB, deltaQueue.pop()); assertSame(elementC, deltaQueue.pop()); } public void testCanRemoveScheduledElements() { deltaQueue.add(1L, elementA); deltaQueue.add(2L, elementB); deltaQueue.add(3L, elementC); assertTrue(deltaQueue.remove(elementB)); deltaQueue.tick(1L); assertSame(elementA, deltaQueue.pop()); deltaQueue.tick(2L); assertSame(elementC, deltaQueue.pop()); } public void testCanRemoveHead() { deltaQueue.add(1L, elementA); deltaQueue.add(2L, elementB); deltaQueue.add(3L, elementC); deltaQueue.remove(elementA); deltaQueue.tick(2L); assertSame(elementB, deltaQueue.pop()); deltaQueue.tick(1L); assertSame(elementC, deltaQueue.pop()); } public void testCanRemoveTail() { deltaQueue.add(1L, elementA); deltaQueue.add(2L, elementB); deltaQueue.add(3L, elementC); deltaQueue.remove(elementC); deltaQueue.tick(1L); assertSame(elementA, deltaQueue.pop()); deltaQueue.tick(1L); assertSame(elementB, deltaQueue.pop()); assertTrue("is empty", deltaQueue.isEmpty()); } public void testReturnsFalseIfElementAlreadyRemoved() { deltaQueue.add(1L, elementA); deltaQueue.add(2L, elementB); assertFalse(deltaQueue.remove(elementC)); } public void testDelayIsMinusOneWhenElementIsAlreadyRemoved() { deltaQueue.add(1L, elementA); deltaQueue.remove(elementA); assertEquals("delay", -1, deltaQueue.delay(elementA)); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/script/000077500000000000000000000000001347002534600260415ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/lib/script/ScriptedActionTests.java000066400000000000000000000061531347002534600326470ustar00rootroot00000000000000package org.jmock.test.unit.lib.script; import static org.hamcrest.Matchers.sameInstance; import static org.jmock.lib.script.ScriptedAction.perform; import junit.framework.TestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Assert; public class ScriptedActionTests extends TestCase { public interface Callout { void doSomethingWith(Callback cb) throws Exception; void doSomethingWithBoth(Callback cb1, Callback cb2); } public interface Callback { void callback(); void throwException() throws Exception; void callbackWith(Object o); void callbackWith(Object o1, Object o2); } Mockery context = new Mockery(); Callout callout = context.mock(Callout.class); Callback callback = context.mock(Callback.class); Callback callback2 = context.mock(Callback.class, "callback2"); public void testInterpretsCallbackExpression() throws Exception { context.checking(new Expectations() {{ oneOf (callout).doSomethingWith(callback); will(perform("$0.callback()")); oneOf (callback).callback(); }}); callout.doSomethingWith(callback); context.assertIsSatisfied(); } public void testScriptCanReferToParametersByIndex() { context.checking(new Expectations() {{ oneOf (callout).doSomethingWithBoth(callback, callback2); will(perform("$1.callback()")); oneOf (callback2).callback(); }}); callout.doSomethingWithBoth(callback, callback2); context.assertIsSatisfied(); } public void testScriptCanReferToInvokedObjectAs$This() throws Exception { context.checking(new Expectations() {{ oneOf (callout).doSomethingWith(callback); will(perform("$0.callbackWith($this)")); oneOf (callback).callbackWith(callout); }}); callout.doSomethingWith(callback); context.assertIsSatisfied(); } public void testCanBindValuesFromTestIntoScript() throws Exception { final Object v1 = new Object(); final Object v2 = new Object(); context.checking(new Expectations() {{ oneOf (callout).doSomethingWith(callback); will(perform("$0.callbackWith(x, y)").where("x", v1).where("y", v2)); oneOf (callback).callbackWith(v1, v2); }}); callout.doSomethingWith(callback); context.assertIsSatisfied(); } public void testExceptionThrownByCallbackIsPassedBackToCaller() throws Exception { final Exception exception = new Exception("exception"); context.checking(new Expectations() {{ oneOf (callout).doSomethingWith(callback); will(perform("$0.throwException()")); oneOf (callback).throwException(); will(throwException(exception)); }}); try { callout.doSomethingWith(callback); } catch (Exception e) { Assert.assertThat(e, sameInstance(exception)); } context.assertIsSatisfied(); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/000077500000000000000000000000001347002534600255035ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/AssertThat.java000066400000000000000000000051741347002534600304370ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.support; import junit.framework.AssertionFailedError; import org.junit.Assert; public class AssertThat extends Assert { public static void arraysAreEqual( 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 stringExcludes( String description, String excludeString, String targetString ) { assertTrue(description + "\nExclude String: " + excludeString + "\n Target String: " + targetString, targetString.indexOf(excludeString) == -1); } public static void stringIncludes( String description, String includeString, String targetString ) { assertTrue(description + "\nInclude String: " + includeString + "\n Target String: " + targetString, targetString.indexOf(includeString) != -1); } public static void stringStartsWith( String description, String startString, String targetString ) { assertTrue(description + "\n Start String: " + startString + "\nTarget String: " + targetString, targetString.startsWith(startString)); } // 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 fails( String message, Runnable runnable ) { try { runnable.run(); } catch (AssertionFailedError expected) { return; } fail(message); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/DummyInterface.java000066400000000000000000000016531347002534600312670ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.support; public interface DummyInterface { void noArgVoidMethod() throws Throwable; String noArgMethod(); String oneArgMethod( String arg1 ); String twoArgMethod( String arg1, String arg2 ) throws Throwable; final String METHOD_NOARGVOID_NAME = "noArgVoidMethod"; final Object[] METHOD_NOARGVOID_ARGS = new Object[0]; final String METHOD_NOARG_NAME = "noArgMethod"; final Object[] METHOD_NOARG_ARGS = new Object[0]; final String METHOD_NOARG_RESULT = "resultNoArgs"; final String METHOD_ONEARG_NAME = "oneArgMethod"; final String[] METHOD_ONEARG_ARGS = new String[]{"oneP1"}; final String METHOD_ONEARG_RESULT = "result1Args"; final String METHOD_TWOARG_NAME = "twoArgMethod"; final String[] METHOD_TWOARG_ARGS = new String[]{"twoP1", "twoP2"}; final String METHOD_TWOARG_RESULT = "resultTwoArgs"; } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/DummyThrowable.java000066400000000000000000000004731347002534600313150ustar00rootroot00000000000000/* Copyright (c) 2000-2004 jMock.org */ package org.jmock.test.unit.support; public class DummyThrowable extends Throwable { private static final long serialVersionUID = 1L; public DummyThrowable() { super(); } public DummyThrowable( String message ) { super(message); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/MethodFactory.java000066400000000000000000000050301347002534600311140ustar00rootroot00000000000000/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.support; import java.lang.reflect.Method; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class MethodFactory extends ClassLoader { public static final int CLASS_FORMAT_VERSION = 49; public static Class[] NO_ARGUMENTS = {}; public static Class[] NO_EXCEPTIONS = {}; public Method newMethodReturning(Class returnType) { return newMethod("ignoredMethodName", NO_ARGUMENTS, returnType, NO_EXCEPTIONS); } public Method newMethod(String name) { return newMethod(name, NO_ARGUMENTS, void.class, NO_EXCEPTIONS); } public Method newMethod(final String methodName, final Class[] argTypes, final Class returnType, final Class[] exceptionTypes) { ClassLoader classLoader = new ClassLoader() { @Override protected Class findClass(String interfaceName) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); writer.visit(CLASS_FORMAT_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_INTERFACE, nameToClassFormat(interfaceName), null, "java/lang/Object", null /* interfaces */); writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, methodName, methodDescriptor(returnType, argTypes), null, classNamesInClassFormat(exceptionTypes)); byte[] classAsBytes = writer.toByteArray(); return defineClass(interfaceName, classAsBytes, 0, classAsBytes.length); } }; try { Class interfaceClass = classLoader .loadClass("InterfaceDefining_" + methodName); return interfaceClass.getMethod(methodName, argTypes); } catch (ClassNotFoundException ex) { throw new Error(ex.getMessage()); } catch (NoSuchMethodException ex) { throw new Error(ex.getMessage()); } } static String nameToClassFormat(String name) { return name.replace('.', '/'); } static String[] classNamesInClassFormat(Class[] classes) { String[] namesInClassFormat = new String[classes.length]; for (int i = 0; i < classes.length; i++) { namesInClassFormat[i] = nameToClassFormat(classes[i].getName()); } return namesInClassFormat; } static String methodDescriptor(Class returnClass, Class[] argClasses) { return Type.getMethodDescriptor(Type.getType(returnClass), classesToTypes(argClasses)); } private static Type[] classesToTypes(Class[] classes) { Type[] types = new Type[classes.length]; for (int i = 0; i < classes.length; i++) { types[i] = Type.getType(classes[i]); } return types; } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/MethodFactoryTests.java000066400000000000000000000033511347002534600321430ustar00rootroot00000000000000/* Copyright (c) 2000-2006 jMock.org */ package org.jmock.test.unit.support; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import junit.framework.TestCase; public class MethodFactoryTests extends TestCase { private class ReturnType { } static final String METHOD_NAME = "METHOD_NAME"; static final Class[] ARG_TYPES = new Class[]{int.class, Object.class, double[].class, String[].class}; static final Class RETURN_TYPE = ReturnType.class; static final Class[] EXCEPTION_TYPES = new Class[]{InterruptedException.class}; MethodFactory factory; @Override public void setUp() { factory = new MethodFactory(); } public void testCreatesMethodInNewNamedClass() { Method method = factory.newMethod(METHOD_NAME, ARG_TYPES, RETURN_TYPE, EXCEPTION_TYPES); assertTrue("is public", Modifier.isPublic(method.getModifiers())); assertEquals("invokedMethod name", METHOD_NAME, method.getName()); assertAllSame("arg types", ARG_TYPES, method.getParameterTypes()); assertSame("return type", RETURN_TYPE, method.getReturnType()); assertAllSame("exception types", EXCEPTION_TYPES, method.getExceptionTypes()); } public void testCreatesMethodThatReturnsAType() { Method method = factory.newMethodReturning(RETURN_TYPE); assertSame("return type", RETURN_TYPE, method.getReturnType()); } private void assertAllSame( String message, Class[] expected, Class[] actual ) { assertEquals(message + ": number of elements ", expected.length, actual.length); for (int i = 0; i < expected.length; i++) { assertSame(message + ": element " + i, expected[i], actual[i]); } } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/MockAction.java000066400000000000000000000020701347002534600303740ustar00rootroot00000000000000package org.jmock.test.unit.support; import org.hamcrest.Description; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.junit.Assert; public class MockAction extends Assert implements Action { public boolean expectInvoke = true; public Invocation expectedInvocation = null; public Object result = null; public Throwable exception = null; public MockAction previous = null; public boolean wasInvoked = false; public String descriptionText; public MockAction() { descriptionText = this.toString(); } public Object invoke(Invocation actualInvocation) throws Throwable { assertTrue("should not be invoked", expectInvoke); if (expectedInvocation != null) { assertEquals("invocation", expectedInvocation, actualInvocation); } if (previous != null) { assertTrue("invoked out of order", previous.wasInvoked); } wasInvoked = true; if (exception != null) { throw exception; } else { return result; } } public void describeTo(Description description) { description.appendText(descriptionText); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/MockExpectation.java000066400000000000000000000036351347002534600314520ustar00rootroot00000000000000package org.jmock.test.unit.support; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.hamcrest.Description; import org.jmock.api.Expectation; import org.jmock.api.Invocation; public class MockExpectation implements Expectation { public boolean matches; public boolean hasBeenInvoked; public boolean isSatisfied; public boolean allowsMoreInvocations; public MockExpectation(boolean matches, boolean isSatisfied, boolean allowsMoreInvocations) { this.matches = matches; this.isSatisfied = isSatisfied; this.allowsMoreInvocations = allowsMoreInvocations; } public boolean matches(Invocation invocation) { return matches; } public boolean allowsMoreInvocations() { return allowsMoreInvocations; } public boolean isSatisfied() { return isSatisfied; } private boolean shouldBeInvoked = true; private Invocation expectedInvocation = null; public Object invokeResult = null; public boolean wasInvoked = false; public void shouldNotBeInvoked() { shouldBeInvoked = false; } public void shouldBeInvokedWith(Invocation invocation) { shouldBeInvoked = true; expectedInvocation = invocation; } public Object invoke(Invocation invocation) throws Throwable { assertTrue("should not have been invoked; invocation: " + invocation, shouldBeInvoked); if (expectedInvocation != null) { assertSame("unexpected invocation", expectedInvocation, invocation); } wasInvoked = true; return invokeResult; } public void describeTo(Description description) { throw new UnsupportedOperationException("not implemented"); } public void describeMismatch(Invocation invocation, Description description) { throw new UnsupportedOperationException("not implemented"); } } jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/StubInvokable.java000066400000000000000000000007201347002534600311150ustar00rootroot00000000000000/** * */ package org.jmock.test.unit.support; import org.jmock.api.Invocation; import org.jmock.api.Invokable; public class StubInvokable implements Invokable { public boolean wasInvoked = false; public Object invoke(Invocation invocation) throws Throwable { wasInvoked = true; return null; } public String toStringResult; @Override public String toString() { return toStringResult; } } SyntheticEmptyInterfaceClassLoader.java000066400000000000000000000024711347002534600352220ustar00rootroot00000000000000jmock-library-2.12.0/jmock/src/test/java/org/jmock/test/unit/support/** * */ package org.jmock.test.unit.support; import static org.jmock.test.unit.support.MethodFactory.CLASS_FORMAT_VERSION; import java.util.regex.Pattern; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; public class SyntheticEmptyInterfaceClassLoader extends ClassLoader { private Pattern namePattern; public SyntheticEmptyInterfaceClassLoader() { this(".*"); } public SyntheticEmptyInterfaceClassLoader(String namePatternRegex) { namePattern = Pattern.compile(namePatternRegex); } @Override protected Class findClass(String name) throws ClassNotFoundException { if (namePattern.matcher(name).matches()) { return synthesiseInterface(name); } else { throw new ClassNotFoundException(name); } } private Class synthesiseInterface(String name) throws ClassFormatError { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); writer.visit(CLASS_FORMAT_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_INTERFACE, MethodFactory.nameToClassFormat(name), null, "java/lang/Object", null /* interfaces */); byte[] b = writer.toByteArray(); return defineClass(name, b, 0, b.length); } } jmock-library-2.12.0/pom.xml000066400000000000000000000363231347002534600156710ustar00rootroot00000000000000 4.0.0 org.jmock jmock-parent 2.12.0 pom jMock 2 Parent org.sonatype.oss oss-parent 7 2003 jMock http://jmock.org BSD style http://jmock.org/license.html repo scm:git:https://github.com/jmock-developers/jmock-library.git scm:git:git@github.com:jmock-developers/jmock-library.git https://github.com/jmock-developers/jmock-library.git UTF-8 UTF-8 1.8 1.8 true 2.1 4.12 7.1 3.0.1 2.0b6 5.4.2 1.9.12 testjar jmock jmock-junit3 jmock-junit4 jmock-junit5 jmock-imposters jmock-legacy jmock-example jmock-imposters-tests org.apache.maven.plugins maven-enforcer-plugin 3.0.0-M2 enforce-maven enforce 3.0.5 org.apache.maven.plugins maven-javadoc-plugin check-javadoc package javadoc org.sonatype.plugins nexus-staging-maven-plugin 1.6.8 true ossrh https://oss.sonatype.org/ true org.apache.maven.plugins maven-surefire-plugin 2.22.2 /**/*.java **/Failing*TestCase.java **/VerifyingTestCaseTests$* **/testdata/jmock/acceptance/**/*.java org.apache.maven.plugins maven-failsafe-plugin 2.22.2 true **/Failing*TestCase.java **/testdata/jmock/acceptance/**/*.java org.apache.maven.plugins maven-jarsigner-plugin 1.4 org.apache.maven.plugins maven-gpg-plugin 1.6 org.apache.maven.plugins maven-source-plugin 3.0.1 org.apache.maven.plugins maven-javadoc-plugin 3.0.1 org.codehaus.mojo versions-maven-plugin 2.7 compile display-dependency-updates display-plugin-updates org.eclipse.m2e lifecycle-mapping 1.0.0 org.codehaus.mojo exec-maven-plugin [1.4.0,) java exec org.hamcrest hamcrest ${hamcrest.version} org.hamcrest hamcrest-library ${hamcrest.version} junit junit ${junit.version} test org.junit.jupiter junit-jupiter-api ${junit.jupiter.version} test org.junit.jupiter junit-jupiter-params ${junit.jupiter.version} test org.junit.jupiter junit-jupiter-engine ${junit.jupiter.version} test org.junit.platform junit-platform-launcher 1.4.0 org.apache-extras.beanshell bsh ${bsh.version} org.objenesis objenesis ${objenesis.version} compile net.bytebuddy byte-buddy ${bytebuddy.version} org.ow2.asm asm ${asm.version} com.thoughtworks.qdox qdox 2.0-M10 test ossrh https://oss.sonatype.org/content/repositories/snapshots ossrh https://oss.sonatype.org/service/local/staging/deploy/maven2/ release org.apache.maven.plugins maven-gpg-plugin true ${gpg.keyname} sign-artifacts verify sign org.apache.maven.plugins maven-source-plugin attach-sources jar-no-fork org.apache.maven.plugins maven-javadoc-plugin attach-javadocs jar jmock-library-2.12.0/settings.xml000066400000000000000000000010061347002534600167240ustar00rootroot00000000000000 ossrh ${env.SONATYPE_USERNAME} ${env.SONATYPE_PASSWORD} jmock-library-2.12.0/testjar/000077500000000000000000000000001347002534600160215ustar00rootroot00000000000000jmock-library-2.12.0/testjar/.gitignore000066400000000000000000000001101347002534600200010ustar00rootroot00000000000000/target/ random_seed trustdb.gpg *~ .gpg-v21-migrated private-keys-v1.d jmock-library-2.12.0/testjar/pom.xml000066400000000000000000000060451347002534600173430ustar00rootroot00000000000000 4.0.0 jmock-testjar jar jMock 2 Test Jar Source for jar files used in jmock core tests org.jmock jmock-parent 2.12.0 ../pom.xml signed org.apache.maven.plugins maven-dependency-plugin copy package copy ${project.groupId} ${project.artifactId} ${project.version} jar true ${project.build.directory} unsigned.jar org.apache.maven.plugins maven-gpg-plugin sign-artifacts verify sign 899FD4CB ${basedir} secret false com.google.code.findbugs annotations 3.0.1 jmock-library-2.12.0/testjar/pubring.gpg000066400000000000000000000023561347002534600201740ustar00rootroot00000000000000 ThsЪu/.,8qFTC&g SBSƾwz$EEO@,wB[mg=0 J+\Qcg9n\Ӆ\7|o6`w`\ߡ=ݷuGjpRbȭ#,%Na%dخlu/B ( bGĤ PW[n禀Joo;j >^An$LUY9ܤ3gNot Oli Bye (Insecure keypair for JMock testjar signatures) 8"Th   p $pW;ku$cܐl`)zH^ anLjS3IDs?{c2Q-NKdаcP6wbҨ ;*{$Q- VRl5gSՃ4˞Xr=9zo暶, u$6f|h.i,eL൱p7 oxWٞ"k/*1CᾠemR͠gv$>K7Д7QB>Qϒ OZR 怰 ThTo<諩ʊQsr= mCƼO S֔ʒJ/p N/qIg}CK=M{W&mI0'2O#* (Zb*IMnt U(NG4ie kdJ_t񸏎^zؽG[bir:}#ҁ:੐7{(IJ[0tC|T%U/F{7E`B,Gnl?x2Yt"LY?5Py-@U?,Q  CĬ*,kH>6<ВGgcA;-ɶS*IS3Zɀb5'P6 $v 2ֹAp?djmock-library-2.12.0/testjar/secring.gpg000066400000000000000000000051201347002534600201500ustar00rootroot00000000000000ThsЪu/.,8qFTC&g SBSƾwz$EEO@,wB[mg=0 J+\Qcg9n\Ӆ\7|o6`w`\ߡ=ݷuGjpRbȭ#,%Na%dخlu/B ( bGĤ PW[n禀Joo;j >^An$LUY9ܤ38/`4#dA%Z-;Y "S<HJŷT-~t xO*r2{$#nz w0]$` q xG XMc 4 >tTP_xqoʟhKT4 ?&BKUۈo6Y*-ݴ Y_{&6aK!܇0P ܳg$KyQpTn_}g -]jX [f؊^oj$tj~:݆I/puױIDsrgNot Oli Bye (Insecure keypair for JMock testjar signatures) 8"Th   p $pW;ku$cܐl`)zH^ anLjS3IDs?{c2Q-NKdаcP6wbҨ ;*{$Q- VRl5gSՃ4˞Xr=9zo暶, u$6f|h.i,eL൱p7 oxWٞ"k/*1CᾠemR͠gv$>K7Д7QB>Qϒ OZR 怰ThTo<諩ʊQsr= mCƼO S֔ʒJ/p N/qIg}CK=M{W&mI0'2O#* (Zb*IMnt U(NG4ie kdJ_t񸏎^zؽG[bir:}#ҁ:੐7{(IJ[0tC|T%U/F aN]-F?ZJ,-C^C OŜ:g~TZK>4 sC,B`:m)*h569o=k̓Oż*&O("-¯.@?"bpzL%^gUW|~ zC2:Lv(@@ueF,!6xȔRM+#_i璒*'q`#vI@9Uzs?o;wИ*m`ehW8.~^J 9~<IciFTڡ/pESOִu(3z|I)ү"Lbʔ%W4_j!pV y-j*c^P\ͲrI 1[(/L$GlK//\Ƥ:a%9T ysҭgTf^ĬqW|uF˱///a:? 4zpwHGg"SZsnBü ž~(l*=r@sn@&NlN% v8]Jt3KǙ1ύa"P Th p $*KjhEט菕in6 o)o;J_}s>{7E`B,Gnl?x2Yt"LY?5Py-@U?,Q  CĬ*,kH>6<ВGgcA;-ɶS*IS3Zɀb5'P6 $v 2ֹAp?djmock-library-2.12.0/testjar/src/000077500000000000000000000000001347002534600166105ustar00rootroot00000000000000jmock-library-2.12.0/testjar/src/main/000077500000000000000000000000001347002534600175345ustar00rootroot00000000000000jmock-library-2.12.0/testjar/src/main/java/000077500000000000000000000000001347002534600204555ustar00rootroot00000000000000jmock-library-2.12.0/testjar/src/main/java/org/000077500000000000000000000000001347002534600212445ustar00rootroot00000000000000jmock-library-2.12.0/testjar/src/main/java/org/jmock/000077500000000000000000000000001347002534600223475ustar00rootroot00000000000000jmock-library-2.12.0/testjar/src/main/java/org/jmock/testjar/000077500000000000000000000000001347002534600240235ustar00rootroot00000000000000jmock-library-2.12.0/testjar/src/main/java/org/jmock/testjar/ClassFromOtherClassLoader.java000066400000000000000000000001511347002534600316730ustar00rootroot00000000000000package org.jmock.testjar; public class ClassFromOtherClassLoader { public void doSomething() {} } jmock-library-2.12.0/testjar/src/main/java/org/jmock/testjar/InterfaceFromOtherClassLoader.java000066400000000000000000000003141347002534600325270ustar00rootroot00000000000000package org.jmock.testjar; import javax.annotation.Nullable; public interface InterfaceFromOtherClassLoader { //void doSomething(); @Nullable T stir(T tea); T stir(int lumps); } jmock-library-2.12.0/testjar/src/main/java/org/jmock/testjar/TypeInSignedJar.java000066400000000000000000000002421347002534600276630ustar00rootroot00000000000000package org.jmock.testjar; /** * Can't use the default package across shared and unshared jars */ public interface TypeInSignedJar { void doSomething(); }