You can subscribe to this list here.
2001 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(13) |
Aug
(151) |
Sep
(21) |
Oct
(6) |
Nov
(70) |
Dec
(8) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2002 |
Jan
(47) |
Feb
(66) |
Mar
(23) |
Apr
(115) |
May
(24) |
Jun
(53) |
Jul
(10) |
Aug
(279) |
Sep
(84) |
Oct
(149) |
Nov
(138) |
Dec
(52) |
2003 |
Jan
(22) |
Feb
(20) |
Mar
(29) |
Apr
(106) |
May
(170) |
Jun
(122) |
Jul
(70) |
Aug
(64) |
Sep
(27) |
Oct
(71) |
Nov
(49) |
Dec
(9) |
2004 |
Jan
(7) |
Feb
(38) |
Mar
(3) |
Apr
(9) |
May
(22) |
Jun
(4) |
Jul
(1) |
Aug
(2) |
Sep
(2) |
Oct
|
Nov
(15) |
Dec
(2) |
2005 |
Jan
(1) |
Feb
(1) |
Mar
|
Apr
(1) |
May
(28) |
Jun
(3) |
Jul
(11) |
Aug
(5) |
Sep
(1) |
Oct
(5) |
Nov
(2) |
Dec
(3) |
2006 |
Jan
(8) |
Feb
(3) |
Mar
(8) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Joe W. <joe...@us...> - 2002-10-14 19:14:20
|
Update of /cvsroot/mockobjects/nmock/test/NMock In directory usw-pr-cvs1:/tmp/cvs-serv19252a/test/NMock Modified Files: MockTest.cs Log Message: Expectations now setup on per method basis rather than per mock Index: MockTest.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/test/NMock/MockTest.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- MockTest.cs 14 Oct 2002 18:43:30 -0000 1.3 +++ MockTest.cs 14 Oct 2002 19:14:13 -0000 1.4 @@ -53,6 +53,13 @@ } [Test] + public void CallWithNoExpectation() + { + mock.Call("myMethod"); + mock.Verify(); + } + + [Test] public void ManyCallsToVoidMethod() { mock.Expect("myMethod"); @@ -101,15 +108,28 @@ } [Test] - [ExpectedException(typeof(VerifyException))] - public void CallMultipleMethodsInWrongOrder() + public void CallMultipleMethodsInDifferentOrder() { mock.Expect("myMethod1"); mock.Expect("myMethod2"); mock.Expect("myMethod3"); - mock.Call("myMethod1"); mock.Call("myMethod3"); + mock.Call("myMethod1"); + mock.Call("myMethod2"); + mock.Verify(); + } + + [Test] + public void CallMultipleMethodsSomeWithoutExpectations() + { + mock.Expect("myMethod1"); + mock.Expect("myMethod3"); + mock.Expect("myMethod3"); + mock.Call("myMethod2"); + mock.Call("myMethod3"); + mock.Call("myMethod1"); + mock.Call("myMethod3"); mock.Verify(); } |
From: Joe W. <joe...@us...> - 2002-10-14 18:43:33
|
Update of /cvsroot/mockobjects/nmock/test/NMock/Dynamic In directory usw-pr-cvs1:/tmp/cvs-serv6916/test/NMock/Dynamic Modified Files: ClassGeneratorTest.cs Log Message: Decoupled from NUnit. Use testing framework of choice. Index: ClassGeneratorTest.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/test/NMock/Dynamic/ClassGeneratorTest.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -u -r1.3 -r1.4 --- ClassGeneratorTest.cs 7 Oct 2002 00:08:02 -0000 1.3 +++ ClassGeneratorTest.cs 14 Oct 2002 18:43:30 -0000 1.4 @@ -134,7 +134,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void CallMethodWithParamExpectationsThatFails() { mock.Expect("WithSimpleArg", new IsEqual("hello")); @@ -151,7 +151,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void CallMethodWithTwoParamExpectationsThatFails() { mock.Expect("WithTwoArgs", new IsEqual("hello"), new IsEqual("world")); |
From: Joe W. <joe...@us...> - 2002-10-14 18:43:33
|
Update of /cvsroot/mockobjects/nmock/src/NMock In directory usw-pr-cvs1:/tmp/cvs-serv6916/src/NMock Modified Files: Mock.cs Added Files: VerifyException.cs Log Message: Decoupled from NUnit. Use testing framework of choice. --- NEW FILE: VerifyException.cs --- using System; namespace NMock { public class VerifyException : Exception { public VerifyException(string msg) : base(msg) { } } } Index: Mock.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/src/NMock/Mock.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- Mock.cs 6 Oct 2002 22:57:48 -0000 1.2 +++ Mock.cs 14 Oct 2002 18:43:29 -0000 1.3 @@ -1,6 +1,5 @@ using System; using System.Collections; -using NUnit.Framework; namespace NMock { @@ -134,7 +133,31 @@ return returnValue; } } - + + private class Assertion + { + public static void Assert(bool expression) + { + if (!expression) + { + Fail("Verification failed."); + } + } + + public static void AssertEquals(object a, object b) + { + if (! a.Equals(b)) + { + Fail("Verification failed."); + } + } + + public static void Fail(string msg) + { + throw new VerifyException(msg); + } + } + } |
From: Joe W. <joe...@us...> - 2002-10-14 18:43:33
|
Update of /cvsroot/mockobjects/nmock/test/NMock In directory usw-pr-cvs1:/tmp/cvs-serv6916/test/NMock Modified Files: MockTest.cs Log Message: Decoupled from NUnit. Use testing framework of choice. Index: MockTest.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/test/NMock/MockTest.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- MockTest.cs 6 Oct 2002 22:57:48 -0000 1.2 +++ MockTest.cs 14 Oct 2002 18:43:30 -0000 1.3 @@ -36,7 +36,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void NoCallToVoidMethod() { mock.Expect("myMethod"); @@ -44,7 +44,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void TooManyCallsToVoidMethod() { mock.Expect("myMethod"); @@ -73,7 +73,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void CallToMethodWithInvalidParams() { mock.Expect("myMethod", new IsEqual("hello"), new IsAnything()); @@ -101,7 +101,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void CallMultipleMethodsInWrongOrder() { mock.Expect("myMethod1"); @@ -134,7 +134,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void CallToNonVoidMethodWithWrongParams() { object something = new object(); @@ -176,7 +176,7 @@ } [Test] - [ExpectedException(typeof(AssertionException))] + [ExpectedException(typeof(VerifyException))] public void DefaultEqualsPredicatesFailure() { mock.Expect("myMethod", new object()); |
From: Nat P. <np...@us...> - 2002-10-14 18:01:56
|
Update of /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock In directory usw-pr-cvs1:/tmp/cvs-serv20269/test/com/b13media/mock Modified Files: Test_Predicates.java Log Message: IsEventFrom predicate can test for event type. Index: Test_Predicates.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock/Test_Predicates.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- Test_Predicates.java 11 Oct 2002 14:57:35 -0000 1.2 +++ Test_Predicates.java 14 Oct 2002 18:01:16 -0000 1.3 @@ -6,6 +6,8 @@ import java.util.EventObject; +import javax.swing.AbstractAction; + public class Test_Predicates @@ -115,6 +117,31 @@ !p.eval(ev2) ); assertTrue( "p should eval to false for objects that are not events", !p.eval(o) ); + } + + private static class DerivedEvent extends EventObject { + public DerivedEvent( Object source ) { + super(source); + } + } + + public void testIsEventSubtypeFrom() { + Object o = new Object(); + DerivedEvent good_ev = new DerivedEvent(o); + DerivedEvent wrong_source = new DerivedEvent(new Object()); + EventObject wrong_type = new EventObject(o); + EventObject wrong_source_and_type = new EventObject(new Object()); + + Predicate p = new IsEventFrom( DerivedEvent.class, o ); + + assertTrue( p.eval(good_ev) ); + assertTrue( "p should eval to false for an event not from o", + !p.eval(wrong_source) ); + assertTrue( "p should eval to false for an event of the wrong type", + !p.eval(wrong_type) ); + assertTrue( "p should eval to false for an event of the wrong type "+ + "and from the wrong source", + !p.eval(wrong_source_and_type) ); } public void testMatches() { |
From: Nat P. <np...@us...> - 2002-10-14 18:01:24
|
Update of /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock In directory usw-pr-cvs1:/tmp/cvs-serv20269/source/com/b13media/mock Modified Files: IsEventFrom.java Log Message: IsEventFrom predicate can test for event type. Index: IsEventFrom.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock/IsEventFrom.java,v retrieving revision 1.1 retrieving revision 1.2 diff -u -r1.1 -r1.2 --- IsEventFrom.java 11 Oct 2002 14:57:37 -0000 1.1 +++ IsEventFrom.java 14 Oct 2002 18:01:18 -0000 1.2 @@ -9,22 +9,30 @@ public class IsEventFrom implements Predicate { + private Class _event_class; private Object _source; public IsEventFrom( Object source ) { + this( EventObject.class, source ); + } + + public IsEventFrom( Class event_class, Object source ) { + _event_class = event_class; _source = source; } - + public boolean eval( Object o ) { if( o instanceof EventObject ) { EventObject ev = (EventObject)o; - return ev.getSource() == _source; + return _event_class.isInstance(o) && ev.getSource() == _source; + } else { return false; } } public String toString() { - return "an event from " + _source.toString(); + return "an event of type " + _event_class.getName() + + " from " + _source.toString(); } } |
From: Nat P. <np...@us...> - 2002-10-14 14:42:52
|
Update of /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock In directory usw-pr-cvs1:/tmp/cvs-serv12855/test/com/b13media/mock Modified Files: Test_Mock.java Log Message: Added expectNotCalled method to Mock class. Index: Test_Mock.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock/Test_Mock.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- Test_Mock.java 11 Oct 2002 14:57:35 -0000 1.2 +++ Test_Mock.java 14 Oct 2002 14:42:47 -0000 1.3 @@ -194,7 +194,7 @@ fail( "strict mock did not fail when unexpected method was called" ); } - public void testUnexpectedMethodDoesNotThrowsWhenNotStrict() { + public void testUnexpectedMethodDoesNotThrowWhenNotStrict() { try { _interface.voidMethod(); } @@ -276,6 +276,27 @@ } fail( "mock did not enforce order of calls" ); + } + + public void testExpectNotCalled() { + _mock.expectNotCalled("noArgs"); + try { + _interface.noArgs(); + } + catch( AssertionFailedError ex ) { + return; + } + + fail("AssertionFailedError expected"); + } + + public void testExpectNotCalledClearedBySubsequentExpectation() { + _mock.expectNotCalled("noArgs"); + _mock.expectVoid( "noArgs", Mock.NO_ARGS ); + + _interface.noArgs(); + + _mock.verify(); } public void testNoErrorWhenOrderedMethodsCalledInCorrectOrder() { |
From: Nat P. <np...@us...> - 2002-10-14 14:42:52
|
Update of /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock In directory usw-pr-cvs1:/tmp/cvs-serv12855/source/com/b13media/mock Modified Files: Mock.java Log Message: Added expectNotCalled method to Mock class. Index: Mock.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock/Mock.java,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- Mock.java 11 Oct 2002 14:57:37 -0000 1.2 +++ Mock.java 14 Oct 2002 14:42:47 -0000 1.3 @@ -33,6 +33,7 @@ private String _name; private Map _expectations = new HashMap(); + private Set _expectations_not_called = new HashSet(); private Map _order_constraints = new HashMap(); private Set _called_methods = new HashSet(); private boolean _strict = false; @@ -98,6 +99,7 @@ */ public void expect( ExpectedCall call ) { _expectations.put( call.getMethodName(), call ); + _expectations_not_called.remove( call.getMethodName() ); } /** Expect a method call and return a result when it is called. @@ -153,6 +155,17 @@ expect( new ExpectedThrow( method, args, exception ) ); } + /** Expect a method not to be called. + * An {@link junit.framework.AssertionFailedError} will be thrown if + * the method is called. + * + * @param method + * The name of the method that will not be called. + */ + public void expectNotCalled( String method ) { + _expectations_not_called.add(method); + } + /** Define an order between two calls. The method named * <var>subsequent_method</var> <em>must</em> be called after * the method namd <var>preceding_method</var>, otherwise an @@ -193,6 +206,8 @@ { String method_name = method.getName(); + assertCanBeCalled( method_name ); + if( _expectations.containsKey( method_name ) ) { ExpectedCall expected = (ExpectedCall)_expectations.get(method_name); @@ -262,9 +277,15 @@ } } + private void assertCanBeCalled( String method_name ) { + if( _expectations_not_called.contains(method_name) ) { + fail(_name + ": unexpected call to method " + method_name ); + } + } + private void assertHasBeenCalled( String method_name ) { if( !_called_methods.contains(method_name) ) { - fail( "method " + method_name + " was not called" ); + fail( _name + ": method " + method_name + " was not called" ); } } |
From: Jeff M. <je...@cu...> - 2002-10-14 11:17:23
|
Ah, I did make sure it all worked with jdk1.4 but it gets a bit confusing going back and forth between j2ee1.2 and 1.3. I don't really have the j2ee1.2 stuff set up anymore. We really should try and sort out a system for checking the build against all supported environments. On Mon, 2002-10-14 at 12:00, Steve Freeman wrote: > Jeff, > > I've been trying to build all the combinations from a script and some of > the alt and helper stuff only works with j2ee 1.3. I've been moving that > stuff into the relevant subtree so that j2ee 1.2 will build. Not > finished yet. > > S. > -- Jeff Martin <je...@cu...> |
From: Jeff M. <je...@mk...> - 2002-10-14 11:10:42
|
Personally I'd rather see dotnetmock move over here. Not to try and subsume what you're doing but to try and keep the flow of ideas between different implementations going. It would be nice to present a united front rather than a whole series of small loosely related projects. On Mon, 2002-10-07 at 23:58, Griffin Caprio wrote: > Sounds good. I would like to keep the dynamic stuff and static stuff > together, also > > Joe, would you like to move the module to the dotnetmock project on > sourceforge? > > -Griffin > > > >From: "Steve Freeman" <st...@m3...> > >To: "Griffin Caprio" > ><gri...@ho...>,<jo...@tr...>,<moc...@li...> > >Subject: Re: [MO-java-dev] .NET Mock Objects? > >Date: Mon, 7 Oct 2002 21:14:17 +0100 > > > > > As for rolling in NMock stuff, I am thinking that would be a good thing > >as > > > opposed to keeping it in the java implementation. .NET developers might > >not > > > know it is there. > > > > > > Steve, Tim, or Philip, want to chime in as how to structure/organize > >these > > > kinds of things? > > > >I'm increasingly convinced that we want to merge the two approaches and > >would like to do the same in the Java world. > > > >As for separate or same project, I don't really mind. Joe started a module > >here just to have somewhere to put it. He could move if he liked. The main > >thing is to keep things cross-linked. > > > >S. > > > > > Griffin Caprio > cell: (773) 230-0936 > > > _________________________________________________________________ > Chat with friends online, try MSN Messenger: http://messenger.msn.com > > > > ------------------------------------------------------- > This sf.net email is sponsored by:ThinkGeek > Welcome to geek heaven. > http://thinkgeek.com/sf > _______________________________________________ > Mockobjects-java-dev mailing list > Moc...@li... > https://lists.sourceforge.net/lists/listinfo/mockobjects-java-dev -- Jeff Martin <je...@mk...> mkodo |
From: Jeff M. <je...@mk...> - 2002-10-14 11:00:12
|
I've added a link on from www.mockobjects.com to this. At some point I might add a bit more detail about each project. On Fri, 2002-10-11 at 06:10, Griffin Caprio wrote: > This is an announcement for the initial release of the .NET Mock Objects > core framework. > > http://www.sourceforge.net/projects/dotnetmock > > The initial .NET implementation of the core framework is complete. Next is > the implementation of standard .NET objects. > > Feedback is welcome as well as any help or contributions. After all, there > is only one lowly programmer working on this ;) > > -Griffin > > > > ------------------------------------------------------- > This sf.net email is sponsored by:ThinkGeek > Welcome to geek heaven. > http://thinkgeek.com/sf > _______________________________________________ > Mockobjects-java-dev mailing list > Moc...@li... > https://lists.sourceforge.net/lists/listinfo/mockobjects-java-dev -- Jeff Martin <je...@mk...> mkodo |
From: Jeff M. <cus...@us...> - 2002-10-14 10:50:49
|
Update of /cvsroot/mockobjects/mockobjects-java/doc/html In directory usw-pr-cvs1:/tmp/cvs-serv22285/html Modified Files: template.txt Log Message: Added link to .NET mock Index: template.txt =================================================================== RCS file: /cvsroot/mockobjects/mockobjects-java/doc/html/template.txt,v retrieving revision 1.7 retrieving revision 1.8 diff -u -r1.7 -r1.8 --- template.txt 9 Sep 2002 09:43:29 -0000 1.7 +++ template.txt 14 Oct 2002 10:50:44 -0000 1.8 @@ -67,6 +67,8 @@ <a target="_blank" href="http://www.abstrakt.de/mockcreator.html">Mock Creator</a><br> <a target="_blank" href="http://www.mockmaker.org/">Mock Maker</a><br> + <a target="_blank" + href="http://www.sourceforge.net/projects/dotnetmock">.NET Mock</a><br> <a target="_blank" href="http://joe.truemesh.com/mockdoclet/">Mock Doclet</a> </td> |
From: Nat P. <np...@us...> - 2002-10-11 14:58:11
|
Update of /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock In directory usw-pr-cvs1:/tmp/cvs-serv19938/test/com/b13media/mock Modified Files: Test_Predicates.java Test_Mock.java Log Message: Mock does not care about order of method calls unless explicitly specified. Mock synthesises results for unexpected methods, unless explicitly told to throw errors. New predicates: IsEventFrom and Matches (regex matching of strings). Index: Test_Predicates.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock/Test_Predicates.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -u -r1.1.1.1 -r1.2 --- Test_Predicates.java 22 May 2002 10:03:00 -0000 1.1.1.1 +++ Test_Predicates.java 11 Oct 2002 14:57:35 -0000 1.2 @@ -4,6 +4,8 @@ */ package com.b13media.mock; +import java.util.EventObject; + public class Test_Predicates @@ -99,5 +101,29 @@ assertTrue( new Or( new False(), new True() ).eval(o) ); assertTrue( new Or( new True(), new False() ).eval(o) ); assertTrue( !new Or( new False(), new False() ).eval(o) ); + } + + public void testIsEventFrom() { + Object o = new Object(); + EventObject ev = new EventObject(o); + EventObject ev2 = new EventObject( new Object() ); + + Predicate p = new IsEventFrom(o); + + assertTrue( p.eval(ev) ); + assertTrue( "p should eval to false for an event not from o", + !p.eval(ev2) ); + assertTrue( "p should eval to false for objects that are not events", + !p.eval(o) ); + } + + public void testMatches() { + Predicate p = new Matches("^hello, (.*)\\.$"); + + assertTrue( p.eval("hello, world.") ); + assertTrue( p.eval("hello, mum.") ); + assertTrue( !p.eval("hello world.") ); + assertTrue( !p.eval("hello, world") ); + assertTrue( !p.eval("goodbye, world.") ); } } Index: Test_Mock.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/test/com/b13media/mock/Test_Mock.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -u -r1.1.1.1 -r1.2 --- Test_Mock.java 22 May 2002 10:03:00 -0000 1.1.1.1 +++ Test_Mock.java 11 Oct 2002 14:57:35 -0000 1.2 @@ -4,6 +4,7 @@ */ package com.b13media.mock; +import java.lang.reflect.Method; import java.lang.reflect.Proxy; import junit.framework.AssertionFailedError; @@ -17,6 +18,21 @@ String objectTypes( Integer i ); int primitiveTypes( int x, int y ); void sideEffect( StringBuffer buf ); + + // These are used to test default return values + boolean booleanResult(); + byte byteResult(); + char charResult(); + short shortResult(); + int intResult(); + long longResult(); + float floatResult(); + double doubleResult(); + String stringResult(); + + // Used to test ordered calls + void first(); + void second(); } public static class DerivedMock @@ -33,7 +49,10 @@ } public String objectTypes( Integer n ) throws Throwable { - return (String)mockCall( "objectTypes", new Object[]{n} ); + Method method = getClass().getMethod("objectTypes", + new Class[] { Integer.class } ); + + return (String)mockCall( method , new Object[]{n} ); } }; @@ -48,10 +67,8 @@ public void setUp() { _mock = new Mock(); - _interface = (ExampleInterface)Proxy.newProxyInstance( - getClass().getClassLoader(), - new Class[]{ ExampleInterface.class }, - _mock ); + _interface = + (ExampleInterface)_mock.createInterface( ExampleInterface.class ); } public void tearDown() { @@ -71,7 +88,7 @@ public void testMockCallToNoArgMethod() { Object result = new Object(); - _mock.expectReturn( "noArgs", new Predicate[0], result ); + _mock.expectReturn( "noArgs", Mock.NO_ARGS, result ); assertSame( result, _interface.noArgs() ); @@ -79,7 +96,7 @@ } public void testMockCallToVoidMethod() { - _mock.expectVoid( "voidMethod", new Predicate[0] ); + _mock.expectVoid( "voidMethod", Mock.NO_ARGS ); _interface.voidMethod(); @@ -105,14 +122,14 @@ _mock.verify(); } - public void testMultipleCalls() { + public void testLaterExpectationsOverrideEarlierExpectations() { Object result1 = new Object(); Object result2 = new Object(); - _mock.expectReturn( "noArgs", new Predicate[0], result1 ); - _mock.expectReturn( "noArgs", new Predicate[0], result2 ); + _mock.expectReturn( "noArgs", Mock.NO_ARGS, result1 ); + _mock.expectReturn( "noArgs", Mock.NO_ARGS, result2 ); - assertSame( result1, _interface.noArgs() ); + assertSame( result2, _interface.noArgs() ); assertSame( result2, _interface.noArgs() ); _mock.verify(); } @@ -152,7 +169,7 @@ } public void testNotAllMethodsCalled() { - _mock.expectVoid( "noArg", new Predicate[0] ); + _mock.expectVoid( "noArg", Mock.NO_ARGS ); try { _mock.verify(); @@ -161,20 +178,41 @@ return; } - fail( "verify did fail when all methods were not called" ); + fail( "verify did not fail when all methods were not called" ); } - public void testInvalidMethod() { - _mock.expectVoid( "noArg", new Predicate[0] ); + public void testUnexpectedMethodThrowsWhenStrict() { + _mock.setStrict(true); try { - _interface.objectTypes( new Integer(1) ); + _interface.voidMethod(); } catch( AssertionFailedError ex ) { return; } - fail( "mock did not fail when unexpected method was called" ); + fail( "strict mock did not fail when unexpected method was called" ); + } + + public void testUnexpectedMethodDoesNotThrowsWhenNotStrict() { + try { + _interface.voidMethod(); + } + catch( AssertionFailedError ex ) { + fail( "unstrict mock failed when unexpected method was called" ); + } + } + + public void testDefaultResultFromUnexpectedCalls() { + assertEquals( false, _interface.booleanResult() ); + assertEquals( 0, _interface.byteResult() ); + assertEquals( '\0', _interface.charResult() ); + assertEquals( 0, _interface.shortResult() ); + assertEquals( 0, _interface.intResult() ); + assertEquals( 0L, _interface.longResult() ); + assertEquals( 0.0f, _interface.floatResult(), 0.0f ); + assertEquals( 0.0d, _interface.doubleResult(), 0.0d ); + assertEquals( "", _interface.stringResult() ); } public void testWrongNumberOfArguments() { @@ -222,6 +260,32 @@ } fail( "mock did not fail when predicate returned false" ); + } + + public void testErrorWhenOrderedMethodsCalledInWrongOrder() { + _mock.expectVoid( "first", Mock.NO_ARGS ); + _mock.expectVoid( "second", Mock.NO_ARGS ); + + _mock.order( "first", "second" ); + + try { + _interface.second(); + } + catch( AssertionFailedError ex ) { + return; + } + + fail( "mock did not enforce order of calls" ); + } + + public void testNoErrorWhenOrderedMethodsCalledInCorrectOrder() { + _mock.expectVoid( "first", Mock.NO_ARGS ); + _mock.expectVoid( "second", Mock.NO_ARGS ); + + _mock.order( "first", "second" ); + + _interface.first(); + _interface.second(); } public void testDerivedMockClass() { |
From: Nat P. <np...@us...> - 2002-10-11 14:57:46
|
Update of /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock In directory usw-pr-cvs1:/tmp/cvs-serv19938/source/com/b13media/mock Modified Files: ExpectedCall.java Mock.java Added Files: Matches.java IsEventFrom.java Log Message: Mock does not care about order of method calls unless explicitly specified. Mock synthesises results for unexpected methods, unless explicitly told to throw errors. New predicates: IsEventFrom and Matches (regex matching of strings). --- NEW FILE: Matches.java --- /* Copyright (c) 2002 Nat Pryce. All rights reserved. * * Created on February 10, 2002, 11:35 PM */ package com.b13media.mock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Is the argument equal to another value, as tested by the * {@link java.lang.Object#equals} method? */ public class Matches implements Predicate { private Pattern _pattern; private Matcher _matcher; /** Creates a new instance of IsEqual */ public Matches( String regex ) { _pattern = Pattern.compile(regex); } public boolean eval( Object arg ) { if( arg instanceof String ) { Matcher matcher = _pattern.matcher((String)arg); return matcher.matches(); } else { return false; } } public String toString() { return "a string that matches <" + _pattern.toString() + ">"; } } --- NEW FILE: IsEventFrom.java --- /** Created on Jun 28, 2002 by npryce * Copyright (c) B13media Ltd. */ package com.b13media.mock; import java.util.EventObject; public class IsEventFrom implements Predicate { private Object _source; public IsEventFrom( Object source ) { _source = source; } public boolean eval( Object o ) { if( o instanceof EventObject ) { EventObject ev = (EventObject)o; return ev.getSource() == _source; } else { return false; } } public String toString() { return "an event from " + _source.toString(); } } Index: ExpectedCall.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock/ExpectedCall.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -u -r1.1.1.1 -r1.2 --- ExpectedCall.java 22 May 2002 10:02:49 -0000 1.1.1.1 +++ ExpectedCall.java 11 Oct 2002 14:57:36 -0000 1.2 @@ -8,6 +8,7 @@ /** An expected call to a method of a mock object */ abstract class ExpectedCall + extends junit.framework.Assert { private String _name; private Predicate[] _expected_args; @@ -27,7 +28,7 @@ return _expected_args.length; } - public boolean checkArgument( int n, Object arg ) { + public boolean testArgument( int n, Object arg ) { return _expected_args[n].eval(arg); } Index: Mock.java =================================================================== RCS file: /cvsroot/mockobjects/nat/jmock/source/com/b13media/mock/Mock.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -u -r1.1.1.1 -r1.2 --- Mock.java 22 May 2002 10:02:53 -0000 1.1.1.1 +++ Mock.java 11 Oct 2002 14:57:37 -0000 1.2 @@ -6,7 +6,17 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import java.util.LinkedList; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.HashMap; +import java.util.Set; + +import junit.framework.AssertionFailedError; /** A convenient class for creating simple @@ -14,18 +24,35 @@ */ public class Mock extends junit.framework.Assert - implements InvocationHandler + implements InvocationHandler { + /** A convenient constant for defining expectations for methods that + * have no methods. + */ public static final Predicate[] NO_ARGS = new Predicate[0]; private String _name; - private LinkedList _expectations = new LinkedList(); + private Map _expectations = new HashMap(); + private Map _order_constraints = new HashMap(); + private Set _called_methods = new HashSet(); + private boolean _strict = false; + + private Map _default_results = new HashMap(); /** Creates a named Mock object, The name will be included in the messages * of exceptions thrown to indicate violated expectations. */ public Mock( String name ) { _name = name; + addDefaultResult( byte.class, new Byte((byte)0) ); + addDefaultResult( short.class, new Short((short)0) ); + addDefaultResult( int.class, new Integer(0) ); + addDefaultResult( long.class, new Long(0L) ); + addDefaultResult( float.class, new Float(0.0f) ); + addDefaultResult( double.class, new Double(0.0d) ); + addDefaultResult( boolean.class, Boolean.FALSE ); + addDefaultResult( char.class, new Character('\0') ); + addDefaultResult( String.class, "" ); } /** Creates a Mock object and automatically assigns a name to it. The assigned @@ -35,13 +62,33 @@ * objects if you use more than one in the same test case. */ public Mock() { + this(null); _name = super.toString(); } + /** Returns the Mock's name. + */ public String toString() { return _name; } + /** Is the mock in strict mode? In strict mode the mock will throw + * {@link junit.framework.AssertionFailedError} exceptions when + * unexpected method calls are made. Otherwise, the mock ignore + * the call or return default arguments. + */ + public boolean isStrict() { + return _strict; + } + + public void setStrict( boolean strict ) { + _strict = strict; + } + + public void addDefaultResult( Class result_type, Object result_value ) { + _default_results.put( result_type, result_value ); + } + /** Expect a method call and mock the behaviour of that call. * * @param call @@ -50,7 +97,7 @@ * The state of the mock object after the call as occurred. */ public void expect( ExpectedCall call ) { - _expectations.addLast(call); + _expectations.put( call.getMethodName(), call ); } /** Expect a method call and return a result when it is called. @@ -106,47 +153,92 @@ expect( new ExpectedThrow( method, args, exception ) ); } + /** Define an order between two calls. The method named + * <var>subsequent_method</var> <em>must</em> be called after + * the method namd <var>preceding_method</var>, otherwise an + * {@link junit.framework.AssertionFailedError} will be thrown. + */ + public void order( String preceding_method, String subsequent_method ) { + Set preceding_calls; + if( _order_constraints.containsKey(subsequent_method) ) { + preceding_calls = (Set)_order_constraints.get(subsequent_method); + } else { + preceding_calls = new HashSet(); + _order_constraints.put( subsequent_method, preceding_calls ); + } + + preceding_calls.add( preceding_method ); + } + /** Called by the {@link java.lang.reflect.Proxy} to mock the behaviour of an * invoked method and check expectations. */ public Object invoke( Object obj, Method method, Object[] args ) throws Throwable { + _called_methods.add( method.getName() ); + try { return getClass().getMethod( method.getName(), method.getParameterTypes() ).invoke( this, args ); } catch( NoSuchMethodException ex ) { - return mockCall( method.getName(), args ); + return mockCall( method, args ); } } - protected Object mockCall( String method_name, Object[] args ) + protected Object mockCall( Method method, Object[] args ) throws Throwable { - assertTrue( _name + ": unexpected call to " + method_name, - !_expectations.isEmpty() ); - - ExpectedCall expected = (ExpectedCall)_expectations.removeFirst(); - - assertEquals( _name + ": unexpected method called", - expected.getMethodName(), method_name ); + String method_name = method.getName(); + if( _expectations.containsKey( method_name ) ) { + ExpectedCall expected = + (ExpectedCall)_expectations.get(method_name); + + checkCallOrder( method_name ); + checkArguments( expected, args ); + return expected.eval( args ); + + } else if( _strict ) { + throw new AssertionFailedError( + _name + ": unexpected call to " + method_name ); + } else { + return defaultResult( method.getReturnType() ); + } + } + + private void checkCallOrder( String method_name ) { + if( _order_constraints.containsKey(method_name) ) { + assertMethodsHaveBeenCalled( + (Set)_order_constraints.get(method_name) ); + } + } + + private void checkArguments( ExpectedCall expected, Object[] args ) + { int arg_count = (args == null) ? 0 : args.length; assertEquals( _name + ": wrong number of arguments to " + - method_name + " method", + expected.getMethodName() + " method", expected.getArgumentCount(), arg_count ); for( int i = 0; i < arg_count; i++ ) { - if( !expected.checkArgument( i, args[i] ) ) { + if( !expected.testArgument( i, args[i] ) ) { fail( _name + ": unexpected argument " + (i+1) + + " to " + expected.getMethodName() + " method" + ", expected " + expected.describeArgument(i) + ", was " + args[i].toString() ); } } - - return expected.eval( args ); + } + + private Object defaultResult( Class return_type ) { + if( _default_results.containsKey(return_type) ) { + return _default_results.get(return_type); + } else { + return null; + } } /** Fails if not all the expected calls have been made to this mock object. @@ -155,7 +247,39 @@ * Not all expected calls were made to this mock object. */ public void verify() { - assertTrue( "not all expected calls were made to " + _name, - _expectations.isEmpty() ); + assertAllExpectedMethodsCalled(); + } + + private void assertAllExpectedMethodsCalled() { + + assertMethodsHaveBeenCalled( _expectations.keySet() ); + } + + private void assertMethodsHaveBeenCalled( Set method_names ) { + Iterator i = method_names.iterator(); + while( i.hasNext() ) { + assertHasBeenCalled( (String)i.next() ); + } + } + + private void assertHasBeenCalled( String method_name ) { + if( !_called_methods.contains(method_name) ) { + fail( "method " + method_name + " was not called" ); + } + } + + public Object createInterface( Class interface_class ) { + return createInterface( interface_class.getClassLoader(), + new Class[]{ interface_class } ); + } + + public Object createInterface( ClassLoader loader, Class interface_class ) { + return createInterface( loader, new Class[]{ interface_class } ); + } + + public Object createInterface( ClassLoader loader, + Class[] interface_classes ) + { + return Proxy.newProxyInstance( loader, interface_classes, this ); } } |
From: Griffin C. <gri...@at...> - 2002-10-11 05:11:10
|
This is an announcement for the initial release of the .NET Mock Objects core framework. http://www.sourceforge.net/projects/dotnetmock The initial .NET implementation of the core framework is complete. Next is the implementation of standard .NET objects. Feedback is welcome as well as any help or contributions. After all, there is only one lowly programmer working on this ;) -Griffin |
From: Griffin C. <gri...@ho...> - 2002-10-07 22:59:02
|
Sounds good. I would like to keep the dynamic stuff and static stuff together, also Joe, would you like to move the module to the dotnetmock project on sourceforge? -Griffin >From: "Steve Freeman" <st...@m3...> >To: "Griffin Caprio" ><gri...@ho...>,<jo...@tr...>,<moc...@li...> >Subject: Re: [MO-java-dev] .NET Mock Objects? >Date: Mon, 7 Oct 2002 21:14:17 +0100 > > > As for rolling in NMock stuff, I am thinking that would be a good thing >as > > opposed to keeping it in the java implementation. .NET developers might >not > > know it is there. > > > > Steve, Tim, or Philip, want to chime in as how to structure/organize >these > > kinds of things? > >I'm increasingly convinced that we want to merge the two approaches and >would like to do the same in the Java world. > >As for separate or same project, I don't really mind. Joe started a module >here just to have somewhere to put it. He could move if he liked. The main >thing is to keep things cross-linked. > >S. Griffin Caprio cell: (773) 230-0936 _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com |
From: Steve F. <st...@m3...> - 2002-10-07 20:39:00
|
> As for rolling in NMock stuff, I am thinking that would be a good thing as > opposed to keeping it in the java implementation. .NET developers might not > know it is there. > > Steve, Tim, or Philip, want to chime in as how to structure/organize these > kinds of things? I'm increasingly convinced that we want to merge the two approaches and would like to do the same in the Java world. As for separate or same project, I don't really mind. Joe started a module here just to have somewhere to put it. He could move if he liked. The main thing is to keep things cross-linked. S. |
From: Joe W. <joe...@us...> - 2002-10-07 19:32:08
|
Update of /cvsroot/mockobjects/nmock/sample/order In directory usw-pr-cvs1:/tmp/cvs-serv25969/sample/order Added Files: Notifier.cs Order.cs OrderProcessor.cs OrderProcessorTest.cs Log Message: Another NMock sample added. --- NEW FILE: Notifier.cs --- using System.Web.Mail; namespace NMockSample.Order { /// <summary> /// Notify people of events using SMTP emails. /// </summary> public class Notifier { private string from = "nobody"; private string admin = "admin"; public virtual void NotifyAdmin(string msg) { MailMessage mail = new MailMessage(); mail.From = from; mail.To = admin; mail.Subject = msg; mail.Body = msg; SmtpMail.Send(mail); } public virtual void NotifyUser(string user, string msg) { MailMessage mail = new MailMessage(); mail.From = from; mail.To = user; mail.Subject = msg; mail.Body = msg; SmtpMail.Send(mail); } } } --- NEW FILE: Order.cs --- using System.Data; using System.Data.SqlClient; namespace NMockSample.Order { /// <summary> /// Details of Order stored directly in database. /// </summary> public class Order { private DataRow row; public virtual int Number { get { return (int)row["number"]; } } public virtual double Amount { get { return (double)row["amount"]; } } public virtual bool Urgent { get { return (bool)row["urgent"]; } } public virtual string User { get { return (string)row["user"]; } } public virtual void Load(SqlConnection con, int id) { string sql = "SELECT * FROM orders WHERE id = " + id; using (SqlDataAdapter adapter = new SqlDataAdapter(sql, con)) { DataTable table = new DataTable(); adapter.Fill(table); row = table.Rows[0]; } } } } --- NEW FILE: OrderProcessor.cs --- using System; namespace NMockSample.Order { /// <summary> /// Process an order: /// - If the amount is greater than or equal to 1000, notify the user that /// their order has been dispatched. /// - If the order is also marked as urgent, notify the administrator to urgently dispatch. /// - If the order is less than 1000, be quiet. It's not worth our time. /// </summary> public class OrderProcessor { internal Notifier notifier = new Notifier(); public virtual void Process(Order order) { if (order.Amount >= 1000) { notifier.NotifyUser(order.User, String.Format( "Order {0} has been dispatched", order.Number)); if (order.Urgent) { notifier.NotifyAdmin(String.Format("Order {0} needs to be urgently dispatched to {1}", order.Number, order.User)); } } } } } --- NEW FILE: OrderProcessorTest.cs --- using NUnit.Framework; using NMock; namespace NMockSample.Order { /// <summary> /// This test demonstrates how to test a class interacts with other domain specific /// classes properly. /// /// The Order class is coupled to the database. The Notifier is coupled to the SMTP mail /// system. This fixture is testing the OrderProcessor which directly interacts with /// Order and Notifier. /// /// The test substitutes in mock implementations of Order and Notifier so OrderProcessor /// can be tested in isolation. /// </summary> [TestFixture] public class OrderProcessorTest { private IMock order; private IMock notifier; private OrderProcessor orderProcessor; [SetUp] public void SetUp() { // setup mock Order and populate with default return values. order = new DynamicMock(typeof(Order)); order.SetValue("Amount", 1002.0); order.SetValue("Urgent", false); order.SetValue("Number", 123); order.SetValue("User", "joe"); // create mock Notifier notifier = new DynamicMock(typeof(Notifier)); // create real OrderProcessor to be tested orderProcessor = new OrderProcessor(); // switch the OrderProcessor to use the mock Notifier orderProcessor.notifier = (Notifier)notifier.Object; } [Test] public void NotifyUser() { // setup notifier.Expect("NotifyUser", "joe", "Order 123 has been dispatched"); // execute orderProcessor.Process((Order)order.Object); // verify notifier.Verify(); } [Test] public void NotifyAnotherUserAnotherNumber() { // setup order.SetValue("Number", 456); order.SetValue("User", "chris"); notifier.Expect("NotifyUser", "chris", "Order 456 has been dispatched"); // execute orderProcessor.Process((Order)order.Object); // verify notifier.Verify(); } [Test] public void DontNotifyUser() { // setup order.SetValue("Amount", 999.0); // execute orderProcessor.Process((Order)order.Object); // verify notifier.Verify(); } [Test] public void NotifyUserAndAdmin() { // setuo order.SetValue("Urgent", true); notifier.Expect("NotifyUser", "joe", "Order 123 has been dispatched"); notifier.Expect("NotifyAdmin", "Order 123 needs to be urgently dispatched to joe"); // execute orderProcessor.Process((Order)order.Object); // verify notifier.Verify(); } [Test] public void DontNotifyEvenThoughUrgent() { // setup order.SetValue("Amount", 999.0); order.SetValue("Urgent", true); // execute orderProcessor.Process((Order)order.Object); // verify notifier.Verify(); } } } |
From: Joe W. <joe...@us...> - 2002-10-07 19:31:22
|
Update of /cvsroot/mockobjects/nmock/sample/order In directory usw-pr-cvs1:/tmp/cvs-serv25677/order Log Message: Directory /cvsroot/mockobjects/nmock/sample/order added to the repository |
From: Simon L. <sim...@uk...> - 2002-10-07 11:10:56
|
Whoops.. Wrong reply mode... =2D--------- Forwarded Message ---------- Subject: Re: [MO-java-dev] Avoiding loops in Verifier again. Date: Monday 07 October 2002 10:14 =46rom: Simon Levitt <sim...@uk...> To: "Steve Freeman" <st...@m3...> On Thursday 03 October 2002 12:30, Steve Freeman wrote: > > The aim of MockObjects, surely?, is to support anything that can be > > thrown at it. Isn't just ignoring this kind of 'problem' limiting? > > The MockObjects must be as complicated as the thing they are trying > > to Mock. Ignoring parts of industry standard interfaces sounds like a > > death sentence to me... > > Not exactly. We also use complexity in testing as a hint that our > design might be getting out of hand. For example, what kind of code > would get a statement from a connection, and then the connection from > the statement, in the same fragment? Sounds like there are two pieces > there that could be tested seperately. That's fair enough. I've actually never used getConnection on a Statement object!. > In that case, you should have different mock clusters set up for each > piece and there should be no recursion. The problem then becomes one of > making test setup lightweight and easy, rather than making the mock > complete. Now whilst I can see this being a nice ideal (and easily implemented for domain specific classes), I can also see the number of these clusters becoming completely unmanageable - both from the point of view of maintenance and upgrade of the Mocks themselves, but finding which cluster to use when writing test cases. With JDBC being such a generic mechanism the way it will be used will vary considerably from one developer to another. If the whole interface can be implemented relatively simply in one Mock - why not do it. My changes to the JDBC classes implement as much of the interface as the originals (in some cases more, and follows the specification better in a couple of places), and I don't think they're really any more complicated than the originals (In fact I believe I've cleaned the hierachy of common and JDK specific objects up - making it more consistant with the other JDBC objects). > We need to find ways for people to do everything they need to, but that > doesn't mean that we need a single mock implementation for all possible > tests. I think in a lot of cases, particularly the more generic interfaces, that is going to be orders of magnitude easier to say than do. > Increasingly, I find myself creating a null implementation of an > interface and then overriding the methods I need for a particular test > in an anonymous class. That's a nice idea, but I can only see that working for domain specific objects. Testers can't be expected to roll their own ResultSet object for example. > One of the essential points about testing with > mocks is that the mocks must be simple enough that the failures will > always be in the target code and that this should be obvious. Our mock > implementations are now getting to the point where they need tests > themselves and that bothers me. But surely the MockObjects need to be providing a conformant interface for what they are trying to mock, and testing that expectation of that interface given a specifc set of mock data can't be a completely bad thing. eg. testing that all the variation methods for setting row data on a ResultSet actually results in the Mock behaving the same. Some mocks are going to have to have some logic to determine what to return when, and it can't be a bad idea to test that. > Easy now, in a moment one of us will use the N?zi word and the game > will be over ;-) *8-) > > Also in certain cirumstances Verifier can be involved in mantaining > > the infinate loops and inherant stack overflow that occurs in these > > circumstances, is this the sort of image a project that should be > > capable of being used in the commerce commercial quality projects be > > projecting? > > Don't understand this. Sorry, thats one of those sentences I re-wrote about 4 times, and then obviously read what I thought was there... Basically: If the Verifier is allowed to cause or participate in the verification of an Object that causes a stack overflow then its going to look bad on the Verifier (whether it was core MockObjects objects that caused it, or test specific mocks). Simon., =2D-=20 =2D------------------------------------------------------------------------- Simon Levitt, Senior Development Engineer @ WorldPay plc, WorldPay Centre, The Science Park, Milton Rd., Cambridge, CB4 0WE, ENGLAND = =20 Sim...@uk... Ph:+44(0)1223 715151 F:+44(0)1223 715157 =2D------------------------ http://www.worldpay.com/ ----------------------- |
From: Griffin C. <gri...@ho...> - 2002-10-07 00:52:34
|
Ah, very cool.. Hadn't noticed the nat module in the java implementation, yet. Yes, more .NET Mock Objects are coming. System.Data is up first... As for rolling in NMock stuff, I am thinking that would be a good thing as opposed to keeping it in the java implementation. .NET developers might not know it is there. Steve, Tim, or Philip, want to chime in as how to structure/organize these kinds of things? -Griffin >From: Joe Walnes <jo...@tr...> >To: "Griffin Caprio" <gri...@ho...>, >moc...@li... >Subject: Re: [MO-java-dev] .NET Mock Objects? >Date: Mon, 07 Oct 2002 01:48:22 +0100 > >Griffin, NMock takes a different approach to DotNetMock. > >Both libraries are pretty much direct ports of existing libraries; >DotNetMock comes from the main Java MockObjects library, whereas NMock >comes from JMock and PythonMock that Nat Pryce wrote (in the nat module). > >NMock uses dynamic bytecode generation to create mocks at runtime which are >configured by the unit-tests. > >The DotNetMock library is better suited for hand-rolled mocks as it is very >flexible and customizable whereas NMock is for when you need something >quick'n'dirty. I'd imagine the DotNetMock project to also supply a set of >existing mock implementations for common .NET libraries. > >I think a lot can be gained from combining our efforts to get the best of >both worlds (the dynamic stuff and predicate library from NMock with the >expectation library from DotNetMock). > >Cheers, >-joe > >Joe Walnes, ThoughtWorks > >At 18:57 06/10/2002 -0500, Griffin Caprio wrote: >>I see that there is a NMock project in the mockobject-java source tree. >>Darren Hobbs and I are already working on a .NET Mock Objects project on >>sourceforge (http://www.sourceforge.net/projects/dotnetmock). We already >>have the core framework implemented. Our first release will be this week, >>once we polish the build and documentation process. After that we are >>hoping for community input as to what to implement next. >> >>Is NMock an exact replication of the java mock objects? >> >>If so, can I suggest that we combine our efforts, so as not to create >>competing .NET Mock Object Implementations? Griffin Caprio cell: (773) 230-0936 _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx |
From: Joe W. <jo...@tr...> - 2002-10-07 00:47:57
|
Griffin, NMock takes a different approach to DotNetMock. Both libraries are pretty much direct ports of existing libraries; DotNetMock comes from the main Java MockObjects library, whereas NMock comes from JMock and PythonMock that Nat Pryce wrote (in the nat module). NMock uses dynamic bytecode generation to create mocks at runtime which are configured by the unit-tests. The DotNetMock library is better suited for hand-rolled mocks as it is very flexible and customizable whereas NMock is for when you need something quick'n'dirty. I'd imagine the DotNetMock project to also supply a set of existing mock implementations for common .NET libraries. I think a lot can be gained from combining our efforts to get the best of both worlds (the dynamic stuff and predicate library from NMock with the expectation library from DotNetMock). Cheers, -joe Joe Walnes, ThoughtWorks At 18:57 06/10/2002 -0500, Griffin Caprio wrote: >I see that there is a NMock project in the mockobject-java source tree. >Darren Hobbs and I are already working on a .NET Mock Objects project on >sourceforge (http://www.sourceforge.net/projects/dotnetmock). We already >have the core framework implemented. Our first release will be this week, >once we polish the build and documentation process. After that we are >hoping for community input as to what to implement next. > >Is NMock an exact replication of the java mock objects? > >If so, can I suggest that we combine our efforts, so as not to create >competing .NET Mock Object Implementations? |
From: Joe W. <joe...@us...> - 2002-10-07 00:22:37
|
Update of /cvsroot/mockobjects/nmock/sample/random In directory usw-pr-cvs1:/tmp/cvs-serv2126/sample/random Modified Files: Weather.cs WeatherTest.cs Log Message: Added test for DefaultWeatherRandom Index: Weather.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/sample/random/Weather.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- Weather.cs 6 Oct 2002 23:14:27 -0000 1.2 +++ Weather.cs 7 Oct 2002 00:22:35 -0000 1.3 @@ -39,9 +39,9 @@ public class DefaultWeatherRandom : WeatherRandom { - private const double CHANCE_OF_RAIN = 0.2; - private const double MIN_TEMPERATURE = 20; - private const double MAX_TEMPERATURE = 30; + public const double CHANCE_OF_RAIN = 0.2; + public const double MIN_TEMPERATURE = 20; + public const double MAX_TEMPERATURE = 30; private const double TEMPERATURE_RANGE = (MAX_TEMPERATURE-MIN_TEMPERATURE); Index: WeatherTest.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/sample/random/WeatherTest.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- WeatherTest.cs 6 Oct 2002 23:14:27 -0000 1.2 +++ WeatherTest.cs 7 Oct 2002 00:22:35 -0000 1.3 @@ -21,8 +21,8 @@ [Test] public void RandomRaining() { - random.ExpectAndReturn("NextTemperature", 1.0); - random.ExpectAndReturn("NextIsRaining", true); + random.SetValue("NextTemperature", 1.0); + random.SetValue("NextIsRaining", true); weather.Randomize(); Assertion.Assert("is raining", weather.IsRaining); } @@ -30,8 +30,8 @@ [Test] public void RandomNotRaining() { - random.ExpectAndReturn("NextTemperature", 1.0); - random.ExpectAndReturn("NextIsRaining", false); + random.SetValue("NextTemperature", 1.0); + random.SetValue("NextIsRaining", false); weather.Randomize(); Assertion.Assert("is not raining", !weather.IsRaining); } @@ -40,8 +40,8 @@ public void RandomTemperatureSunny() { double TEMPERATURE = 20.0; - random.ExpectAndReturn("NextTemperature", TEMPERATURE); - random.ExpectAndReturn("NextIsRaining", false); + random.SetValue("NextTemperature", TEMPERATURE); + random.SetValue("NextIsRaining", false); weather.Randomize(); Assertion.AssertEquals("temperature", TEMPERATURE, weather.Temperature); } @@ -50,12 +50,58 @@ public void RandomTemperatureRaining() { double TEMPERATURE = 20.0; - random.ExpectAndReturn("NextTemperature", TEMPERATURE); - random.ExpectAndReturn("NextIsRaining", true); + random.SetValue("NextTemperature", TEMPERATURE); + random.SetValue("NextIsRaining", true); weather.Randomize(); Assertion.AssertEquals("temperature", TEMPERATURE / 2.0, weather.Temperature); } } + [TestFixture] + public class DefaultWeatherRandomTest + { + + [Test] + public void NextIsRaining() + { + IMock random = new DynamicMock(typeof(System.Random)); + WeatherRandom weather = new DefaultWeatherRandom((System.Random)random.Object); + + random.SetValue("NextDouble", 0.0); + Assertion.Assert("is raining", weather.NextIsRaining()); + + random.SetValue("NextDouble", DefaultWeatherRandom.CHANCE_OF_RAIN); + Assertion.Assert("is not raining", !weather.NextIsRaining()); + + random.SetValue("NextDouble", 1.0); + Assertion.Assert("is not raining", !weather.NextIsRaining()); + } + + [Test] + public void NextTemperature() + { + IMock random = new DynamicMock(typeof(System.Random)); + WeatherRandom weather = new DefaultWeatherRandom((System.Random)random.Object); + + random.SetValue("NextDouble", 0.0); + Assertion.AssertEquals("should be min temperature", + DefaultWeatherRandom.MIN_TEMPERATURE, + weather.NextTemperature() + ); + + random.SetValue("NextDouble", 0.5); + Assertion.AssertEquals("should be average temperature", + 0.5 * (DefaultWeatherRandom.MIN_TEMPERATURE + DefaultWeatherRandom.MAX_TEMPERATURE), + weather.NextTemperature() + ); + + random.SetValue("NextDouble", 1.0); + Assertion.AssertEquals("should be max temperature", + DefaultWeatherRandom.MAX_TEMPERATURE, + weather.NextTemperature() + ); + } + + } } |
From: Joe W. <joe...@us...> - 2002-10-07 00:08:06
|
Update of /cvsroot/mockobjects/nmock/test/NMock/Dynamic In directory usw-pr-cvs1:/tmp/cvs-serv28357/test/NMock/Dynamic Modified Files: ClassGeneratorTest.cs Log Message: ClassGenerator can now create dynamic mocks based on classes as well as interfaces (although it can only override virtual methods). Index: ClassGeneratorTest.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/test/NMock/Dynamic/ClassGeneratorTest.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- ClassGeneratorTest.cs 6 Oct 2002 23:11:39 -0000 1.2 +++ ClassGeneratorTest.cs 7 Oct 2002 00:08:02 -0000 1.3 @@ -27,6 +27,23 @@ string AProperty { get; set; } } + public abstract class SolidThingy + { + public virtual string VirtualMethod() { return "xx"; } + public override string ToString() { return "xx"; } + public abstract string AbstractMethod(); + + // cannot override + public static string StaticMethod() { return "xx"; } + public string NonVirtualMethod() { return "xx"; } + private string privateMethod() { return "xx"; } + internal string internalMethod() { return "xx"; } + protected virtual string protectedMethod() { return "xx"; } + protected internal virtual string protectedInternalMethod() { return "xx"; } + string defaultInternalMethod() { return "xx"; } + + } + [TestFixture] public class ClassGeneratorTest { @@ -201,6 +218,25 @@ mock.Verify(); } + [Test] + public void ExtendClass() + { + cg = new ClassGenerator(); + SolidThingy s = (SolidThingy)cg.Generate(typeof(SolidThingy), mock); + + mock.ExpectAndReturn("VirtualMethod", "hello"); + mock.ExpectAndReturn("ToString", "STRING"); + mock.ExpectAndReturn("GetHashCode", 123); + mock.ExpectAndReturn("AbstractMethod", "fish"); + Assertion.AssertEquals("hello", s.VirtualMethod()); + Assertion.AssertEquals("STRING", s.ToString()); + Assertion.AssertEquals(123, s.GetHashCode()); + Assertion.AssertEquals("fish", s.AbstractMethod()); + + Assertion.AssertEquals("xx", s.NonVirtualMethod()); + mock.Verify(); + } + [Test] public void BoxingOpCodes() { |
From: Joe W. <joe...@us...> - 2002-10-07 00:08:05
|
Update of /cvsroot/mockobjects/nmock/src/NMock/Dynamic In directory usw-pr-cvs1:/tmp/cvs-serv28357/src/NMock/Dynamic Modified Files: ClassGenerator.cs Log Message: ClassGenerator can now create dynamic mocks based on classes as well as interfaces (although it can only override virtual methods). Index: ClassGenerator.cs =================================================================== RCS file: /cvsroot/mockobjects/nmock/src/NMock/Dynamic/ClassGenerator.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -u -r1.2 -r1.3 --- ClassGenerator.cs 6 Oct 2002 23:11:39 -0000 1.2 +++ ClassGenerator.cs 7 Oct 2002 00:08:02 -0000 1.3 @@ -10,47 +10,45 @@ { private static IDictionary boxingOpCodes; - public class GeneratedBase - { - private IMock underlyingMock; - - public IMock UnderlyingMock - { - set { underlyingMock = value; } - } - - protected object CallMock(string name, params object[] args) - { - return underlyingMock.Call(name, args); - } - } - public object Generate(Type type, IMock mock) { TypeBuilder typeBuilder = getTypeBuilder("Mock" + type.Name, type); + FieldBuilder mockFieldBuilder = typeBuilder.DefineField("underlyingMock", typeof(IMock), FieldAttributes.Public); MethodInfo[] methods = type.GetMethods(); foreach ( MethodInfo m in methods ) { - implementMethod(type, typeBuilder, m); + implementMethod(type, typeBuilder, m, mockFieldBuilder); } Type proxyType = typeBuilder.CreateType(); - GeneratedBase result = (GeneratedBase)Activator.CreateInstance(proxyType); - result.UnderlyingMock = mock; + object result = Activator.CreateInstance(proxyType); + FieldInfo underlyingMock = proxyType.GetField("underlyingMock"); + underlyingMock.SetValue(result, mock); return result; } - private TypeBuilder getTypeBuilder(string name, Type implementsInterface) + private TypeBuilder getTypeBuilder(string name, Type originalType) { AppDomain appDomain = AppDomain.CurrentDomain; AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "DynamicMockAssembly"; AssemblyBuilder assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MockModule"); - return moduleBuilder.DefineType(name, TypeAttributes.Public, typeof(GeneratedBase), - new Type[]{implementsInterface}); + Type superClass; + Type[] interfaces; + if (originalType.IsInterface) + { + superClass = null; + interfaces = new Type[] {originalType}; + } + else + { + superClass = originalType; + interfaces = new Type[0]; + } + return moduleBuilder.DefineType(name, TypeAttributes.Public, superClass, interfaces); } - private void implementMethod(Type type, TypeBuilder typeBuilder, MethodInfo m) + private void implementMethod(Type type, TypeBuilder typeBuilder, MethodInfo m, FieldBuilder mockFieldBuilder) { Type returnType = m.ReturnType; ArrayList types = new ArrayList(); @@ -60,7 +58,6 @@ } Type[] paramTypes = (Type[])types.ToArray(typeof(Type)); MethodBuilder methodBuilder = typeBuilder.DefineMethod(m.Name, MethodAttributes.Public | MethodAttributes.Virtual, returnType, paramTypes); - typeBuilder.DefineMethodOverride(methodBuilder, type.GetMethod(m.Name)); ILGenerator il = methodBuilder.GetILGenerator(); @@ -76,6 +73,7 @@ } il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldfld, mockFieldBuilder); il.Emit(OpCodes.Ldstr, methodName); il.Emit(OpCodes.Ldc_I4_S, paramTypes.Length); il.Emit(OpCodes.Newarr, typeof(object)); @@ -98,9 +96,8 @@ } } - MethodInfo call = typeof(GeneratedBase).GetMethod("CallMock", - BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); - il.EmitCall(OpCodes.Call, call, null); + MethodInfo call = typeof(IMock).GetMethod("Call"); + il.EmitCall(OpCodes.Callvirt, call, null); if (returnType == typeof(void)) { |