diff --git a/Spring.build b/Spring.build index ec89656dd..7d10157cb 100644 --- a/Spring.build +++ b/Spring.build @@ -573,255 +573,24 @@ Commandline Examples: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + diff --git a/lib/Mono/2.0/DotNetMock.Framework.dll b/lib/Mono/2.0/DotNetMock.Framework.dll deleted file mode 100644 index b91f079ff..000000000 Binary files a/lib/Mono/2.0/DotNetMock.Framework.dll and /dev/null differ diff --git a/lib/Mono/2.0/DotNetMock.dll b/lib/Mono/2.0/DotNetMock.dll deleted file mode 100644 index 794065d35..000000000 Binary files a/lib/Mono/2.0/DotNetMock.dll and /dev/null differ diff --git a/lib/Mono/2.0/Rhino.Mocks.dll b/lib/Mono/2.0/Rhino.Mocks.dll deleted file mode 100644 index 3fc4b2ae4..000000000 Binary files a/lib/Mono/2.0/Rhino.Mocks.dll and /dev/null differ diff --git a/lib/Mono/2.0/Rhino.Mocks.xml b/lib/Mono/2.0/Rhino.Mocks.xml deleted file mode 100644 index d6ae366d2..000000000 --- a/lib/Mono/2.0/Rhino.Mocks.xml +++ /dev/null @@ -1,5624 +0,0 @@ - - - - Rhino.Mocks - - - - - Defines constraints and return values for arguments of a mock. - Only use Arg inside a method call on a mock that is recording. - Example: - ExpectCall( - mock.foo( - Arg<int>.Is.GreaterThan(2), - Arg<string>.Is.Anything - )); - Use Arg.Text for string specific constraints - Use Arg<ListClass>.List for list specific constraints - - - - - - Register the predicate as a constraint for the current call. - - The predicate. - default(T) - - Allow you to use code to create constraints - - demo.AssertWasCalled(x => x.Bar(Arg{string}.Matches(a => a.StartsWith("b") && a.Contains("ba")))); - - - - - - Define a complex constraint for this argument by passing several constraints - combined with operators. (Use Is in simple cases.) - Example: Arg<string>.Matches(Is.Equal("Hello") || Text.EndsWith("u")); - - Constraints using Is, Text and List - Dummy to satisfy the compiler - - - - Define a Ref argument. - - Constraints for this argument - value returned by the mock - - - - - Define a out parameter. Use it together with the keyword out and use the - Dummy field available by the return value. - Example: mock.foo( out Arg<string>.Out("hello").Dummy ); - - - - - - - Define a simple constraint for this argument. (Use Matches in simple cases.) - Example: - Arg<int>.Is.Anthing - Arg<string>.Is.Equal("hello") - - - - - Define Constraints on list arguments. - - - - - Use the Arg class (without generic) to define Text constraints - - - - - Evaluate an equal constraint for . - - The object the parameter should equal to - - - - Define constraints on text arguments. - - - - - Used to manage the static state of the Arg<T> class"/> - - - - - Resets the static state - - - - - Returns return values for the out and ref parameters - Note: the array returned has the size of the number of out and ref - argument definitions - - - - - - Returns the constraints for all arguments. - Out arguments have an Is.Anything constraint and are also in the list. - - - - - - What should BackToRecord clear - - - - - Retain all expectations and behaviors and return to mock - - - - - All expectations - - - - - Event subscribers for this instance - - - - - Methods that should be forwarded to the base class implementation - - - - - Properties that should behave like properties - - - - - Remove all the behavior of the object - - - - - Interface for constraints - - - - - Determines if the object pass the constraints - - - - - And operator for constraints - - - - - Not operator for constraints - - - - - Or operator for constraints - - - - - Allow overriding of || or && - - - - - - - Allow overriding of || or && - - - - - - - Gets the message for this constraint - - - - - - Constrain that the public field has a specified value - - - - - Constrain that the public field matches another constraint. - - - - - Creates a new instance. - - Name of the public field. - Constraint to place on the public field value. - - - - Creates a new instance, specifying a disambiguating - for the public field. - - The type that declares the public field, used to disambiguate between public fields. - Name of the public field. - Constraint to place on the public field value. - - - - Determines if the object passes the constraint. - - - - - Gets the message for this constraint - - - - - - Creates a new instance. - - Name of the public field. - Expected value. - - - - Creates a new instance, specifying a disambiguating - for the public field. - - The type that declares the public field, used to disambiguate between public fields. - Name of the public field. - Expected value. - - - - Constrain that the property has a specified value - - - - - Constrain that the property matches another constraint. - - - - - Creates a new instance. - - Name of the property. - Constraint to place on the property value. - - - - Creates a new instance, specifying a disambiguating - for the property. - - The type that declares the property, used to disambiguate between properties. - Name of the property. - Constraint to place on the property value. - - - - Determines if the object passes the constraint. - - - - - Gets the message for this constraint - - - - - - Creates a new instance. - - Name of the property. - Expected value. - - - - Creates a new instance, specifying a disambiguating - for the property. - - The type that declares the property, used to disambiguate between properties. - Name of the property. - Expected value. - - - - Constrain that the parameter must be of the specified type - - - - - Creates a new instance. - - Type. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that determines whether an object is the same object as another. - - - - - Creates a new instance. - - Obj. - - - - Determines if the object passes the constraints. - - - - - Gets the message for this constraint. - - - - - Evaluate a parameter using constraints - - - - - Create new instance - - - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - A constraint based on lambda expression, we are using Expression{T} - because we want to be able to get good error reporting on that. - - - - - Initializes a new instance of the class. - - The expr. - - - - Determines if the object pass the constraints - - - - - - - Gets the message for this constraint - - - - - - Constrain that the list contains the same items as the parameter list - - - - - Creates a new instance. - - In list. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constrain that the parameter is one of the items in the list - - - - - Creates a new instance. - - In list. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constrain that the object is inside the parameter list - - - - - Creates a new instance. - - In list. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Applies another AbstractConstraint to the collection count. - - - - - Creates a new instance. - - The constraint that should be applied to the collection count. - - - - Determines if the parameter conforms to this constraint. - - - - - Gets the message for this constraint. - - - - - Applies another AbstractConstraint to a specific list element. - - - - - Creates a new instance. - - The zero-based index of the list element. - The constraint that should be applied to the list element. - - - - Determines if the parameter conforms to this constraint. - - - - - Gets the message for this constraint - - - - - - Applies another AbstractConstraint to a specific generic keyed list element. - - - - - Creates a new instance. - - The key of the list element. - The constraint that should be applied to the list element. - - - - Determines if the parameter conforms to this constraint. - - - - - Gets the message for this constraint - - - - - - Constrains that all elements are in the parameter list - - - - - Initializes a new instance of the class. - - The these. - - - - Determines if the object pass the constraints - - - - - - - Gets the message for this constraint - - - - - - Combines two constraints, constraint pass if either is fine. - - - - - Creates a new instance. - - C1. - C2. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Negate a constraint - - - - - Creates a new instance. - - C1. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Combines two constraints - - - - - - Creates a new instance. - - C1. - C2. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constrain the argument to validate according to regex pattern - - - - - Creates a new instance. - - Pattern. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that evaluate whatever an argument contains the specified string. - - - - - Creates a new instance. - - Inner string. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that evaluate whatever an argument ends with the specified string - - - - - Creates a new instance. - - End. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that evaluate whatever an argument start with the specified string - - - - - Creates a new instance. - - Start. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that evaluate whatever an object equals another - - - - - Creates a new instance. - - Obj. - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that always returns true - - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Constraint that evaluate whatever a comparable is greater than another - - - - - Creates a new instance. - - - - - Determines if the object pass the constraints - - - - - Gets the message for this constraint - - - - - - Initializes a new constraint object. - - The expected object, The actual object is passed in as a parameter to the method - - - - Evaluate this constraint. - - The actual object that was passed in the method call to the mock. - True when the constraint is met, else false. - - - - Checks if the properties of the object - are the same as the properies of the object. - - The expected object - The actual object - True when both objects have the same values, else False. - - - - - - - - - This is the real heart of the beast. - - - - Used by CheckReferenceType to check all properties of the reference type. - - The expected object - The actual object - True when both objects have the same values, else False. - - - - Used by CheckReferenceType to check all fields of the reference type. - - The expected object - The actual object - True when both objects have the same values, else False. - - - - Checks the items of both collections - - The expected collection - - True if both collections contain the same items in the same order. - - - - Builds a propertyname from the Stack _properties like 'Order.Product.Price' - to be used in the error message. - - A nested property name. - - - - Rhino.Mocks uses this property to generate an error message. - - - A message telling the tester why the constraint failed. - - - - - Provides access to the constraintes defined in the class to be used in context - with the syntax. - - The type of the argument - - - - Evaluate a greater than constraint for . - - The object the parameter should be greater than - - - - Evaluate a less than constraint for . - - The object the parameter should be less than - - - - Evaluate a less than or equal constraint for . - - The object the parameter should be less than or equal to - - - - Evaluate a greater than or equal constraint for . - - The object the parameter should be greater than or equal to - - - - Evaluate an equal constraint for . - - The object the parameter should equal to - - - - Converts the object type to a better match if this is a primitive type. - - The obj. - - - - - Converts the object type to match. - - - Because of implicit conversions and the way ArgConstraints this method is needed to check - object type and potentially change the object type for a better "match" so that obj1.Equals(obj2) - will return the proper "answer" - - The obj. - - - - - Evaluate a not equal constraint for . - - The object the parameter should not equal to - - - - Evaluate a same as constraint. - - The object the parameter should the same as. - - - - Evaluate a not same as constraint. - - The object the parameter should not be the same as. - - - - Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. - - - - - - - Serves as a hash function for a particular type. - - - A hash code for the current . - - - - - A constraints that accept anything - - - - - - A constraint that accept only nulls - - - - - - A constraint that accept only non null values - - - - - - A constraint that accept only value of the specified type. - The check is performed on the type that has been defined - as the argument type. - - - - - Provides access to the constraints defined in the class to be used in context - with the syntax. - - - - - Determines whether the specified object is in the parameter. - The parameter must be IEnumerable. - - Obj. - - - - - Determines whatever the parameter is in the collection. - - - - - Determines that the parameter collection is identical to the specified collection - - - - - Determines that the parameter collection has the specified number of elements. - - The constraint that should be applied to the collection count. - - - - Determines that an element of the parameter collections conforms to another AbstractConstraint. - - The zero-based index of the list element. - The constraint which should be applied to the list element. - - - - Determines that all elements of the specified collection are in the the parameter collection - - The collection to compare against - The constraint which should be applied to the list parameter. - - - - Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. - - - - - - - Serves as a hash function for a particular type. - - - A hash code for the current . - - - - - Provides a dummy field to pass as out or ref argument. - - - - - - Dummy field to satisfy the compiler. Used for out and ref arguments. - - - - - Central location for constraints for object's public fields - - - - - Constrains the parameter to have a public field with the specified value - - Name of the public field. - Expected value. - - - - - Constrains the parameter to have a public field with the specified value. - - The type that declares the public field, used to disambiguate between public fields. - Name of the public field. - Expected value. - - - - - Constrains the parameter to have a public field satisfying a specified constraint. - - Name of the public field. - Constraint for the public field. - - - - Constrains the parameter to have a public field satisfying a specified constraint. - - The type that declares the public field, used to disambiguate between public fields. - Name of the public field. - Constraint for the public field. - - - - Determines whether the parameter has the specified public field and that it is null. - - Name of the public field. - - - - - Determines whether the parameter has the specified public field and that it is null. - - The type that declares the public field, used to disambiguate between public fields. - Name of the public field. - - - - - Determines whether the parameter has the specified public field and that it is not null. - - Name of the public field. - - - - - Determines whether the parameter has the specified public field and that it is not null. - - The type that declares the public field, used to disambiguate between public fields. - Name of the public field. - - - - - Central location for constraints - - - - - Evaluate a greater than constraint for . - - The object the parameter should be greater than - - - - Evaluate a less than constraint for . - - The object the parameter should be less than - - - - Evaluate a less than or equal constraint for . - - The object the parameter should be less than or equal to - - - - Evaluate a greater than or equal constraint for . - - The object the parameter should be greater than or equal to - - - - Evaluate an equal constraint for . - - The object the parameter should equal to - - - - Evaluate a not equal constraint for . - - The object the parameter should not equal to - - - - Evaluate a same as constraint. - - The object the parameter should the same as. - - - - Evaluate a not same as constraint. - - The object the parameter should not be the same as. - - - - A constraints that accept anything - - - - - - A constraint that accept only nulls - - - - - - A constraint that accept only non null values - - - - - - A constraint that accept only value of the specified type - - - - - A constraint that accept only value of the specified type - - - - - Evaluate a parameter using a predicate - - The predicate to use - - - - Central location for constraints about lists and collections - - - - - Determines whether the specified obj is in the parameter. - The parameter must be IEnumerable. - - Obj. - - - - - Determines whatever the parameter is in the collection. - - - - - Determines that the parameter collection is identical to the specified collection - - - - - Determines that the parameter collection has the specified number of elements. - - The constraint that should be applied to the collection count. - - - - Determines that an element of the parameter collections conforms to another AbstractConstraint. - - The zero-based index of the list element. - The constraint which should be applied to the list element. - - - - Determines that an element of the parameter collections conforms to another AbstractConstraint. - - The key of the element. - The constraint which should be applied to the element. - - - - Determines that all elements of the specified collection are in the the parameter collection - - The collection to compare against - The constraint which should be applied to the list parameter. - - - - Central location for constraints for object's properties - - - - - Constrains the parameter to have property with the specified value - - Name of the property. - Expected value. - - - - - Constrains the parameter to have property with the specified value. - - The type that declares the property, used to disambiguate between properties. - Name of the property. - Expected value. - - - - - Constrains the parameter to have a property satisfying a specified constraint. - - Name of the property. - Constraint for the property. - - - - Constrains the parameter to have a property satisfying a specified constraint. - - The type that declares the property, used to disambiguate between properties. - Name of the property. - Constraint for the property. - - - - Determines whether the parameter has the specified property and that it is null. - - Name of the property. - - - - - Determines whether the parameter has the specified property and that it is null. - - The type that declares the property, used to disambiguate between properties. - Name of the property. - - - - - Determines whether the parameter has the specified property and that it is not null. - - Name of the property. - - - - - Determines whether the parameter has the specified property and that it is not null. - - The type that declares the property, used to disambiguate between properties. - Name of the property. - - - - - constraints the parameter to have the exact same property values as the expected object. - - An object, of the same type as the parameter, whose properties are set with the expected values. - An instance of the constraint that will do the actual check. - - The parameter's public property values and public field values will be matched against the expected object's - public property values and public field values. The first mismatch will be reported and no further matching is done. - The matching is recursive for any property or field that has properties or fields of it's own. - Collections are supported through IEnumerable, which means the constraint will check if the actual and expected - collection contain the same values in the same order, where the values contained by the collection can have properties - and fields of their own that will be checked as well because of the recursive nature of this constraint. - - - - - Central location for all text related constraints - - - - - Constrain the argument to starts with the specified string - - - - - Constrain the argument to end with the specified string - - - - - Constrain the argument to contain the specified string - - - - - Constrain the argument to validate according to regex pattern - - - - - Provides access to the constraintes defined in the class to be used in context - with the syntax. - - - - - Constrain the argument to starts with the specified string - - - - - - Constrain the argument to end with the specified string - - - - - Constrain the argument to contain the specified string - - - - - Constrain the argument to validate according to regex pattern - - - - - Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. - - - - - - - Serves as a hash function for a particular type. - - - A hash code for the current . - - - - - This class defines a lot of method signatures, which we will use - to allow compatability on net-2.0 - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - dummy - - - - - Allows expectations to be set on methods that should never be called. - For methods with void return value, you need to use LastCall or - DoNotExpect.Call() with a delegate. - - - - - Sets LastCall.Repeat.Never() on /any/ proxy on /any/ repository on the current thread. - This method if not safe for multi threading scenarios. - - - - - Accepts a delegate that will execute inside the method which - LastCall.Repeat.Never() will be applied to. - It is expected to be used with anonymous delegates / lambda expressions and only one - method should be called. - - - IService mockSrv = mocks.CreateMock(typeof(IService)) as IService; - DoNotExpect.Call(delegate{ mockSrv.Stop(); }); - ... - - - - - An expectaton violation was detected. - - - - - Creates a new instance. - - Message. - - - - Serialization constructor - - - - - Signals that an object was call on a mock repository which doesn't - belong to this mock repository or not a mock - - - - - Creates a new instance. - - Message. - - - - Serialization constructor - - - - - Allows to set expectation on methods that has return values. - For methods with void return value, you need to use LastCall - - - - - The method options for the last call on /any/ proxy on /any/ repository on the current thread. - This method if not safe for multi threading scenarios, use . - - - - - Accepts a delegate that will execute inside the method, and then return the resulting - instance. - It is expected to be used with anonymous delegates / lambda expressions and only one - method should be called. - - - IService mockSrv = mocks.CreateMock(typeof(IService)) as IService; - Expect.Call(delegate{ mockSrv.Start(); }).Throw(new NetworkException()); - ... - - - - - Get the method options for the last method call on the mockInstance. - - - - - A delegate that can be used to get better syntax on Expect.Call(delegate { foo.DoSomething(); }); - - - - - Abstract class that holds common information for - expectations. - - - - - Interface to validate that a method call is correct. - - - - - Validate the arguments for the method. - This method can be called numerous times, so be careful about side effects - - The arguments with which the method was called - - - - Add an actual method call to this expectation - - - - - Returns the return value or throw the exception and setup any output / ref parameters - that has been set. - - - - - Builds the verification failure message. - - - - - - Gets the error message. - - - - - - Range of expected calls - - - - - Number of call actually made for this method - - - - - If this expectation is still waiting for calls. - - - - - The return value for a method matching this expectation - - - - - Gets or sets the exception to throw on a method matching this expectation. - - - - - Gets a value indicating whether this instance's action is staisfied. - A staisfied instance means that there are no more requirements from - this method. A method with non void return value must register either - a return value or an exception to throw. - - - - - Gets the method this expectation is for. - - - - - Gets or sets what special condtions there are for this method - repeating. - - - - - Gets a value indicating whether this expectation was satisfied - - - - - Specify whatever this expectation has a return value set - You can't check ReturnValue for this because a valid return value include null. - - - - - An action to execute when the method is matched. - - - - - Set the out / ref parameters for the method call. - The indexing is zero based and ignores any non out/ref parameter. - It is possible not to pass all the parameters. This method can be called only once. - - - - - Documentation Message - - - - - Gets the invocation for this expectation - - The invocation. - - - - Occurs when the exceptation is match on a method call - - - - - Allow to set the return value in the future, if it was already set. - - - - - Number of actuall calls made that passed this expectation - - - - - Range of expected calls that should pass this expectation. - - - - - The return value for a method matching this expectation - - - - - The exception to throw on a method matching this expectation. - - - - - The method this expectation is for. - - - - - The return value for this method was set - - - - - Whether this method will repeat - unlimited number of times. - - - - - A delegate that will be run when the - expectation is matched. - - - - - The arguments that matched this expectation. - - - - - Documentation message - - - - - The method originalInvocation - - - - - Get the hash code - - - - - Add an actual actualMethodCall call to this expectation - - - - - Builds the verification failure message. - - - - - - Returns the return value or throw the exception and setup output / ref parameters - - - - - Validate the arguments for the method on the child methods - - The arguments with which the method was called - - - - Creates a new instance. - - The originalInvocation for this method, required because it contains the generic type infromation - Number of method calls for this expectations - - - - Creates a new instance. - - Expectation. - - - - Validate the arguments for the method on the child methods - - The arguments with which the method was called - - - - Determines if this object equal to obj - - - - - The error message for these arguments - - - - - Asserts that the delegate has the same parameters as the expectation's method call - - - - - Setter for the outpur / ref parameters for this expecataion. - Can only be set once. - - - - - Specify whether this expectation has a return value set - You can't check ReturnValue for this because a valid return value include null. - - - - - Gets the method this expectation is for. - - - - - Gets the originalInvocation for this expectation - - The originalInvocation. - - - - Gets or sets what special condtions there are for this method - - - - - Range of expected calls - - - - - Number of call actually made for this method - - - - - If this expectation is still waiting for calls. - - - - - Gets a value indicating whether this expectation was satisfied - - - - - The return value for a method matching this expectation - - - - - An action to execute when the method is matched. - - - - - Gets or sets the exception to throw on a method matching this expectation. - - - - - Gets a value indicating whether this instance's action is staisfied. - A staisfied instance means that there are no more requirements from - this method. A method with non void return value must register either - a return value or an exception to throw or an action to execute. - - - - - Documentation message - - - - - Occurs when the exceptation is match on a method call - - - - - Allow to set the return value in the future, if it was already set. - - - - - Gets the error message. - - - - - - Expectation that matches any arguments for the method. - - - - - Creates a new instance. - - Invocation for this expectation - Number of method calls for this expectations - - - - Creates a new instance. - - Expectation. - - - - Validate the arguments for the method. - - The arguments with which the method was called - - - - Determines if the object equal to expectation - - - - - Get the hash code - - - - - Gets the error message. - - - - - - Summary description for ArgsEqualExpectation. - - - - - Creates a new instance. - - Expected args. - The invocation for this expectation - Number of method calls for this expectations - - - - Validate the arguments for the method. - - The arguments with which the method was called - - - - Determines if the object equal to expectation - - - - - Get the hash code - - - - - Gets the error message. - - - - - - Get the expected args. - - - - - Call a specified callback to verify the expectation - - - - - Creates a new instance. - - Expectation. - Callback. - - - - Creates a new instance. - - Invocation for this expectation - Callback. - Number of method calls for this expectations - - - - Validate the arguments for the method on the child methods - - The arguments with which the method was called - - - - Determines if the object equal to expectation - - - - - Get the hash code - - - - - Gets the error message. - - - - - - Expect the method's arguments to match the contraints - - - - - Creates a new instance. - - Invocation for this expectation - Constraints. - Number of method calls for this expectations - - - - Creates a new instance. - - Expectation. - Constraints. - - - - Validate the arguments for the method. - - The arguments with which the method was called - - - - Determines if the object equal to expectation - - - - - Get the hash code - - - - - Gets the error message. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Summary for AndSpecification - - - - - - - - - - - - - - - - - - - - - - Summary description for FollowsEventNamingStandard - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Summary descritpion for NamedEventExistsOnDeclaringType - - - - - - - - - Doesn't log anything, just makes happy noises - - - - - Log expectations - allows to see what is going on inside Rhino Mocks - - - - - Logs the expectation as is was recorded - - The invocation. - The expectation. - - - - Logs the expectation as it was recorded - - The invocation. - The expectation. - - - - Logs the unexpected method call. - - The invocation. - The message. - - - - Logs the expectation as is was recorded - - The invocation. - The expectation. - - - - Logs the expectation as it was recorded - - The invocation. - The expectation. - - - - Logs the unexpected method call. - - The invocation. - The message. - - - - Operation on a remoting proxy - - - It is not possible to directly communicate to a real proxy via transparent proxy. - Transparent proxy impersonates a user type and only methods of that user type are callable. - The only methods that are guaranteed to exist on any transparent proxy are methods defined - in Object: namely ToString(), GetHashCode(), and Equals()). - - These three methods are the only way to tell the real proxy to do something. - Equals() is the most suitable of all, since it accepts an arbitrary object parameter. - The RemotingProxy code is built so that if it is compared to an IRemotingProxyOperation, - transparentProxy.Equals(operation) will call operation.Process(realProxy). - This way we can retrieve a real proxy from transparent proxy and perform - arbitrary operation on it. - - - - - Generates remoting proxies and provides utility functions - - - - - Create the proxy using remoting - - - - - Check whether an object is a transparent proxy with a RemotingProxy behind it - - Object to check - true if the object is a transparent proxy with a RemotingProxy instance behind it, false otherwise - We use Equals() method to communicate with the real proxy behind the object. - See IRemotingProxyOperation for more details - - - - Retrieve a mocked object from a transparent proxy - - Transparent proxy with a RemotingProxy instance behind it - Mocked object associated with the proxy - We use Equals() method to communicate with the real proxy behind the object. - See IRemotingProxyOperation for more details - - - - Implementation of IInvocation based on remoting proxy - - Some methods are marked NotSupported since they either don't make sense - for remoting proxies, or they are never called by Rhino Mocks - - - - Rudimetry implementation that simply logs methods calls as text. - - - - - Initializes a new instance of the class. - - The writer. - - - - Logs the expectation as it was recorded - - The invocation. - The expectation. - - - - Logs the expectation as it was recorded - - The invocation. - The expectation. - - - - Logs the unexpected method call. - - The invocation. - The message. - - - - Behave like a stub, all properties and events acts normally, methods calls - return default values by default (but can use expectations to set them up), etc. - - - - - Records all the expectations for a mock - - - - - Different actions on this mock - - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Verify that this mock expectations have passed. - - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Gets a mock state that match the original mock state of the object. - - - - - Get the options for the last method call - - - - - Set the exception to throw when Verify is called. - This is used to report exception that may have happened but where caught in the code. - This way, they are reported anyway when Verify() is called. - - - - - This method is called to indicate that a property behavior call. - This is done so we generate good error message in the common case of people using - Stubbed properties with Return(). - - - - - Gets the matching verify state for this state - - - - - Get the options for the last method call - - - - - Get the options for the last method call - - - - - Set the exception to throw when Verify is called. - This is used to report exception that may have happened but where caught in the code. - This way, they are reported anyway when Verify() is called. - - - - - This method is called to indicate that a property behavior call. - This is done so we generate good error message in the common case of people using - Stubbed properties with Return(). - - - - - Creates a new instance. - - Repository. - The proxy that generates the method calls - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Verify that this mock expectations have passed. - - - - - Gets a mock state that match the original mock state of the object. - - - - - Asserts the previous method is closed (had an expectation set on it so we can replay it correctly) - - - - - Get the default call count range expectation - - - - - - Gets the last expectation. - - - - - Gets the total method calls count. - - - - - Get the options for the last method call - - - - - Gets the matching verify state for this state - - - - - Initializes a new instance of the class. - - The proxy that generates the method calls - Repository. - - - - We don't care much about expectations here, so we will remove the expectation if - it is not closed. - - - - - Verify that we can move to replay state and move - to the reply state. - - - - - - Get the default call count range expectation - - - - - - Validate expectations on recorded methods, but in general completely ignoring them. - Similar to except that it would return a - when BackToRecord is called. - - - - - Validate all expectations on a mock - - - - - The repository for this state - - - - - The proxy object for this state - - - - - Get the options for the last method call - - - - - Creates a new instance. - - The previous state for this method - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Add a method call for this state' mock. - This allows derived method to cleanly get a the setupresult behavior while adding - their own. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Set the exception to throw when Verify is called. - This is used to report exception that may have happened but where caught in the code. - This way, they are reported anyway when Verify() is called. - - - - - not relevant - - - - - Verify that this mock expectations have passed. - - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Gets a mock state that match the original mock state of the object. - - - - - Get the options for the last method call - - - - - Gets the matching verify state for this state - - - - - Initializes a new instance of the class. - - The previous state for this method - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Gets a mock state that matches the original mock state of the object. - - - - - Write rhino mocks log info to the trace - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class. - - if set to true [log recorded]. - if set to true [log replayed]. - if set to true [log unexpected]. - - - - Logs the expectation as is was recorded - - The invocation. - The expectation. - - - - Logs the expectation as it was recorded - - The invocation. - The expectation. - - - - Logs the unexpected method call. - - The invocation. - The message. - - - - Writes log information as stack traces about rhino mocks activity - - - - - Allows to redirect output to a different location. - - - - - Logs the expectation as is was recorded - - The invocation. - The expectation. - - - - Logs the expectation as it was recorded - - The invocation. - The expectation. - - - - Logs the unexpected method call. - - The invocation. - The message. - - - - Marker interface used to indicate that this is a partial mock. - - - - - Options for CallOriginalMethod - - - - - No expectation is created, the method will be called directly - - - - - Normal expectation is created, but when the method is later called, it will also call the original method - - - - - This is a data structure that is used by - to pass - the current method to the relevant delegate - - - - - Initializes a new instance of the class. - - The invocation. - - - - Gets the args for this method invocation - - - - - Get the method that was caused this invocation - - - - - Gets or sets the return value for this method invocation - - The return value. - - - - Adds optional new usage: - using(mockRepository.Record()) { - Expect.Call(mock.Method()).Return(retVal); - } - using(mockRepository.Playback()) { - // Execute code - } - N.B. mockRepository.ReplayAll() and mockRepository.VerifyAll() - calls are taken care of by Record/Playback - - - Creates proxied instances of types. - - - - Generates a stub without needing a - Arguments for 's constructor - The of stub to create. - The stub - - - - Generates a stub without needing a - The of stub. - Arguments for the 's constructor. - The stub - - - - Generate a mock object without needing a - type of mock object to create. - Arguments for 's constructor - the mock object - - - - Generate a multi-mock object without needing a - The typeof object to generate a mock for. - A second interface to generate a multi-mock for. - Arguments for 's constructor - the multi-mock object - - - - Generate a multi-mock object without without needing a - The typeof object to generate a mock for. - An interface to generate a multi-mock for. - A second interface to generate a multi-mock for. - Arguments for 's constructor - the multi-mock object - - - - Creates a multi-mock without without needing a - The type of mock to create, this can be a class - Any extra interfaces to add to the multi-mock, these can only be interfaces. - Arguments for 's constructor - the multi-mock object - - - - Creates a strict mock without without needing a - Any arguments required for the 's constructor - The type of mock object to create. - The mock object with strict replay semantics - - - - Creates a strict multi-mock without needing a - Any arguments required for the 's constructor - The type of mock object to create, this can be a class. - An interface to generate a multi-mock for, this must be an interface! - The multi-mock object with strict replay semantics - - - - Creates a strict multi-mock without needing a - Any arguments required for the 's constructor - The type of mock object to create, this can be a class. - An interface to generate a multi-mock for, this must be an interface! - A second interface to generate a multi-mock for, this must be an interface! - The multi-mock object with strict replay semantics - - - - Creates a strict multi-mock without needing a - The type of mock object to create, this can be a class - Any extra interfaces to generate a multi-mock for, these must be interaces! - Any arguments for the 's constructor - The strict multi-mock object - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Generate a mock object with dynamic replay semantics and remoting without needing the mock repository - - - - - Generate a mock object with strict replay semantics and remoting without needing the mock repository - - - - Helper method to create a mock object without a repository instance and put the object back into replay mode. - The type of mock object to create - A delegate that uses a mock repository instance to create the underlying mock - The mock object in the replay mode. - - - - - - - - - - - - - - This is a map of types to ProxyGenerators. - - - - - This is used to record the last repository that has a method called on it. - - - - - this is used to get to the last proxy on this repository. - - - - - For mock delegates, maps the proxy instance from intercepted invocations - back to the delegate that was originally returned to client code, if any. - - - - - All the proxies in the mock repositories - - - - - This is here because we can't put it in any of the recorders, since repeatable methods - have no orderring, and if we try to handle them using the usual manner, we would get into - wierd situations where repeatable method that was defined in an orderring block doesn't - exists until we enter this block. - - - - - Creates a new instance. - - - - - Move the repository to ordered mode - - - - - Move the repository to un-ordered mode - - - - - Creates a mock for the specified type. - - Type. - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a strict mock for the specified type. - - Type. - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a remoting mock for the specified type. - - Type. - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a strict remoting mock for the specified type. - - Type. - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a remoting mock for the specified type. - - - Arguments for the class' constructor, if mocking a concrete class - - - - - Creates a strict remoting mock for the specified type. - - - Arguments for the class' constructor, if mocking a concrete class - - - - - Creates a mock from several types, with strict semantics. - Only may be a class. - - - - - Creates a strict mock from several types, with strict semantics. - Only may be a class. - - - - - Creates a mock from several types, with strict semantics. - Only may be a class. - - The main type to mock. - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class. - - - - Creates a strict mock from several types, with strict semantics. - Only may be a class. - - The main type to mock. - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class. - - - - Creates a mock from several types, with dynamic semantics. - Only may be a class. - - The main type to mock. - Extra interface types to mock. - - - - Creates a mock from several types, with dynamic semantics. - Only may be a class. - - The main type to mock. - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class. - - - Creates a dynamic mock for the specified type. - Type. - Arguments for the class' constructor, if mocking a concrete class - - - Creates a dynamic mock for the specified type. - Type. - Arguments for the class' constructor, if mocking a concrete class - - - Creates a dynamic mock for the specified type. - - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a mock object that defaults to calling the class methods if no expectation is set on the method. - Type. - Arguments for the class' constructor. - - - Creates a mock object that defaults to calling the class methods. - Type. - Extra interface types to mock. - - - Creates a mock object that defaults to calling the class methods. - Type. - Extra interface types to mock. - Arguments for the class' constructor. - - - Creates a mock object using remoting proxies - Type to mock - must be MarshalByRefObject - Mock object - Proxy mock can mock non-virtual methods, but not static methods - Creates the mock state for this proxy - - - - Cause the mock state to change to replay, any further call is compared to the - ones that were called in the record state. - - This method *cannot* be called from inside an ordering. - the object to move to replay state - - - - Cause the mock state to change to replay, any further call is compared to the - ones that were called in the record state. - - the object to move to replay state - - - - Move the mocked object back to record state.You can (and it's recommended) to run {Verify()} before you use this method. - Will delete all current expectations! - - - - Move the mocked object back to record state. - Optionally, can delete all current expectations, but allows more granularity about how - it would behave with regard to the object state. - - - - - Verify that all the expectations for this object were fulfilled. - - the object to verify the expectations for - - - - Get the method options for the last call on - mockedInstance. - - The mock object - Method options for the last call - - - - Maps an invocation proxy back to the mock object instance that was originally - returned to client code which might have been a delegate to this proxy. - - The mock object proxy from the intercepted invocation - The mock object - - - This is provided to allow advance extention functionality, where Rhino Mocks standard functionality is not enough. - The type to mock - Delegate that create the first state of the mocked object (usualy the record state). - Additional types to be implemented, this can be only interfaces - optional arguments for the constructor - - - - - Method: GetMockedObject - Get an IProxy from a mocked object instance, or throws if the - object is not a mock object. - - - - - Method: GetMockedObjectOrNull - Get an IProxy from a mocked object instance, or null if the - object is not a mock object. - - - - Pops the recorder. - - - Pushes the recorder. - New recorder. - - - - All the mock objects in this repository will be moved - to record state. - - - - - All the mock objects in this repository will be moved - to record state. - - - - - Replay all the mocks from this repository - - - - - Verify all the mocks from this repository - - - - - Gets the proxy generator for a specific type. Having a single ProxyGenerator - with multiple types linearly degrades the performance so this implementation - keeps one ProxyGenerator per type. - - - - Set the exception to be thrown when verified is called. - - - - Creates a mock for the spesified type with strict mocking semantics. - Strict semantics means that any call that wasn't explicitly recorded is considered an error and would cause an exception to be thrown. - - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a mock for the spesified type with strict mocking semantics. - Strict semantics means that any call that wasn't explicitly recorded is considered an error and would cause an exception to be thrown. - - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a dynamic mock for the specified type. - - Arguments for the class' constructor, if mocking a concrete class - - - - Creates a mock object from several types. - - - - - Creates a strict mock object from several types. - - - - - Create a mock object from several types with dynamic semantics. - - - - - Create a mock object from several types with partial semantics. - - - - - Create a mock object from several types with strict semantics. - - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class - - - - Create a strict mock object from several types with strict semantics. - - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class - - - - Create a mock object from several types with dynamic semantics. - - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class - - - - Create a mock object from several types with partial semantics. - - Extra interface types to mock. - Arguments for the class' constructor, if mocking a concrete class - - - - Create a mock object with from a class that defaults to calling the class methods - - Arguments for the class' constructor, if mocking a concrete class - - - - Create a stub object, one that has properties and events ready for use, and - can have methods called on it. It requires an explicit step in order to create - an expectation for a stub. - - The arguments for constructor. - - - - Create a stub object, one that has properties and events ready for use, and - can have methods called on it. It requires an explicit step in order to create - an expectation for a stub. - - The type. - The arguments for constructor. - The stub - - - - Returns true if the passed mock is currently in replay mode. - - The mock to test. - True if the mock is in replay mode, false otherwise. - - - - Determines whether the specified proxy is a stub. - - The proxy. - - - - Register a call on a prperty behavior - - - - - - Gets the recorder. - - - - - - Gets the replayer for this repository. - - - - - - Gets the last proxy which had a method call. - - - - - Delegate: CreateMockState - This is used internally to cleanly handle the creation of different - RecordMockStates. - - - - - A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks - - - - - Create an expectation on this mock for this action to occur - - - The mock. - The action. - - - - - Reset all expectations on this mock object - - - The mock. - - - - Reset the selected expectation on this mock object - - - The mock. - The options to reset the expectations on this mock. - - - - Cause the mock state to change to replay, any further call is compared to the - ones that were called in the record state. - - the mocked object to move to replay state - - - - Gets the mock repository for this specificied mock object - - - The mock. - - - - - Create an expectation on this mock for this action to occur - - - - The mock. - The action. - - - - - Tell the mock object to perform a certain action when a matching - method is called. - Does not create an expectation for this method. - - - The mock. - The action. - - - - - Tell the mock object to perform a certain action when a matching - method is called. - Does not create an expectation for this method. - - - - The mock. - The action. - - - - - Gets the arguments for calls made on this mock object and the method that was called - in the action. - - - The mock. - The action. - - - Here we will get all the arguments for all the calls made to DoSomething(int) - - var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0)) - - - - - - Gets the arguments for calls made on this mock object and the method that was called - in the action and matches the given constraints - - - The mock. - The action. - The setup constraints. - - - Here we will get all the arguments for all the calls made to DoSomething(int) - - var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0)) - - - - - - Asserts that a particular method was called on this mock object - - - The mock. - The action. - - - - Asserts that a particular method was called on this mock object that match - a particular constraint set. - - - The mock. - The action. - The setup constraints. - - - - Asserts that a particular method was called on this mock object that match - a particular constraint set. - - - The mock. - The action. - - - - Asserts that a particular method was called on this mock object that match - a particular constraint set. - - - The mock. - The action. - The setup constraints. - - - - Asserts that a particular method was NOT called on this mock object - - - The mock. - The action. - - - - Asserts that a particular method was NOT called on this mock object that match - a particular constraint set. - - - The mock. - The action. - The setup constraints. - - - - Asserts that a particular method was NOT called on this mock object - - - The mock. - The action. - - - - Asserts that a particular method was NOT called on this mock object - - - The mock. - The action. - The setup constraints. - - - - Finds the approprite implementation type of this item. - This is the class or an interface outside of the rhino mocks. - - The mocked obj. - - - - - Verifies all expectations on this mock object - - The mock object. - - - - Gets the event raiser for the event that was called in the action passed - - The type of the event source. - The mock object. - The event subscription. - - - - - Raise the specified event using the passed arguments. - The even is extracted from the passed labmda - - The type of the event source. - The mock object. - The event subscription. - The sender. - The instance containing the event data. - - - - Raise the specified event using the passed arguments. - The even is extracted from the passed labmda - - The type of the event source. - The mock object. - The event subscription. - The args. - - - TODO: Make this better! It currently breaks down when mocking classes or - ABC's that call other virtual methods which are getting intercepted too. I wish - we could just walk Expression{Action{Action{T}} to assert only a single - method is being made. - - The workaround is to not call foo.AssertWasCalled .. rather foo.VerifyAllExpectations() - The type of mock object - The mock repository - The actual mock object to assert expectations on. - - - - Fake type that disallow creating it. - Should have been System.Type, but we can't use it. - - - - - Utility class for dealing with messing generics scenarios. - - - - - There are issues with trying to get this to work correctly with open generic types, since this is an edge case, - I am letting the runtime handle it. - - - - - Gets the real type, including de-constructing and constructing the type of generic - methods parameters. - - The type. - The invocation. - - - - - Because we need to support complex types here (simple generics were handled above) we - need to be aware of the following scenarios: - List[T] and List[Foo[T]] - - - - - ExpectationsList - - - - - Dictionary - - - - - Dictionary class - - - - - Create a new instance of ProxyStateDictionary - - - - - Allows to call a method and immediately get it's options. - - - - - Interface to allow calling a method and immediately get it's options. - - - - - Get the method options for the call - - The method call should go here, the return value is ignored - - - - Creates a new instance. - - - - - Get the method options for the call - - The method call should go here, the return value is ignored - - - - Allows to call a method and immediately get it's options. - Set the expected number for the call to Any() - - - - - Creates a new instance. - - Proxy. - Mocked instance. - - - - Get the method options for the call - - The method call should go here, the return value is ignored - - - - This class is reponsible for taking a delegate and creating a wrapper - interface around it, so it can be mocked. - - - - - The scope for all the delegate interfaces create by this mock repository. - - - - - Gets a type with an "Invoke" method suitable for use as a target of the - specified delegate type. - - - - - - - Raise events for all subscribers for an event - - - - - Raise events for all subscribers for an event - - - - - Raise the event - - - - - The most common form for the event handler signature - - - - - Create an event raiser for the specified event on this instance. - - - - - Creates a new instance of EventRaiser - - - - - Raise the event - - - - - The most common signature for events - Here to allow intellisense to make better guesses about how - it should suggest parameters. - - - - - Allows to define what would happen when a method - is called. - - - - - Allows to define what would happen when a method - is called. - - - - - Set the return value for the method. - - The object the method will return - IRepeat that defines how many times the method will return this value - - - - Allow to override this return value in the future - - IRepeat that defines how many times the method will return this value - - - - Throws the specified exception when the method is called. - - Exception to throw - - - - Ignores the arguments for this method. Any argument will be matched - againt this method. - - - - - Add constraints for the method's arguments. - - - - - Set a callback method for the last call - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched - and allow to optionally modify the invocation as needed - - - - - Call the original method on the class, bypassing the mocking layers. - - - - - - Call the original method on the class, optionally bypassing the mocking layers. - - - - - - Use the property as a simple property, getting/setting the values without - causing mock expectations. - - - - - Expect last (property) call as property setting, ignore the argument given - - - - - - Expect last (property) call as property setting with a given argument. - - - - - - - Get an event raiser for the last subscribed event. - - - - - Set the parameter values for out and ref parameters. - This is done using zero based indexing, and _ignoring_ any non out/ref parameter. - - - - - Documentation message for the expectation - - Message - - - - Better syntax to define repeats. - - - - - Allows to specify the number of time for method calls - - - - - Repeat the method twice. - - - - - Repeat the method once. - - - - - Repeat the method at least once, then repeat as many time as it would like. - - - - - Repeat the method any number of times. - This has special affects in that this method would now ignore orderring. - - - - - Set the range to repeat an action. - - Min. - Max. - - - - Set the amount of times to repeat an action. - - - - - This method must not appear in the replay state. - This has special affects in that this method would now ignore orderring. - - - - - Creates a new instance. - - the repository for this expectation - the recorder for this proxy - the proxy for this expectation - Expectation. - - - - Add constraints for the method's arguments. - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Set the return value for the method. - - The object the method will return - IRepeat that defines how many times the method will return this value - - - - Set the return value for the method, but allow to override this return value in the future - - IRepeat that defines how many times the method will return this value - - - - Throws the specified exception when the method is called. - - Exception to throw - - - - Ignores the arguments for this method. Any argument will be matched - againt this method. - - - - - Call the original method on the class, bypassing the mocking layers. - - - - - - Call the original method on the class, optionally bypassing the mocking layers - - - - - - Use the property as a simple property, getting/setting the values without - causing mock expectations. - - - - - Expect last (property) call as property setting, ignore the argument given - - - - - - Expect last (property) call as property setting with a given argument. - - - - - - - Gets the event raiser for the last event - - - - - Set the parameter values for out and ref parameters. - This is done using zero based indexing, and _ignoring_ any non out/ref parameter. - - - - - Repeat the method twice. - - - - - Repeat the method once. - - - - - Repeat the method at least once, then repeat as many time as it would like. - - - - - This method must not appear in the replay state. - - - - - Documentation message for the expectation - - Message - - - - Repeat the method any number of times. - - - - - Set the range to repeat an action. - - Min. - Max. - - - - Set the amount of times to repeat an action. - - - - - Better syntax to define repeats. - - - - - This class will provide hash code for hashtables without needing - to call the GetHashCode() on the object, which may very well be mocked. - This class has no state so it is a singelton to avoid creating a lot of objects - that does the exact same thing. See flyweight patterns. - - - - - Get the hash code for a proxy object without calling GetHashCode() - on the object. - - - - - Compares two instances of mocked objects - - - - - Compare two mocked objects - - - - - The next hash code value for a mock object. - This is safe for multi threading. - - - - - The sole instance of - - - - - This is a dummy type that is used merely to give DynamicProxy the proxy instance that - it needs to create IProxy's types. - - - - - Interface to find the repository of a mocked object - - - - - Return true if it should call the original method on the object - instead of pass it to the message chain. - - The method to call - - - - Register a method to be called on the object directly - - - - - Register a property on the object that will behave as a simple property - - - - - Check if the method was registered as a property method. - - - - - Do get/set on the property, according to need. - - - - - Do add/remove on the event - - - - - Get the subscribers of a spesific event - - - - - Gets the declaring type of the method, taking into acccount the possible generic - parameters that it was created with. - - - - - Clears the state of the object, remove original calls, property behavior, subscribed events, etc. - - - - - Get all the method calls arguments that were made against this object with the specificed - method. - - - Only method calls in replay mode are counted - - - - - Records the method call - - - - - Mocks that are tied to this mock lifestyle - - - - - The unique hash code of this mock, which is not related - to the value of the GetHashCode() call on the object. - - - - - Gets the repository. - - - - - Gets the implemented types by this mocked object - - The implemented. - - - - Gets or sets the constructor arguments. - - The constructor arguments. - - - - The mocked instance that this is representing - - - - - Create a new instance of - - - - - Return true if it should call the original method on the object - instead of pass it to the message chain. - - The method to call - - - - Register a method to be called on the object directly - - - - - Register a property on the object that will behave as a simple property - Return true if there is already a value for the property - - - - - Check if the method was registered as a property method. - - - - - Do get/set on the property, according to need. - - - - - Do add/remove on the event - - - - - Get the subscribers of a spesific event - - - - - Gets the declaring type of the method, taking into acccount the possible generic - parameters that it was created with. - - - - - Get all the method calls arguments that were made against this object with the specificed - method. - - - - - Only method calls in replay mode are counted - - - - - Records the method call - - - - - - - Clears the state of the object, remove original calls, property behavior, subscribed events, etc. - - - - - Mocks that are tied to this mock lifestyle - - - - - The unique hash code of this proxy, which is not related - to the value of the GetHashCode() call on the object. - - - - - Gets the repository. - - - - - Gets or sets the constructor arguments. - - The constructor arguments. - - - - The mocked instance that this is representing - - - - - Gets the implemented types by this mocked object - - The implemented. - - - - Range for expected method calls - - - - - Creates a new instance. - - Min. - Max. - - - - Return the string representation of this range. - - - - - Gets or sets the min. - - - - - - Gets or sets the max. - - - - - - Records all the expectations for a mock and - return a ReplayDynamicMockState when Replay() - is called. - - - - - Creates a new instance. - - Repository. - The proxy that generates the method calls - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Get the default call count range expectation - - - - - - Gets a mock state that match the original mock state of the object. - - - - - Records all the expectations for a mock and - return a ReplayPartialMockState when Replay() - is called. - - - - - Creates a new instance. - - Repository. - The proxy that generates the method calls - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Gets a mock state that matches the original mock state of the object. - - - - - Options for special repeat option - - - - - This method can be called only as many times as the IMethodOptions.Expect allows. - - - - - This method should never be called - - - - - This method can be call any number of times - - - - - This method will call the original method - - - - - This method will call the original method, bypassing the mocking layer - - - - - This method will simulate simple property behavior - - - - - Validate all expectations on a mock and ignores calls to - any method that was not setup properly. - - - - - Creates a new instance. - - The previous state for this method - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Gets a mock state that match the original mock state of the object. - - - - - Validate all expectations on a mock and ignores calls to - any method that was not setup properly. - - - - - Creates a new instance. - - The previous state for this method - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Gets a mock state that match the original mock state of the object. - - - - - Summary description for RhinoInterceptor. - - - - - Creates a new instance. - - - - - Intercept a method call and direct it to the repository. - - - - - Validate arguments for methods - - - - - Validate that the passed argument is not null. - - The object to validate - The name of the argument - - If the obj is null, an ArgumentNullException with the passed name - is thrown. - - - - - Validate that the arguments are equal. - - Expected args. - Actual Args. - - - - Validate that the two arguments are equals, including validation for - when the arguments are collections, in which case it will validate their values. - - - - - This method is safe for use even if any of the objects is a mocked object - that override equals. - - - - - Throw an object already verified when accessed - - - - - Create a new instance of VerifiedMockState - - The previous mock state, used to get the initial record state - - - - Add a method call for this state' mock. - - The invocation for this method - The method that was called - The arguments this method was called with - - - - Verify that this mock expectations have passed. - - - - - Verify that we can move to replay state and move - to the reply state. - - - - - Gets a mock state that match the original mock state of the object. - - - - - Get the options for the last method call - - - - - Set the exception to throw when Verify is called. - This is used to report exception that may have happened but where caught in the code. - This way, they are reported anyway when Verify() is called. - - - - - not relevant - - - - - Gets the matching verify state for this state - - - - - Get the options for the last method call - - - - - Records the actions on all the mocks created by a repository. - - - - - Records the specified call with the specified args on the mocked object. - - - - - Get the expectation for this method on this object with this arguments - - - - - This check the methods that were setup using the SetupResult.For() - or LastCall.Repeat.Any() and that bypass the whole expectation model. - - - - - Gets the all expectations for a mocked object and method combination, - regardless of the expected arguments / callbacks / contraints. - - Mocked object. - Method. - List of all relevant expectation - - - - Gets the all expectations for proxy. - - Mocked object. - List of all relevant expectation - - - - Removes all the repeatable expectations for proxy. - - Mocked object. - - - - Replaces the old expectation with the new expectation for the specified proxy/method pair. - This replace ALL expectations that equal to old expectations. - - Proxy. - Method. - Old expectation. - New expectation. - - - - Adds the recorder and turn it into the active recorder. - - Recorder. - - - - Moves to previous recorder. - - - - - Gets the recorded expectation or null. - - - - - Gets the next expected calls string. - - - - - Moves to parent recorder. - - - - - Set the expectation so it can repeat any number of times. - - - - - Removes the expectation from the recorder - - - - - Clear the replayer to call (and all its chain of replayers) - This also removes it from the list of expectations, so it will never be considered again - - - - - Get the expectation for this method on this object with this arguments - - - - - Gets a value indicating whether this instance has expectations that weren't satisfied yet. - - - true if this instance has expectations; otherwise, false. - - - - - Allows to set various options for the last method call on - a specified object. - If the method has a return value, it's recommended to use Expect - - - - - Allows to get an interface to work on the last call. - - The mocked object - Interface that allows to set options for the last method call on this object - - - - Set the return value for the method. - - The object the method will return - IRepeat that defines how many times the method will return this value - - - - Set the return value for the method. This overload is needed for LastCall.Return(null) - - The object the method will return - IRepeat that defines how many times the method will return this value - - - - Throws the specified exception when the method is called. - - Exception to throw - - - - Ignores the arguments for this method. Any argument will be matched - againt this method. - - - - - Add constraints for the method's arguments. - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Set a callback method for the last call - - - - - Call the original method on the class, bypassing the mocking layers, for the last call. - - - - - Call the original method on the class, optionally bypassing the mocking layers, for the last call. - - - - - Set a delegate to be called when the expectation is matched. - The delegate return value will be returned from the expectation. - - - - - Gets an interface that will raise the last event when called. - - - - - Set the parameter values for out and ref parameters. - This is done using zero based indexing, and _ignoring_ any non out/ref parameter. - - - - - Documentation message for the expectation - - Message - - - - Use the property as a simple property, getting/setting the values without - causing mock expectations. - - - - - Better syntax to define repeats. - - - - - Base class for method recorders, handle delegating to inner recorder if needed. - - - - - List of the expected actions on for this recorder - The legal values are: - * Expectations - * Method Recorders - - - - - The current recorder. - - - - - The current replayer; - - - - - The parent recorder of this one, may be null. - - - - - This contains a list of all the replayers that should be ignored - for a spesific method call. A replayer gets into this list by calling - ClearReplayerToCall() on its parent. This list is Clear()ed on each new invocation. - - - - - All the repeatable methods calls. - - - - - Counts the recursion depth of the current expectation search stack - - - - - Creates a new instance. - - - - - Creates a new instance. - - Parent recorder. - Repeatable methods - - - - Records the specified call with the specified args on the mocked object. - - - - - Get the expectation for this method on this object with this arguments - - - - - Gets the all expectations for a mocked object and method combination, - regardless of the expected arguments / callbacks / contraints. - - Mocked object. - Method. - List of all relevant expectation - - - - Gets the all expectations for proxy. - - Mocked object. - List of all relevant expectation - - - - Replaces the old expectation with the new expectation for the specified proxy/method pair. - This replace ALL expectations that equal to old expectations. - - Proxy. - Method. - Old expectation. - New expectation. - - - - Remove the all repeatable expectations for proxy. - - Mocked object. - - - - Set the expectation so it can repeat any number of times. - - - - - Removes the expectation from the recorder - - - - - Adds the recorder and turn it into the active recorder. - - Recorder. - - - - Moves to previous recorder. - - - - - Moves to parent recorder. - - - - - Gets the recorded expectation or null. - - - - - Clear the replayer to call (and all its chain of replayers). - This also removes it from the list of expectations, so it will never be considered again - - - - - Get the expectation for this method on this object with this arguments - - - - - Gets the next expected calls string. - - - - - Handles the real getting of the recorded expectation or null. - - - - - Handle the real execution of this method for the derived class - - - - - Handle the real execution of this method for the derived class - - - - - Handle the real execution of this method for the derived class - - - - - Handle the real execution of this method for the derived class - - - - - Handle the real execution of this method for the derived class - - - - - Handle the real execution of this method for the derived class - - - - - Should this replayer be considered valid for this call? - - - - - This check the methods that were setup using the SetupResult.For() - or LastCall.Repeat.Any() and that bypass the whole expectation model. - - - - - Gets a value indicating whether this instance has expectations that weren't satisfied yet. - - - true if this instance has expectations; otherwise, false. - - - - - Handle the real execution of this method for the derived class - - - - - Ordered collection of methods, methods must arrive in specified order - in order to pass. - - - - - Unordered collection of method records, any expectation that exist - will be matched. - - - - - The parent recorder we have redirected to. - Useful for certain edge cases in orderring. - See: FieldProblem_Entropy for the details. - - - - - Creates a new instance. - - Parent recorder. - Repeatable methods - - - - Creates a new instance. - - - - - Records the specified call with the specified args on the mocked object. - - Mocked object. - Method. - Expectation. - - - - Get the expectation for this method on this object with this arguments - - Invocation for this method - Mocked object. - Method. - Args. - True is the call was recorded, false otherwise - - - - Gets the all expectations for a mocked object and method combination, - regardless of the expected arguments / callbacks / contraints. - - Mocked object. - Method. - List of all relevant expectation - - - - Gets the all expectations for proxy. - - Mocked object. - List of all relevant expectation - - - - Replaces the old expectation with the new expectation for the specified proxy/method pair. - This replace ALL expectations that equal to old expectations. - - Proxy. - Method. - Old expectation. - New expectation. - - - - Handle the real execution of this method for the derived class - - - - - Handles the real getting of the recorded expectation or null. - - - - - Handle the real execution of this method for the derived class - - - - - Gets the next expected calls string. - - - - - Create an exception for an unexpected method call. - - - - - Gets a value indicating whether this instance has expectations that weren't satisfied yet. - - - true if this instance has expectations; otherwise, false. - - - - - Creates a new instance. - - Parent recorder. - Repetable methods - - - - Creates a new instance. - - - - - Handles the real getting of the recorded expectation or null. - - - - - Get the expectation for this method on this object with this arguments - - - - - Gets the next expected calls string. - - - - - Hold an expectation for a method call on an object - - - - - Creates a new instance. - - Proxy. - Method. - Expectation. - - - - Determines if the object equal to this instance - - Obj. - - - - - Gets the hash code. - - - - - - Gets the proxy. - - - - - - Gets the method. - - - - - - Gets the expectation. - - - - - - Holds a pair of mocked object and a method - and allows to compare them against each other. - This allows us to have a distinction between mockOne.MyMethod() and - mockTwo.MyMethod()... - - - - - Creates a new instance. - - Proxy. - Method. - - - - Determines whatever obj equals to this instance. - ProxyMethodPairs are equal when they point to the same /instance/ of - an object, and to the same method. - - Obj. - - - - - Gets the hash code. - - - - - - Gets the proxy. - - - - - - Gets the method. - - - - - - Change the recorder from ordered to unordered and vice versa - - - - - Creates a new instance. - - - - - Disposes this instance. - - - - - Accessor for the current mocker - - - - - The current mocker - - - - - Used for [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] - Used for [assembly: InternalsVisibleTo(RhinoMocks.NormalName)] - - - - - Strong name for the Dynamic Proxy assemblies. Used for InternalsVisibleTo specification. - - - - - Normal name for dynamic proxy assemblies. Used for InternalsVisibleTo specification. - - - - - Logs all method calls for methods - - - - - Setup method calls to repeat any number of times. - - - - - Get the method options and set the last method call to repeat - any number of times. - This also means that the method would transcend ordering - - - - - Get the method options for the last method call on the mockInstance and set it - to repeat any number of times. - This also means that the method would transcend ordering - - - - - Utility class for working with method calls. - - - - - Return the string representation of a method call and its arguments. - - The method - The method arguments - Invocation of the method, used to get the generics arguments - Delegate to format the parameter - The string representation of this method call - - - - Return the string representation of a method call and its arguments. - - The invocation of the method, used to get the generic parameters - The method - The method arguments - The string representation of this method call - - - - Delegate to format the argument for the string representation of - the method call. - - - - - Utility to get the default value for a type - - - - - The default value for a type. - Null for reference types and void - 0 for value types. - First element for enums - Note that we need to get the value even for opened generic types, such as those from - generic methods. - - Type. - The invocation. - the default value - - - - Allows easier access to MockRepository, works closely with Mocker.Current to - allow access to a context where the mock repository is automatially verified at - the end of the code block. - - - - - Initialize a code block where Mocker.Current is initialized. - At the end of the code block, all the expectation will be verified. - This overload will create a new MockRepository. - - The code that will be executed under the mock context - - - - Initialize a code block where Mocker.Current is initialized. - At the end of the code block, all the expectation will be verified. - This overload will create a new MockRepository. - - The mock repository to use, at the end of the code block, VerifyAll() will be called on the repository. - The code that will be executed under the mock context - - - - Create a FluentMocker - - The mock repository to use. - - - - A method with no arguments and no return value that will be called under the mock context. - - - - - FluentMocker implements some kind of fluent interface attempt - for saying "With the Mocks [mocks], Expecting (in same order) [things] verify [that]." - - - - - Interface to verify previously defined expectations - - - - - Verifies if a piece of code - - - - - Defines unordered expectations - - A delegate describing the expectations - an IMockVerifier - - - - Defines ordered expectations - - A delegate describing the expectations - an IMockVerifier - - - - Verifies previously defined expectations - - - - - This delegate is compatible with the System.Func{T,R} signature - We have to define our own to get compatability with 2.0 - - - - - This attribute is here so we can get better Pex integration - Using this means that Pex will not try to inspect the work of - the actual proxies being generated by Rhino Mocks - - - - diff --git a/src/Directory.Build.props b/src/Directory.Build.props index b14138642..b3ce936cf 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -31,8 +31,8 @@ en-US True - git - https://github.com/spring-projects/spring-net + true + true True @@ -46,8 +46,13 @@ latest + + + + + Full DEBUG;TRACE;DEBUG_DYNAMIC;$(DefineConstants) diff --git a/src/Spring/Spring.Aop/Aop/Framework/AdvisorChainFactoryUtils.cs b/src/Spring/Spring.Aop/Aop/Framework/AdvisorChainFactoryUtils.cs index d4ebd34ef..7f8c998b3 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/AdvisorChainFactoryUtils.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/AdvisorChainFactoryUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Aop/Aop/Framework/AopContext.cs b/src/Spring/Spring.Aop/Aop/Framework/AopContext.cs index 5954a361c..5c8cca18f 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/AopContext.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/AopContext.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ namespace Spring.Aop.Framework /// advice configuration. ///

///

- /// To expose the current proxy, set the + /// To expose the current proxy, set the /// property on the controlling proxy to . /// The default value for the property /// is , for performance reasons. @@ -70,7 +70,7 @@ public sealed class AopContext /// private static Stack ProxyStack { - get + get { if (tls_ProxyStack == null) { @@ -90,7 +90,7 @@ private static Stack ProxyStack /// on the controlling proxy has been set to . ///

///

- /// The default value for the + /// The default value for the /// property /// is , for performance reasons. ///

@@ -99,7 +99,7 @@ public static bool IsActive { get { - return (tls_ProxyStack != null && tls_ProxyStack.Count > 0); + return (tls_ProxyStack != null && tls_ProxyStack.Count > 0); } } @@ -125,7 +125,7 @@ public static object CurrentProxy } /// - /// Sets the current proxy by pushing it to the proxy stack. + /// Sets the current proxy by pushing it to the proxy stack. /// /// ///

diff --git a/src/Spring/Spring.Aop/Aop/Framework/AutoProxy/AbstractAutoProxyCreator.cs b/src/Spring/Spring.Aop/Aop/Framework/AutoProxy/AbstractAutoProxyCreator.cs index 4e45a4934..02528ba00 100644 --- a/src/Spring/Spring.Aop/Aop/Framework/AutoProxy/AbstractAutoProxyCreator.cs +++ b/src/Spring/Spring.Aop/Aop/Framework/AutoProxy/AbstractAutoProxyCreator.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,13 +109,13 @@ public abstract class AbstractAutoProxyCreator : ProxyConfig, IInstantiationAwar /// Indicates whether to mark the create proxy as immutable. /// /// - /// Setting this to true effectively disables modifying the generated + /// Setting this to true effectively disables modifying the generated /// proxy's advisor configuration /// private bool freezeProxy = false; ///

- /// Names of common interceptors. + /// Names of common interceptors. /// We must use object name rather than object references /// to handle prototype advisors/interceptors. /// Default is the empty array: no common interceptors. @@ -142,7 +142,7 @@ public abstract class AbstractAutoProxyCreator : ProxyConfig, IInstantiationAwar #region Properties /// - /// Sets the AdvisorAdapterRegistry to use. + /// Sets the AdvisorAdapterRegistry to use. /// /// /// Default is the global AdvisorAdapterRegistry. @@ -170,19 +170,19 @@ public IList CustomTargetSourceCreators set { customTargetSourceCreators = value; } } - /// - /// Sets the common interceptors, a list of , + /// + /// Sets the common interceptors, a list of , /// and introduction object names. /// /// /// - /// If this property isn't set, there will be zero common interceptors. + /// If this property isn't set, there will be zero common interceptors. /// This is perfectly valid, if "specific" interceptors such as /// matching Advisors are all we want. /// /// /// - /// The list of , + /// The list of , /// and introduction object names. /// /// @@ -194,7 +194,7 @@ public string[] InterceptorNames /// /// Sets whether the common interceptors should be applied before - /// object-specific ones. + /// object-specific ones. /// /// /// Default is true; else, object-specific interceptors will get applied first. @@ -683,7 +683,7 @@ public bool PostProcessAfterInstantiation(object objectInstance, string objectNa /// The property values that the factory is about to apply (never null). /// he relevant property infos for the target object (with ignored /// dependency types - which the factory handles specifically - already filtered out) - /// The object instance created, but whose properties have not yet + /// The object instance created, but whose properties have not yet /// been set. /// Name of the object. /// The passed in PropertyValues diff --git a/src/Spring/Spring.Aop/Aop/Target/SimplePoolTargetSource.cs b/src/Spring/Spring.Aop/Aop/Target/SimplePoolTargetSource.cs index 623150ae1..362265cda 100644 --- a/src/Spring/Spring.Aop/Aop/Target/SimplePoolTargetSource.cs +++ b/src/Spring/Spring.Aop/Aop/Target/SimplePoolTargetSource.cs @@ -2,13 +2,13 @@ /* * Copyright © 2002-2011 the original author or authors. -* +* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -* +* * http://www.apache.org/licenses/LICENSE-2.0 -* +* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs b/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs index aee150980..fc754a5c2 100644 --- a/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs +++ b/src/Spring/Spring.Core/Context/Support/AbstractApplicationContext.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -236,7 +236,7 @@ protected AbstractApplicationContext(string name, bool caseSensitive, /// processors being added to the underlying /// /// - /// Each time is called on this context, the context ensures, that + /// Each time is called on this context, the context ensures, that /// all default s are registered with the underlying . /// /// The instance. @@ -268,7 +268,7 @@ public virtual void Dispose() #endregion - // Closed event is raised before destroying objectfactory to enable registered IApplicationEventListeners + // Closed event is raised before destroying objectfactory to enable registered IApplicationEventListeners // to handle the event before they get disposed. PublishEvent(this, new ContextClosedEventArgs()); @@ -1046,7 +1046,7 @@ public void Refresh() } /// - /// Registers well-known s and + /// Registers well-known s and /// preregisters well-known dependencies using /// /// the raw object factory as returned from @@ -1370,14 +1370,14 @@ public IList GetObjectDefinitionNames() { return GetObjectDefinitionNames(false); } - + /// /// Return the names of all objects defined in this factory, if includeAncestorsis true /// includes all parent factories. /// /// to include parent factories into result /// - /// The names of all objects defined in this factory, if includeAncestors is true includes all + /// The names of all objects defined in this factory, if includeAncestors is true includes all /// objects defined in parent factories, or an empty array if none are defined. /// public IList GetObjectDefinitionNames(bool includeAncestors) @@ -1401,7 +1401,7 @@ public IList GetObjectDefinitionNames(bool includeAncestors) /// /// /// In the case of errors. - /// + /// public virtual IObjectDefinition GetObjectDefinition(string name) { return SafeGetObjectFactory().GetObjectDefinition(name); @@ -1425,7 +1425,7 @@ public virtual IObjectDefinition GetObjectDefinition(string name) /// /// /// In the case of errors. - /// + /// public IObjectDefinition GetObjectDefinition(string name, bool includeAncestors) { return SafeGetObjectFactory().GetObjectDefinition(name, includeAncestors); @@ -2099,7 +2099,7 @@ public IObjectFactory ParentObjectFactory /// of the given name from an ancestor object factory. /// /// - /// + /// /// /// The name of the object to query. /// @@ -2115,8 +2115,8 @@ public bool ContainsLocalObject(string name) #region IObjectDefinitionRegistry Members /// - /// Determine whether the given object name is already in use within this context, - /// i.e. whether there is a local object. May be override by subclasses, the default + /// Determine whether the given object name is already in use within this context, + /// i.e. whether there is a local object. May be override by subclasses, the default /// implementation simply returns /// public virtual bool IsObjectNameInUse(string objectName) @@ -2496,7 +2496,7 @@ public void Unsubscribe(object subscriber, Type targetSourceType) /// /// ///

- /// + /// ///

///
/// diff --git a/src/Spring/Spring.Core/Expressions/LambdaExpressionNode.cs b/src/Spring/Spring.Core/Expressions/LambdaExpressionNode.cs index 986871b37..bd5ee866a 100644 --- a/src/Spring/Spring.Core/Expressions/LambdaExpressionNode.cs +++ b/src/Spring/Spring.Core/Expressions/LambdaExpressionNode.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ public class LambdaExpressionNode : BaseNode /// caches argumentNames of this instance /// private string[] argumentNames; - + /// /// caches body expression of this lambda function /// @@ -56,7 +56,7 @@ protected LambdaExpressionNode(SerializationInfo info, StreamingContext context) : base(info, context) { } - + /// /// Gets argument names for this lambda expression. /// @@ -107,7 +107,7 @@ protected override object Get(object context, EvaluationContext evalContext, obj arguments[argNames[i]] = argValues[i]; } - EvaluationContext ec = (EvaluationContext)evalContext; + EvaluationContext ec = evalContext; using (ec.SwitchLocalVariables(arguments)) { object result = Get(context, ec); diff --git a/src/Spring/Spring.Core/Expressions/Parser/ExpressionParser.cs b/src/Spring/Spring.Core/Expressions/Parser/ExpressionParser.cs index 202e41e3f..1124ebb53 100644 --- a/src/Spring/Spring.Core/Expressions/Parser/ExpressionParser.cs +++ b/src/Spring/Spring.Core/Expressions/Parser/ExpressionParser.cs @@ -4,7 +4,7 @@ namespace Spring.Expressions.Parser { // Generate the header common to all output files. using System; - + using TokenBuffer = antlr.TokenBuffer; using Token = antlr.Token; using TokenStream = antlr.TokenStream; @@ -88,10 +88,10 @@ internal class ExpressionParser : antlr.LLkParser public const int EXPONENT_PART = 69; public const int SIGN = 70; public const int REAL_TYPE_SUFFIX = 71; - - + + // CLOVER:OFF - + public override void reportError(RecognitionException ex) { //base.reportError(ex); @@ -103,7 +103,7 @@ public override void reportError(string error) //base.reportError(error); throw new RecognitionException(error); } - + private string GetRelationalOperatorNodeType(string op) { switch (op) @@ -119,48 +119,48 @@ private string GetRelationalOperatorNodeType(string op) case "between" : return "Spring.Expressions.OpBetween"; case "like" : return "Spring.Expressions.OpLike"; case "matches" : return "Spring.Expressions.OpMatches"; - default : + default : throw new ArgumentException("Node type for operator '" + op + "' is not defined."); } } - + protected void initialize() { tokenNames = tokenNames_; initializeFactory(); } - - + + protected ExpressionParser(TokenBuffer tokenBuf, int k) : base(tokenBuf, k) { initialize(); } - + public ExpressionParser(TokenBuffer tokenBuf) : this(tokenBuf,2) { } - + protected ExpressionParser(TokenStream lexer, int k) : base(lexer,k) { initialize(); } - + public ExpressionParser(TokenStream lexer) : this(lexer,2) { } - + public ExpressionParser(ParserSharedInputState state) : base(state,2) { initialize(); } - + public void expr() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST expr_AST = null; - + try { // for error handling expression(); if (0 == inputState.guessing) @@ -184,14 +184,14 @@ public void expr() //throws RecognitionException, TokenStreamException } returnAST = expr_AST; } - + public void expression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST expression_AST = null; - + try { // for error handling logicalOrExpression(); if (0 == inputState.guessing) @@ -284,14 +284,14 @@ public void expression() //throws RecognitionException, TokenStreamException } returnAST = expression_AST; } - + public void exprList() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST exprList_AST = null; - + try { // for error handling match(LPAREN); expression(); @@ -316,7 +316,7 @@ public void exprList() //throws RecognitionException, TokenStreamException { if (_cnt4 >= 1) { goto _loop4_breakloop; } else { throw new NoViableAltException(LT(1), getFilename());; } } - + _cnt4++; } _loop4_breakloop: ; @@ -349,14 +349,14 @@ public void exprList() //throws RecognitionException, TokenStreamException } returnAST = exprList_AST; } - + public void logicalOrExpression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST logicalOrExpression_AST = null; - + try { // for error handling logicalXorExpression(); if (0 == inputState.guessing) @@ -382,7 +382,7 @@ public void logicalOrExpression() //throws RecognitionException, TokenStreamExce { goto _loop13_breakloop; } - + } _loop13_breakloop: ; } // ( ... )* @@ -402,14 +402,14 @@ public void logicalOrExpression() //throws RecognitionException, TokenStreamExce } returnAST = logicalOrExpression_AST; } - + public void parenExpr() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST parenExpr_AST = null; - + try { // for error handling match(LPAREN); expression(); @@ -434,14 +434,14 @@ public void parenExpr() //throws RecognitionException, TokenStreamException } returnAST = parenExpr_AST; } - + public void logicalXorExpression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST logicalXorExpression_AST = null; - + try { // for error handling logicalAndExpression(); if (0 == inputState.guessing) @@ -467,7 +467,7 @@ public void logicalXorExpression() //throws RecognitionException, TokenStreamExc { goto _loop16_breakloop; } - + } _loop16_breakloop: ; } // ( ... )* @@ -487,14 +487,14 @@ public void logicalXorExpression() //throws RecognitionException, TokenStreamExc } returnAST = logicalXorExpression_AST; } - + public void logicalAndExpression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST logicalAndExpression_AST = null; - + try { // for error handling relationalExpression(); if (0 == inputState.guessing) @@ -520,7 +520,7 @@ public void logicalAndExpression() //throws RecognitionException, TokenStreamExc { goto _loop19_breakloop; } - + } _loop19_breakloop: ; } // ( ... )* @@ -540,17 +540,17 @@ public void logicalAndExpression() //throws RecognitionException, TokenStreamExc } returnAST = logicalAndExpression_AST; } - + public void relationalExpression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST relationalExpression_AST = null; Spring.Expressions.SpringAST e1_AST = null; Spring.Expressions.SpringAST op_AST = null; Spring.Expressions.SpringAST e2_AST = null; - + try { // for error handling sumExpr(); if (0 == inputState.guessing) @@ -590,7 +590,7 @@ public void relationalExpression() //throws RecognitionException, TokenStreamExc { throw new NoViableAltException(LT(1), getFilename()); } - + } relationalExpression_AST = (Spring.Expressions.SpringAST)currentAST.root; } @@ -608,14 +608,14 @@ public void relationalExpression() //throws RecognitionException, TokenStreamExc } returnAST = relationalExpression_AST; } - + public void sumExpr() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST sumExpr_AST = null; - + try { // for error handling prodExpr(); if (0 == inputState.guessing) @@ -645,7 +645,7 @@ public void sumExpr() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } prodExpr(); if (0 == inputState.guessing) @@ -657,7 +657,7 @@ public void sumExpr() //throws RecognitionException, TokenStreamException { goto _loop25_breakloop; } - + } _loop25_breakloop: ; } // ( ... )* @@ -677,14 +677,14 @@ public void sumExpr() //throws RecognitionException, TokenStreamException } returnAST = sumExpr_AST; } - + public void relationalOperator() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST relationalOperator_AST = null; - + try { // for error handling switch ( LA(1) ) { @@ -807,14 +807,14 @@ public void relationalOperator() //throws RecognitionException, TokenStreamExcep } returnAST = relationalOperator_AST; } - + public void prodExpr() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST prodExpr_AST = null; - + try { // for error handling powExpr(); if (0 == inputState.guessing) @@ -869,7 +869,7 @@ public void prodExpr() //throws RecognitionException, TokenStreamException { goto _loop29_breakloop; } - + } _loop29_breakloop: ; } // ( ... )* @@ -889,14 +889,14 @@ public void prodExpr() //throws RecognitionException, TokenStreamException } returnAST = prodExpr_AST; } - + public void powExpr() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST powExpr_AST = null; - + try { // for error handling unaryExpression(); if (0 == inputState.guessing) @@ -922,7 +922,7 @@ public void powExpr() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } powExpr_AST = (Spring.Expressions.SpringAST)currentAST.root; } @@ -940,14 +940,14 @@ public void powExpr() //throws RecognitionException, TokenStreamException } returnAST = powExpr_AST; } - + public void unaryExpression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST unaryExpression_AST = null; - + try { // for error handling if ((LA(1)==PLUS||LA(1)==MINUS||LA(1)==BANG)) { @@ -1003,7 +1003,7 @@ public void unaryExpression() //throws RecognitionException, TokenStreamExceptio { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -1019,14 +1019,14 @@ public void unaryExpression() //throws RecognitionException, TokenStreamExceptio } returnAST = unaryExpression_AST; } - + public void primaryExpression() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST primaryExpression_AST = null; - + try { // for error handling startNode(); if (0 == inputState.guessing) @@ -1048,7 +1048,7 @@ public void primaryExpression() //throws RecognitionException, TokenStreamExcept { throw new NoViableAltException(LT(1), getFilename()); } - + } if (0==inputState.guessing) { @@ -1077,14 +1077,14 @@ public void primaryExpression() //throws RecognitionException, TokenStreamExcept } returnAST = primaryExpression_AST; } - + public void unaryOperator() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST unaryOperator_AST = null; - + try { // for error handling switch ( LA(1) ) { @@ -1135,14 +1135,14 @@ public void unaryOperator() //throws RecognitionException, TokenStreamException } returnAST = unaryOperator_AST; } - + public void startNode() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST startNode_AST = null; - + try { // for error handling { switch ( LA(1) ) @@ -1347,14 +1347,14 @@ public void startNode() //throws RecognitionException, TokenStreamException } returnAST = startNode_AST; } - + public void node() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST node_AST = null; - + try { // for error handling { // ( ... )+ int _cnt43=0; @@ -1455,14 +1455,14 @@ public void node() //throws RecognitionException, TokenStreamException } returnAST = node_AST; } - + public void methodOrProperty() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST methodOrProperty_AST = null; - + try { // for error handling bool synPredMatched56 = false; if (((LA(1)==ID) && (LA(2)==LPAREN))) @@ -1508,7 +1508,7 @@ public void methodOrProperty() //throws RecognitionException, TokenStreamExcepti { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -1524,14 +1524,14 @@ public void methodOrProperty() //throws RecognitionException, TokenStreamExcepti } returnAST = methodOrProperty_AST; } - + public void functionOrVar() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST functionOrVar_AST = null; - + try { // for error handling bool synPredMatched46 = false; if (((LA(1)==POUND) && (LA(2)==ID))) @@ -1574,7 +1574,7 @@ public void functionOrVar() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -1590,14 +1590,14 @@ public void functionOrVar() //throws RecognitionException, TokenStreamException } returnAST = functionOrVar_AST; } - + public void localFunctionOrVar() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST localFunctionOrVar_AST = null; - + try { // for error handling bool synPredMatched51 = false; if (((LA(1)==DOLLAR) && (LA(2)==ID))) @@ -1640,7 +1640,7 @@ public void localFunctionOrVar() //throws RecognitionException, TokenStreamExcep { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -1656,17 +1656,17 @@ public void localFunctionOrVar() //throws RecognitionException, TokenStreamExcep } returnAST = localFunctionOrVar_AST; } - + public void reference() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST reference_AST = null; Spring.Expressions.SpringAST cn_AST = null; Spring.Expressions.SpringAST id_AST = null; Spring.Expressions.SpringAST localid_AST = null; - + try { // for error handling bool synPredMatched64 = false; if (((LA(1)==AT) && (LA(2)==LPAREN))) @@ -1744,7 +1744,7 @@ public void reference() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -1760,14 +1760,14 @@ public void reference() //throws RecognitionException, TokenStreamException } returnAST = reference_AST; } - + public void indexer() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST indexer_AST = null; - + try { // for error handling Spring.Expressions.IndexerNode tmp46_AST = null; tmp46_AST = (Spring.Expressions.IndexerNode) astFactory.create(LT(1), "Spring.Expressions.IndexerNode"); @@ -1794,7 +1794,7 @@ public void indexer() //throws RecognitionException, TokenStreamException { goto _loop67_breakloop; } - + } _loop67_breakloop: ; } // ( ... )* @@ -1815,14 +1815,14 @@ public void indexer() //throws RecognitionException, TokenStreamException } returnAST = indexer_AST; } - + public void literal() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST literal_AST = null; - + try { // for error handling switch ( LA(1) ) { @@ -1902,15 +1902,15 @@ public void literal() //throws RecognitionException, TokenStreamException } returnAST = literal_AST; } - + public void type() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST type_AST = null; Spring.Expressions.SpringAST tn_AST = null; - + try { // for error handling match(TYPE); name(); @@ -1946,15 +1946,15 @@ public void type() //throws RecognitionException, TokenStreamException } returnAST = type_AST; } - + public void constructor() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST constructor_AST = null; Spring.Expressions.SpringAST type_AST = null; - + try { // for error handling bool synPredMatched90 = false; if (((LA(1)==LITERAL_new) && (LA(2)==ID))) @@ -2014,7 +2014,7 @@ public void constructor() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -2030,14 +2030,14 @@ public void constructor() //throws RecognitionException, TokenStreamException } returnAST = constructor_AST; } - + public void projection() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST projection_AST = null; - + try { // for error handling Spring.Expressions.ProjectionNode tmp57_AST = null; tmp57_AST = (Spring.Expressions.ProjectionNode) astFactory.create(LT(1), "Spring.Expressions.ProjectionNode"); @@ -2065,14 +2065,14 @@ public void projection() //throws RecognitionException, TokenStreamException } returnAST = projection_AST; } - + public void selection() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST selection_AST = null; - + try { // for error handling Spring.Expressions.SelectionNode tmp59_AST = null; tmp59_AST = (Spring.Expressions.SelectionNode) astFactory.create(LT(1), "Spring.Expressions.SelectionNode"); @@ -2099,7 +2099,7 @@ public void selection() //throws RecognitionException, TokenStreamException { goto _loop71_breakloop; } - + } _loop71_breakloop: ; } // ( ... )* @@ -2120,14 +2120,14 @@ public void selection() //throws RecognitionException, TokenStreamException } returnAST = selection_AST; } - + public void firstSelection() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST firstSelection_AST = null; - + try { // for error handling Spring.Expressions.SelectionFirstNode tmp62_AST = null; tmp62_AST = (Spring.Expressions.SelectionFirstNode) astFactory.create(LT(1), "Spring.Expressions.SelectionFirstNode"); @@ -2155,14 +2155,14 @@ public void firstSelection() //throws RecognitionException, TokenStreamException } returnAST = firstSelection_AST; } - + public void lastSelection() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST lastSelection_AST = null; - + try { // for error handling Spring.Expressions.SelectionLastNode tmp64_AST = null; tmp64_AST = (Spring.Expressions.SelectionLastNode) astFactory.create(LT(1), "Spring.Expressions.SelectionLastNode"); @@ -2190,14 +2190,14 @@ public void lastSelection() //throws RecognitionException, TokenStreamException } returnAST = lastSelection_AST; } - + public void listInitializer() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST listInitializer_AST = null; - + try { // for error handling Spring.Expressions.ListInitializerNode tmp66_AST = null; tmp66_AST = (Spring.Expressions.ListInitializerNode) astFactory.create(LT(1), "Spring.Expressions.ListInitializerNode"); @@ -2224,7 +2224,7 @@ public void listInitializer() //throws RecognitionException, TokenStreamExceptio { goto _loop99_breakloop; } - + } _loop99_breakloop: ; } // ( ... )* @@ -2245,14 +2245,14 @@ public void listInitializer() //throws RecognitionException, TokenStreamExceptio } returnAST = listInitializer_AST; } - + public void mapInitializer() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST mapInitializer_AST = null; - + try { // for error handling match(POUND); Spring.Expressions.MapInitializerNode tmp70_AST = null; @@ -2280,7 +2280,7 @@ public void mapInitializer() //throws RecognitionException, TokenStreamException { goto _loop102_breakloop; } - + } _loop102_breakloop: ; } // ( ... )* @@ -2301,14 +2301,14 @@ public void mapInitializer() //throws RecognitionException, TokenStreamException } returnAST = mapInitializer_AST; } - + public void lambda() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST lambda_AST = null; - + try { // for error handling match(LAMBDA); { @@ -2326,7 +2326,7 @@ public void lambda() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } match(PIPE); expression(); @@ -2362,15 +2362,15 @@ public void lambda() //throws RecognitionException, TokenStreamException } returnAST = lambda_AST; } - + public void attribute() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST attribute_AST = null; Spring.Expressions.SpringAST tn_AST = null; - + try { // for error handling match(AT); match(LBRACKET); @@ -2394,7 +2394,7 @@ public void attribute() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } match(RBRACKET); if (0==inputState.guessing) @@ -2424,14 +2424,14 @@ public void attribute() //throws RecognitionException, TokenStreamException } returnAST = attribute_AST; } - + public void function() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST function_AST = null; - + try { // for error handling match(POUND); Spring.Expressions.FunctionNode tmp80_AST = null; @@ -2459,14 +2459,14 @@ public void function() //throws RecognitionException, TokenStreamException } returnAST = function_AST; } - + public void var() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST var_AST = null; - + try { // for error handling match(POUND); Spring.Expressions.VariableNode tmp82_AST = null; @@ -2489,14 +2489,14 @@ public void var() //throws RecognitionException, TokenStreamException } returnAST = var_AST; } - + public void methodArgs() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST methodArgs_AST = null; - + try { // for error handling match(LPAREN); { @@ -2523,7 +2523,7 @@ public void methodArgs() //throws RecognitionException, TokenStreamException { goto _loop60_breakloop; } - + } _loop60_breakloop: ; } // ( ... )* @@ -2534,7 +2534,7 @@ public void methodArgs() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } match(RPAREN); methodArgs_AST = (Spring.Expressions.SpringAST)currentAST.root; @@ -2553,14 +2553,14 @@ public void methodArgs() //throws RecognitionException, TokenStreamException } returnAST = methodArgs_AST; } - + public void localFunction() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST localFunction_AST = null; - + try { // for error handling match(DOLLAR); Spring.Expressions.LocalFunctionNode tmp87_AST = null; @@ -2588,14 +2588,14 @@ public void localFunction() //throws RecognitionException, TokenStreamException } returnAST = localFunction_AST; } - + public void localVar() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST localVar_AST = null; - + try { // for error handling match(DOLLAR); Spring.Expressions.LocalVariableNode tmp89_AST = null; @@ -2618,14 +2618,14 @@ public void localVar() //throws RecognitionException, TokenStreamException } returnAST = localVar_AST; } - + public void property() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST property_AST = null; - + try { // for error handling Spring.Expressions.PropertyOrFieldNode tmp90_AST = null; tmp90_AST = (Spring.Expressions.PropertyOrFieldNode) astFactory.create(LT(1), "Spring.Expressions.PropertyOrFieldNode"); @@ -2647,14 +2647,14 @@ public void property() //throws RecognitionException, TokenStreamException } returnAST = property_AST; } - + public void argument() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST argument_AST = null; - + try { // for error handling expression(); if (0 == inputState.guessing) @@ -2677,14 +2677,14 @@ public void argument() //throws RecognitionException, TokenStreamException } returnAST = argument_AST; } - + public void quotableName() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST quotableName_AST = null; - + try { // for error handling if ((LA(1)==STRING_LITERAL)) { @@ -2706,7 +2706,7 @@ public void quotableName() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -2722,14 +2722,14 @@ public void quotableName() //throws RecognitionException, TokenStreamException } returnAST = quotableName_AST; } - + public void name() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST name_AST = null; - + try { // for error handling Spring.Expressions.QualifiedIdentifier tmp92_AST = null; tmp92_AST = (Spring.Expressions.QualifiedIdentifier) astFactory.create(LT(1), "Spring.Expressions.QualifiedIdentifier"); @@ -2751,7 +2751,7 @@ public void name() //throws RecognitionException, TokenStreamException { goto _loop78_breakloop; } - + } _loop78_breakloop: ; } // ( ... )* @@ -2771,14 +2771,14 @@ public void name() //throws RecognitionException, TokenStreamException } returnAST = name_AST; } - + public void qualifiedId() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST qualifiedId_AST = null; - + try { // for error handling Spring.Expressions.QualifiedIdentifier tmp94_AST = null; tmp94_AST = (Spring.Expressions.QualifiedIdentifier) astFactory.create(LT(1), "Spring.Expressions.QualifiedIdentifier"); @@ -2802,7 +2802,7 @@ public void qualifiedId() //throws RecognitionException, TokenStreamException { goto _loop114_breakloop; } - + } _loop114_breakloop: ; } // ( ... )* @@ -2822,14 +2822,14 @@ public void qualifiedId() //throws RecognitionException, TokenStreamException } returnAST = qualifiedId_AST; } - + public void ctorArgs() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST ctorArgs_AST = null; - + try { // for error handling match(LPAREN); { @@ -2856,7 +2856,7 @@ public void ctorArgs() //throws RecognitionException, TokenStreamException { goto _loop107_breakloop; } - + } _loop107_breakloop: ; } // ( ... )* @@ -2867,7 +2867,7 @@ public void ctorArgs() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } match(RPAREN); ctorArgs_AST = (Spring.Expressions.SpringAST)currentAST.root; @@ -2886,14 +2886,14 @@ public void ctorArgs() //throws RecognitionException, TokenStreamException } returnAST = ctorArgs_AST; } - + public void argList() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST argList_AST = null; - + try { // for error handling { Spring.Expressions.SpringAST tmp100_AST = null; @@ -2915,7 +2915,7 @@ public void argList() //throws RecognitionException, TokenStreamException { goto _loop87_breakloop; } - + } _loop87_breakloop: ; } // ( ... )* @@ -2947,15 +2947,15 @@ public void argList() //throws RecognitionException, TokenStreamException } returnAST = argList_AST; } - + public void arrayConstructor() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST arrayConstructor_AST = null; Spring.Expressions.SpringAST type_AST = null; - + try { // for error handling match(LITERAL_new); qualifiedId(); @@ -2983,7 +2983,7 @@ public void arrayConstructor() //throws RecognitionException, TokenStreamExcepti { throw new NoViableAltException(LT(1), getFilename()); } - + } if (0==inputState.guessing) { @@ -3012,14 +3012,14 @@ public void arrayConstructor() //throws RecognitionException, TokenStreamExcepti } returnAST = arrayConstructor_AST; } - + public void arrayRank() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST arrayRank_AST = null; - + try { // for error handling Spring.Expressions.SpringAST tmp104_AST = null; tmp104_AST = (Spring.Expressions.SpringAST) astFactory.create(LT(1)); @@ -3049,7 +3049,7 @@ public void arrayRank() //throws RecognitionException, TokenStreamException { goto _loop96_breakloop; } - + } _loop96_breakloop: ; } // ( ... )* @@ -3060,7 +3060,7 @@ public void arrayRank() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } match(RBRACKET); arrayRank_AST = (Spring.Expressions.SpringAST)currentAST.root; @@ -3079,14 +3079,14 @@ public void arrayRank() //throws RecognitionException, TokenStreamException } returnAST = arrayRank_AST; } - + public void mapEntry() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST mapEntry_AST = null; - + try { // for error handling expression(); if (0 == inputState.guessing) @@ -3126,14 +3126,14 @@ public void mapEntry() //throws RecognitionException, TokenStreamException } returnAST = mapEntry_AST; } - + public void namedArgument() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST namedArgument_AST = null; - + try { // for error handling bool synPredMatched111 = false; if (((LA(1)==ID) && (LA(2)==ASSIGN))) @@ -3180,7 +3180,7 @@ public void namedArgument() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -3196,14 +3196,14 @@ public void namedArgument() //throws RecognitionException, TokenStreamException } returnAST = namedArgument_AST; } - + public void boolLiteral() //throws RecognitionException, TokenStreamException { - + returnAST = null; ASTPair currentAST = new ASTPair(); Spring.Expressions.SpringAST boolLiteral_AST = null; - + try { // for error handling if ((LA(1)==TRUE)) { @@ -3224,7 +3224,7 @@ public void boolLiteral() //throws RecognitionException, TokenStreamException { throw new NoViableAltException(LT(1), getFilename()); } - + } catch (RecognitionException ex) { @@ -3240,12 +3240,12 @@ public void boolLiteral() //throws RecognitionException, TokenStreamException } returnAST = boolLiteral_AST; } - + public new Spring.Expressions.SpringAST getAST() { return (Spring.Expressions.SpringAST) returnAST; } - + private void initializeFactory() { if (astFactory == null) @@ -3258,7 +3258,7 @@ static public void initializeASTFactory( ASTFactory factory ) { factory.setMaxNodeType(71); } - + public static readonly string[] tokenNames_ = new string[] { @"""<0>""", @"""EOF""", @@ -3333,7 +3333,7 @@ static public void initializeASTFactory( ASTFactory factory ) @"""SIGN""", @"""REAL_TYPE_SUFFIX""" }; - + private static long[] mk_tokenSet_0_() { long[] data = { 2L, 0L}; @@ -3478,6 +3478,6 @@ private static long[] mk_tokenSet_23_() return data; } public static readonly BitSet tokenSet_23_ = new BitSet(mk_tokenSet_23_()); - + } } diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/ConfigurationReader.cs b/src/Spring/Spring.Core/Objects/Factory/Config/ConfigurationReader.cs index 1dadff8f7..1bc2de2df 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/ConfigurationReader.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/ConfigurationReader.cs @@ -1,14 +1,14 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. - * + * Copyright © 2002-2011 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,11 +41,11 @@ namespace Spring.Objects.Factory.Config { /// - /// Various utility methods for .NET style .config files. + /// Various utility methods for .NET style .config files. /// /// ///

- /// Currently supports reading custom configuration sections and returning them as + /// Currently supports reading custom configuration sections and returning them as /// objects. ///

///
@@ -314,7 +314,7 @@ public static object GetSectionFromXmlDocument(XmlDocument document, string conf if (typeof(IConfigurationSectionHandler).IsAssignableFrom(handlerType)) { IConfigurationSectionHandler handler = (IConfigurationSectionHandler)ObjectUtils.InstantiateType(handlerType); - return ((IConfigurationSectionHandler)handler).Create(null, null, sectionContent); + return handler.Create(null, null, sectionContent); } // NET 2.0 ConfigurationSection @@ -362,7 +362,7 @@ private static Type GetSectionHandlerType(XmlDocument document, string configSec handlerType = defaultConfigurationSectionHandlerType; } } - + if (xmlConfig != null) { XmlAttribute xmlConfigType = xmlConfig.Attributes[ConfigSectionTypeAttribute]; diff --git a/src/Spring/Spring.Core/Objects/Factory/Config/SharedStateAwareProcessor.cs b/src/Spring/Spring.Core/Objects/Factory/Config/SharedStateAwareProcessor.cs index 94f4971d4..56484badd 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Config/SharedStateAwareProcessor.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Config/SharedStateAwareProcessor.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionParserHelper.cs b/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionParserHelper.cs index 1f600838c..1b2b3be69 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionParserHelper.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectDefinitionParserHelper.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ namespace Spring.Objects.Factory.Xml /// /// Stateful class used to parse XML object definitions. /// - /// Not all parsing code has been refactored into this class. See + /// Not all parsing code has been refactored into this class. See /// BeanDefinitionParserDelegate in Java for how this class should evolve. /// Rob Harrop /// Juergen Hoeller @@ -84,7 +84,7 @@ public ObjectDefinitionParserHelper(XmlReaderContext readerContext, XmlElement r } /// - /// Gets the defaults definition object, or null if the + /// Gets the defaults definition object, or null if the /// default have not yet been initialized. /// /// The defaults. @@ -341,7 +341,7 @@ public ObjectDefinitionHolder ParseObjectDefinitionElement(XmlElement element, I { if (aliases.Count > 0) { - objectName = (string) aliases[0]; + objectName = aliases[0]; aliases.RemoveAt(0); if (log.IsDebugEnabled) { @@ -373,9 +373,9 @@ public ObjectDefinitionHolder ParseObjectDefinitionElement(XmlElement element, I objectName = readerContext.GenerateObjectName(definition); // Register an alias for the plain object type name, if possible. string objectTypeName = definition.ObjectTypeName; - if (objectTypeName != null - && objectName.StartsWith(objectTypeName) - && objectName.Length>objectTypeName.Length + if (objectTypeName != null + && objectName.StartsWith(objectTypeName) + && objectName.Length>objectTypeName.Length && !readerContext.Registry.IsObjectNameInUse(objectTypeName)) { aliases.Add(objectTypeName); @@ -543,7 +543,7 @@ public ObjectDefinitionBuilder CreateRootObjectDefinitionBuilder(Type objectType /// Returns the value of the element's attribute or null, if the attribute is not specified. /// /// - /// This is a helper for bypassing the behavior of + /// This is a helper for bypassing the behavior of /// to return if the attribute does not exist. /// public string GetAttributeValue(XmlElement element, string attributeName) @@ -556,11 +556,11 @@ public string GetAttributeValue(XmlElement element, string attributeName) } /// - /// Returns the value of the element's attribute or , + /// Returns the value of the element's attribute or , /// if the attribute is not specified. /// /// - /// This is a helper for bypassing the behavior of + /// This is a helper for bypassing the behavior of /// to return if the attribute does not exist. /// public string GetAttributeValue(XmlElement element, string attributeName, string defaultValue) diff --git a/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectsNamespaceParser.cs b/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectsNamespaceParser.cs index 6495938fa..6aec4f8a7 100644 --- a/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectsNamespaceParser.cs +++ b/src/Spring/Spring.Core/Objects/Factory/Xml/ObjectsNamespaceParser.cs @@ -276,8 +276,8 @@ protected virtual void ParseEventListenerDefinition( case ObjectDefinitionConstants.TypeAttribute: // we're wiring up to a static event exposed on a Type (class) myHandler.Source = parserContext.ReaderContext.Reader.Domain == null ? - (object)sourceAtt.Value : - (object)TypeResolutionUtils.ResolveType(sourceAtt.Value); + sourceAtt.Value : + TypeResolutionUtils.ResolveType(sourceAtt.Value) as object; break; } events.AddHandler(myHandler); @@ -481,7 +481,7 @@ AbstractObjectDefinition od autowire = childParserContext.ParserHelper.Defaults.Autowire; } od.AutowireMode = GetAutowireMode(autowire); - + string autowireCandidates = GetAttributeValue(element, ObjectDefinitionConstants.AutowireCandidateAttribute); if (string.IsNullOrEmpty(autowireCandidates) || ObjectDefinitionConstants.DefaultValue.Equals(autowireCandidates)) { @@ -695,7 +695,7 @@ protected void ParseMetaElements(XmlElement element, ObjectMetadataAttributeAcce ObjectMetadataAttribute attribute = new ObjectMetadataAttribute(key, value); attribute.Source = (XmlElement)node; - attributeAccessor.AddMetadataAttribute(attribute); + attributeAccessor.AddMetadataAttribute(attribute); } } @@ -724,7 +724,7 @@ public void ParseQualifierElement(string name, XmlElement element, ParserContext parserContext.ReaderContext.Resource, name, "Tag 'qualifier' must have a 'type' attribute"); } - + var qualifier = new AutowireCandidateQualifier(typeName); qualifier.Source = element; @@ -1180,7 +1180,7 @@ private bool ParseMergeAttribute(XmlElement collectionElement, ObjectDefinitionP /// /// The set definition. protected Set ParseSetElement(XmlElement collectionEle, string name, ParserContext parserContext) - { + { string elementTypeName = GetAttributeValue(collectionEle, "element-type"); XmlNodeList nl = collectionEle.ChildNodes; ManagedSet target = new ManagedSet(nl.Count); @@ -1556,7 +1556,7 @@ private string GetNamespacePrefix(XmlElement element) // /// Returns the value of the element's attribute or null, if the attribute is not specified. // /// // /// -// /// This is a helper for bypassing the behavior of +// /// This is a helper for bypassing the behavior of // /// to return if the attribute does not exist. // /// // protected static string GetAttributeValue(XmlElement element, string attributeName) @@ -1569,11 +1569,11 @@ private string GetNamespacePrefix(XmlElement element) // } // // /// -// /// Returns the value of the element's attribute or , +// /// Returns the value of the element's attribute or , // /// if the attribute is not specified. // /// // /// -// /// This is a helper for bypassing the behavior of +// /// This is a helper for bypassing the behavior of // /// to return if the attribute does not exist. // /// // protected static string GetAttributeValue(XmlElement element, string attributeName, string defaultValue) diff --git a/src/Spring/Spring.Core/Objects/Support/AutoWiringEventHandlerValue.cs b/src/Spring/Spring.Core/Objects/Support/AutoWiringEventHandlerValue.cs index 8179e9e1b..9a1a58745 100644 --- a/src/Spring/Spring.Core/Objects/Support/AutoWiringEventHandlerValue.cs +++ b/src/Spring/Spring.Core/Objects/Support/AutoWiringEventHandlerValue.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -222,7 +222,7 @@ private void WireEvent(EventInfo theEvent) #endregion IEventHandlerValue myHandler = method.IsStatic ? - (IEventHandlerValue) new StaticEventHandlerValue() : + new StaticEventHandlerValue() : (IEventHandlerValue) new InstanceEventHandlerValue(); myHandler.EventName = theEvent.Name; myHandler.MethodName = method.Name; diff --git a/src/Spring/Spring.Core/Objects/Support/MethodInvoker.cs b/src/Spring/Spring.Core/Objects/Support/MethodInvoker.cs index 3d9350058..04305cef7 100644 --- a/src/Spring/Spring.Core/Objects/Support/MethodInvoker.cs +++ b/src/Spring/Spring.Core/Objects/Support/MethodInvoker.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,7 @@ namespace Spring.Objects.Support /// . ///

///

- /// Usage: specify either the and + /// Usage: specify either the and /// or the /// and /// properties respectively, and @@ -58,13 +58,13 @@ namespace Spring.Objects.Support /// arguments. ///

/// - /// public class Foo + /// public class Foo /// { /// public string ToString(string name, int age, string address) /// { /// return string.Format("{0}, {1} years old, {2}", name, age, address); /// } - /// + /// /// public static void Main() /// { /// Foo foo = new Foo(); @@ -352,7 +352,7 @@ private void PrepareArguments() } // look up the index of where in the prepared args array we're gonna stick the named argument value - int namedArgumentsIndex = (int) argumentNamesToIndexes[argumentName]; + int namedArgumentsIndex = argumentNamesToIndexes[argumentName]; PreparedArguments[namedArgumentsIndex] = argumentValue; // we've prepped this index position, so mark it as so... argumentNamesToIndexes[argumentName] = THE_ARGUMENT_IS_PREPARED; @@ -420,7 +420,7 @@ protected virtual MethodInfo FindTheMethodToInvoke() } if (theMethod == null) { - // search for a method with a matching signature... + // search for a method with a matching signature... ComposedCriteria searchCriteria = new ComposedCriteria(); searchCriteria.Add(new MethodNameMatchCriteria(genericInfo.GenericMethodName)); searchCriteria.Add(new MethodParametersCountCriteria(ArgumentCount)); diff --git a/src/Spring/Spring.Core/Util/NumberUtils.cs b/src/Spring/Spring.Core/Util/NumberUtils.cs index 1e92570a5..db1f5bdd6 100644 --- a/src/Spring/Spring.Core/Util/NumberUtils.cs +++ b/src/Spring/Spring.Core/Util/NumberUtils.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Data.NHibernate/Data/NHibernate/Generic/HibernateTemplate.cs b/src/Spring/Spring.Data.NHibernate/Data/NHibernate/Generic/HibernateTemplate.cs index 1ebfbc21a..c4ee3617c 100644 --- a/src/Spring/Spring.Data.NHibernate/Data/NHibernate/Generic/HibernateTemplate.cs +++ b/src/Spring/Spring.Data.NHibernate/Data/NHibernate/Generic/HibernateTemplate.cs @@ -1,14 +1,14 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. - * + * Copyright � 2002-2011 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -50,18 +50,18 @@ namespace Spring.Data.NHibernate.Generic /// or handling Session lifecycle exceptions. For typical single step actions, /// there are various convenience methods (Find, Load, SaveOrUpdate, Delete). ///

- /// + /// ///

Can be used within a service implementation via direct instantiation /// with a ISessionFactory reference, or get prepared in an application context /// and given to services as an object reference. Note: The ISessionFactory should /// always be configured as an object in the application context, in the first case /// given to the service directly, in the second case to the prepared template. ///

- /// + /// ///

This class can be considered as a direct alternative to working with the raw /// Hibernate Session API (through SessionFactoryUtils.Session). ///

- /// + /// ///

LocalSessionFactoryObject is the preferred way of obtaining a reference /// to a specific NHibernate ISessionFactory. ///

@@ -73,8 +73,8 @@ public class HibernateTemplate : HibernateAccessor, IHibernateOperations #region Fields NHibernate.HibernateTemplate classicHibernateTemplate; - - #endregion + + #endregion #region Constructor (s) @@ -89,25 +89,25 @@ public HibernateTemplate() /// /// Initializes a new instance of the class. /// - /// Allows creation of a new non-transactional session when no + /// Allows creation of a new non-transactional session when no /// transactional Session can be found for the current thread /// The session factory to create sessions. public HibernateTemplate(ISessionFactory sessionFactory) { - classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory); + classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory); AfterPropertiesSet(); } /// /// Initializes a new instance of the class. /// - /// The session factory to create sessions. + /// The session factory to create sessions. /// if set to true allow creation - /// of a new non-transactional session when no transactional Session can be found + /// of a new non-transactional session when no transactional Session can be found /// for the current thread. public HibernateTemplate(ISessionFactory sessionFactory, bool allowCreate) { - classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory, allowCreate); + classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory, allowCreate); AfterPropertiesSet(); } @@ -247,7 +247,7 @@ public override IObjectFactory ObjectFactory } /// - /// Gets or sets a value indicating whether to + /// Gets or sets a value indicating whether to /// cache all queries executed by this template. /// /// @@ -344,7 +344,7 @@ public NHibernate.HibernateTemplate ClassicHibernateTemplate /// /// Gets or sets the proxy factory. /// - /// This may be useful to set if you create many instances of + /// This may be useful to set if you create many instances of /// HibernateTemplate and/or HibernateDaoSupport. This allows the same /// ProxyFactory implementation to be used thereby limiting the /// number of dynamic proxy types created in the temporary assembly, which @@ -362,8 +362,8 @@ public virtual ProxyFactory ProxyFactory #region Properties - - + + #endregion #region Methods @@ -374,7 +374,7 @@ public virtual ProxyFactory ProxyFactory /// public void Clear() { - classicHibernateTemplate.Clear(); + classicHibernateTemplate.Clear(); } @@ -606,13 +606,13 @@ public object SaveOrUpdateCopy(object entity) #endif /// - /// Copy the state of the given object onto the persistent object with the same identifier. + /// Copy the state of the given object onto the persistent object with the same identifier. /// If there is no persistent instance currently associated with the session, it will be loaded. - /// Return the persistent instance. If the given instance is unsaved, + /// Return the persistent instance. If the given instance is unsaved, /// save a copy of and return it as a newly persistent instance. - /// The given instance does not become associated with the session. + /// The given instance does not become associated with the session. /// This operation cascades to associated instances if the association is mapped with cascade="merge". - /// The semantics of this method are defined by JSR-220. + /// The semantics of this method are defined by JSR-220. /// /// The persistent object to merge. /// (not necessarily to be associated with the Hibernate Session) @@ -636,7 +636,7 @@ public object Merge(object entity) /// The object type to get. /// The id of the object to get. /// the persistent instance, or null if not found - /// In case of Hibernate errors + /// In case of Hibernate errors public T Get(object id) { return Get(id, null); @@ -668,7 +668,7 @@ public T Get(object id, LockMode lockMode) /// The object type to load. /// An identifier of the persistent instance. /// The persistent instance - /// If not found + /// If not found /// In case of Hibernate errors public T Load(object id) { @@ -684,8 +684,8 @@ public T Load(object id) /// An identifier of the persistent instance. /// The lock mode. /// The persistent instance - /// If not found - /// In case of Hibernate errors + /// If not found + /// In case of Hibernate errors public T Load(object id, LockMode lockMode) { return Execute(new LoadByTypeHibernateCallback(id, lockMode), true); @@ -715,7 +715,7 @@ public IList LoadAll() /// /// a generic List containing 0 or more persistent instances /// - /// In case of Hibernate errors + /// In case of Hibernate errors public IList Find(string queryString) { return Find(queryString, (object[]) null, (IType[]) null); @@ -731,7 +731,7 @@ public IList Find(string queryString) /// /// a generic List containing 0 or more persistent instances /// - /// In case of Hibernate errors + /// In case of Hibernate errors public IList Find(string queryString, object value) { return Find(queryString, new object[] {value}, (IType[]) null); @@ -748,7 +748,7 @@ public IList Find(string queryString, object value) /// /// a generic List containing 0 or more persistent instances /// - /// In case of Hibernate errors + /// In case of Hibernate errors public IList Find(string queryString, object value, IType type) { return Find(queryString, new object[] {value}, new IType[] {type}); @@ -762,7 +762,7 @@ public IList Find(string queryString, object value, IType type) /// a query expressed in Hibernate's query language /// the values of the parameters /// a generic List containing 0 or more persistent instances - /// In case of Hibernate errors + /// In case of Hibernate errors public IList Find(string queryString, object[] values) { return Find(queryString, values, (IType[]) null); @@ -779,8 +779,8 @@ public IList Find(string queryString, object[] values) /// /// a generic List containing 0 or more persistent instances /// - /// In case of Hibernate errors - /// If values and types are not null and their lengths are not equal + /// In case of Hibernate errors + /// If values and types are not null and their lengths are not equal public IList Find(string queryString, object[] values, IType[] types) { if (values != null && types != null && values.Length != types.Length) @@ -1009,7 +1009,7 @@ public IList FindByNamedQueryAndNamedParam(string queryName, string[] para /// A generic List containing 0 or more persistent instances /// In case of Hibernate errors /// If paramNames length is not equal to values length or - /// if paramNames length is not equal to types length (when types is not null) + /// if paramNames length is not equal to types length (when types is not null) public IList FindByNamedQueryAndNamedParam(string queryName, string[] paramNames, object[] values, IType[] types) { @@ -1050,7 +1050,7 @@ public IList FindByNamedQueryAndValueObject(string queryName, object value /// of the given object to named parameters in the query string. /// /// The object type to find. - /// A query expressed in Hibernate's query language + /// A query expressed in Hibernate's query language /// The values of the parameters /// A generic List containing 0 or more persistent instances /// In case of Hibernate errors diff --git a/src/Spring/Spring.Data.NHibernate/Data/NHibernate/HibernateTemplate.cs b/src/Spring/Spring.Data.NHibernate/Data/NHibernate/HibernateTemplate.cs index df8f2a357..51c7bdc54 100644 --- a/src/Spring/Spring.Data.NHibernate/Data/NHibernate/HibernateTemplate.cs +++ b/src/Spring/Spring.Data.NHibernate/Data/NHibernate/HibernateTemplate.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/src/Spring/Spring.Data.NHibernate/Data/NHibernate/LocalSessionFactoryObject.cs b/src/Spring/Spring.Data.NHibernate/Data/NHibernate/LocalSessionFactoryObject.cs index 7bff9bd90..871c71ab1 100644 --- a/src/Spring/Spring.Data.NHibernate/Data/NHibernate/LocalSessionFactoryObject.cs +++ b/src/Spring/Spring.Data.NHibernate/Data/NHibernate/LocalSessionFactoryObject.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,7 +70,7 @@ namespace Spring.Data.NHibernate /// as autodetected by Spring's /// for AOP-based translation of PersistenceExceptionTranslationPostProcessor. /// Hence, the presence of e.g. LocalSessionFactoryBean automatically enables - /// a PersistenceExceptionTranslationPostProcessor to translate Hibernate exceptions. + /// a PersistenceExceptionTranslationPostProcessor to translate Hibernate exceptions. /// /// /// Mark Pollack (.NET) @@ -117,7 +117,7 @@ public class LocalSessionFactoryObject : IFactoryObject, IInitializingObject, IP private IApplicationContext applicationContext; - // Configuration time DB provider. + // Configuration time DB provider. // This will not be available after configuration has been done. private static IDbProvider configTimeDbProvider; @@ -508,7 +508,7 @@ public virtual void AfterPropertiesSet() IDictionary typedProperties = new Dictionary(); foreach (KeyValuePair entry in hibernateProperties) { - typedProperties.Add((string) entry.Key, (string) entry.Value); + typedProperties.Add(entry.Key, entry.Value); } Dialect dialect = Dialect.GetDialect(typedProperties); @@ -545,7 +545,7 @@ public virtual void AfterPropertiesSet() log.Info("Overriding use of Spring's Hibernate Connection Provider with [" + hibernateProperties[Environment.ConnectionProvider] + "]"); } - #endregion + #endregion config.Properties.Remove(Environment.ConnectionProvider); } @@ -625,7 +625,7 @@ public virtual void AfterPropertiesSet() } } - if (this.eventListeners != null) + if (this.eventListeners != null) { // Register specified NHibernate event listeners. foreach (DictionaryEntry entry in eventListeners) @@ -641,7 +641,7 @@ public virtual void AfterPropertiesSet() } object listenerObject = entry.Value; - if (listenerObject is ICollection) + if (listenerObject is ICollection) { ICollection listeners = (ICollection) listenerObject; EventListeners listenerRegistry = config.EventListeners; @@ -651,7 +651,7 @@ public virtual void AfterPropertiesSet() object[] listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType)); config.SetListeners(listenerType, listenerArray); } - else + else { config.SetListener(listenerType, listenerObject); } @@ -694,8 +694,8 @@ public void Dispose() if (log.IsInfoEnabled) { log.Info("Closing Hibernate SessionFactory"); - } - #endregion + } + #endregion sessionFactory.Close(); } @@ -753,7 +753,7 @@ protected virtual void AfterSessionFactoryCreation() UpdateDatabaseSchema(); } } - + /// /// Execute schema drop script, determined by the Configuration object /// used for creating the SessionFactory. A replacement for NHibernate's @@ -781,7 +781,7 @@ public void DropDatabaseSchema() ExecuteSchemaScript(con, sql); return null; })); - + } /// @@ -810,8 +810,8 @@ public void CreateDatabaseSchema() string[] sql = Configuration.GenerateSchemaCreationScript(dialect); ExecuteSchemaScript(con, sql); return null; - - })); + + })); } /// @@ -829,7 +829,7 @@ public void CreateDatabaseSchema() /// connection to perform the script. ///

/// - public virtual void UpdateDatabaseSchema() + public virtual void UpdateDatabaseSchema() { log.Info("Updating database schema for Hibernate SessionFactory"); HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory); @@ -859,17 +859,17 @@ public virtual void UpdateDatabaseSchema() /// The SQL statement to execute. protected virtual void ExecuteSchemaScript(IDbConnection con, string[] sql) { - if (sql != null && sql.Length > 0) + if (sql != null && sql.Length > 0) { IDbCommand cmd = con.CreateCommand(); - try + try { - for (int i = 0; i < sql.Length; i++) + for (int i = 0; i < sql.Length; i++) { ExecuteSchemaStatement(cmd, sql[i]); } } - finally + finally { AdoUtils.DisposeCommand(cmd); } @@ -887,18 +887,18 @@ protected virtual void ExecuteSchemaScript(IDbConnection con, string[] sql) /// protected virtual void ExecuteSchemaStatement(IDbCommand cmd, string sql) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled) { log.Debug("Executing schema statement: " + sql); } - try + try { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } - catch (ADOException ex) + catch (ADOException ex) { - if (log.IsWarnEnabled) + if (log.IsWarnEnabled) { log.Warn("Unsuccessful schema statement: " + sql, ex); } @@ -921,7 +921,7 @@ protected virtual ISessionFactory NewSessionFactory(Configuration config) { ISessionFactory sf = config.BuildSessionFactory(); ISessionFactoryImplementor sfImplementor = sf as ISessionFactoryImplementor; - + if (sfImplementor != null) { DbProviderWrapper dbProviderWrapper = sfImplementor.ConnectionProvider as DbProviderWrapper; @@ -997,7 +997,7 @@ public override IDbConnection GetConnection() /// /// public DataAccessException TranslateExceptionIfPossible(Exception ex) - { + { if (ex is HibernateException) { return ConvertHibernateException((HibernateException) ex); @@ -1032,7 +1032,7 @@ protected virtual DataAccessException ConvertHibernateException(HibernateExcepti /// protected virtual DataAccessException ConvertAdoAccessException(ADOException ex) { - return SessionFactoryUtils.ConvertAdoAccessException(AdoExceptionTranslator, ex); + return SessionFactoryUtils.ConvertAdoAccessException(AdoExceptionTranslator, ex); } #endregion diff --git a/src/Spring/Spring.Web/Web/UI/Controls/ContentReplacer.cs b/src/Spring/Spring.Web/Web/UI/Controls/ContentReplacer.cs index b6aa6ca2a..c170b7b1c 100644 --- a/src/Spring/Spring.Web/Web/UI/Controls/ContentReplacer.cs +++ b/src/Spring/Spring.Web/Web/UI/Controls/ContentReplacer.cs @@ -36,11 +36,11 @@ namespace Spring.Web.UI.Controls /// within the page. /// /// - /// In contrast to control, ContentReplacer can replace the content of + /// In contrast to control, ContentReplacer can replace the content of /// any control within the current page - it is not limited to replacing ContentPlaceholders on master pages. /// /// - /// This technique is useful if you want to group e.g. rendering navigation elements on 1 ascx control, but your + /// This technique is useful if you want to group e.g. rendering navigation elements on 1 ascx control, but your /// design requires navigation elements to be distributed across different places within the HTML code. /// /// @@ -71,7 +71,7 @@ protected override void OnPreRender(EventArgs e) if (!Visible) return; //log.Debug(string.Format("OnPreRender Content['{0}']", this.contentPlaceHolderID)); - Control ctlRoot = (this.Page.Master != null) ? (Control)this.Page.Master : (Control)this.Page; + Control ctlRoot = Page.Master != null ? Page.Master : (Control) Page; Control ctl = ctlRoot.FindControl(this.contentPlaceHolderID); if (ctl != null) @@ -120,7 +120,7 @@ private void RenderNothing(HtmlTextWriter output, Control container) private static readonly PropertyInfo piRareFieldsEnsured = typeof(Control).GetProperty("RareFieldsEnsured", BindingFlags.NonPublic | BindingFlags.Instance); - private static readonly FieldInfo fiRenderMethod = + private static readonly FieldInfo fiRenderMethod = typeof(Control).GetNestedType("ControlRareFields",BindingFlags.NonPublic).GetField("RenderMethod"); private RenderMethod GetRenderMethod() diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 110b81d44..88ada2da0 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -22,7 +22,7 @@ 3.10.1 3.10.0 - 3.6.1 + 4.8.1 15.7.2 True @@ -36,6 +36,7 @@ + Full DEBUG;TRACE;$(DefineConstants) diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/AbstractMethodInvocationTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/AbstractMethodInvocationTests.cs index 36610422d..1f6af64c6 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/AbstractMethodInvocationTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/AbstractMethodInvocationTests.cs @@ -18,18 +18,16 @@ #endregion -#region Imports - using System; using System.Collections; using System.Globalization; using System.Reflection; using AopAlliance.Intercept; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Aop.Framework { @@ -41,16 +39,13 @@ namespace Spring.Aop.Framework [TestFixture] public abstract class AbstractMethodInvocationTests { - private MockRepository mocks; - [SetUp] public virtual void SetUp() { - mocks = new MockRepository(); } protected abstract AbstractMethodInvocation CreateMethodInvocation( - object proxy, object target, MethodInfo method, MethodInfo onProxyMethod, + object proxy, object target, MethodInfo method, MethodInfo onProxyMethod, object[] arguments, Type targetType, IList interceptors); [Test] @@ -178,7 +173,7 @@ public void ValidInvocation() IMethodInterceptor interceptor = (IMethodInterceptor) repository.CreateMock(typeof (IMethodInterceptor)); AbstractMethodInvocation join = CreateMethodInvocation( null, target, target.GetTargetMethodNoArgs(), null, null, target.GetType(), new object[] { interceptor }); - Expect.Call(interceptor.Invoke(join)).Return(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture)); + Expect.Call(interceptor.Invoke(join)).Returns(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture)); repository.ReplayAll(); string score = (string) join.Proceed(); Assert.AreEqual(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture) + Target.Suffix, score); @@ -186,18 +181,14 @@ public void ValidInvocation() */ Target target = new Target(); - IMethodInterceptor mock = (IMethodInterceptor) mocks.CreateMock(typeof(IMethodInterceptor)); + IMethodInterceptor mock = A.Fake(); AbstractMethodInvocation join = CreateMethodInvocation( null, target, target.GetTargetMethodNoArgs(), null, null, target.GetType(), new object[] { mock }); - - Expect.Call(mock.Invoke(null)).IgnoreArguments().Return(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture)); - mocks.ReplayAll(); + + A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Returns(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture)); string score = (string) join.Proceed(); Assert.AreEqual(Target.DefaultScore.ToLower(CultureInfo.InvariantCulture) + Target.Suffix, score); - - mocks.VerifyAll(); - } [Test] @@ -222,53 +213,30 @@ public void UnwrapsTargetInvocationException_NoInterceptors() [Test] public void UnwrapsTargetInvocationException_WithInterceptor() - { - BadCommand target = new BadCommand(); - IMethodInterceptor mock = (IMethodInterceptor) mocks.CreateMock(typeof(IMethodInterceptor)); - AbstractMethodInvocation join = CreateMethodInvocation( - null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] { mock }); - - Expect.Call(mock.Invoke(null)).IgnoreArguments().Return(null); - mocks.ReplayAll(); + { + BadCommand target = new BadCommand(); + IMethodInterceptor mock = A.Fake(); + AbstractMethodInvocation join = CreateMethodInvocation( + null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] {mock}); - try - { - join.Proceed(); - } - catch (NotImplementedException) - { - // this is good, we want this exception to bubble up... - } - catch (TargetInvocationException) - { - Assert.Fail("Must have unwrapped this."); - } - mocks.VerifyAll(); - } + A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Throws(); - [Test] + // we want this exception to bubble up... + Assert.Throws(() => join.Proceed()); + } + + [Test] public void UnwrapsTargetInvocationException_WithInterceptorThatThrowsAnException() { BadCommand target = new BadCommand(); - IMethodInterceptor mock = (IMethodInterceptor) mocks.CreateMock(typeof(IMethodInterceptor)); + IMethodInterceptor mock = A.Fake(); AbstractMethodInvocation join = CreateMethodInvocation( null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] { mock }); - Expect.Call(mock.Invoke(null)).IgnoreArguments().Throw(new NotImplementedException()); - mocks.ReplayAll(); - try - { - join.Proceed(); - } - catch (NotImplementedException) - { - // this is good, we want this exception to bubble up... - } - catch (TargetInvocationException) - { - Assert.Fail("Must have unwrapped this."); - } - mocks.VerifyAll(); + A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Throws(); + + // we want this exception to bubble up... + Assert.Throws(() => join.Proceed()); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/AfterReturningAdviceInterceptorTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/AfterReturningAdviceInterceptorTests.cs index 880fb01a5..ca3cb116e 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/AfterReturningAdviceInterceptorTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/AfterReturningAdviceInterceptorTests.cs @@ -18,48 +18,41 @@ #endregion -#region Imports - using System; + using AopAlliance.Intercept; +using FakeItEasy; using NUnit.Framework; -using Rhino.Mocks; -using Spring.Util; -#endregion +using Spring.Util; namespace Spring.Aop.Framework.Adapter { - /// - /// Unit tests for the AfterReturningAdviceInterceptor class. - /// - /// Rod Johnson - /// Simon White (.NET) - [TestFixture] - public sealed class AfterReturningAdviceInterceptorTests - { - [Test] - public void PassNullAdviceToCtor() - { + /// + /// Unit tests for the AfterReturningAdviceInterceptor class. + /// + /// Rod Johnson + /// Simon White (.NET) + [TestFixture] + public sealed class AfterReturningAdviceInterceptorTests + { + [Test] + public void PassNullAdviceToCtor() + { Assert.Throws(() => new AfterReturningAdviceInterceptor(null)); - } + } - [Test] - public void IsNotInvokedIfServiceObjectThrowsException() - { - MockRepository repository = new MockRepository(); - IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); - IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice)repository.CreateMock(typeof(IAfterReturningAdvice)); - mockAdvice.AfterReturning(null, null, null, null); - LastCall.IgnoreArguments(); - LastCall.Throw(new FormatException()); + [Test] + public void IsNotInvokedIfServiceObjectThrowsException() + { + IMethodInvocation mockInvocation = A.Fake(); + IAfterReturningAdvice mockAdvice = A.Fake(); - Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { })); - Expect.Call(mockInvocation.Arguments).Return(null); - Expect.Call(mockInvocation.This).Return(new object()); - Expect.Call(mockInvocation.Proceed()).Return(null); - - repository.ReplayAll(); + A.CallTo(() => mockAdvice.AfterReturning(null, null, null, null)).WithAnyArguments().Throws(); + A.CallTo(() => mockInvocation.Method).Returns(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { })); + A.CallTo(() => mockInvocation.Arguments).Returns(null); + A.CallTo(() => mockInvocation.This).Returns(new object()); + A.CallTo(() => mockInvocation.Proceed()).Returns(null); try { @@ -70,29 +63,19 @@ public void IsNotInvokedIfServiceObjectThrowsException() catch (FormatException) { } - - repository.VerifyAll(); - - } - - [Test] - public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping() - { - - MockRepository repository = new MockRepository(); - IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); - IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice) repository.CreateMock(typeof (IAfterReturningAdvice)); - mockAdvice.AfterReturning(null,null,null,null); - LastCall.IgnoreArguments(); - LastCall.Throw(new FormatException()); - - Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { })); - Expect.Call(mockInvocation.Arguments).Return(null); - Expect.Call(mockInvocation.This).Return(new object()); - Expect.Call(mockInvocation.Proceed()).Return(null); - - repository.ReplayAll(); - + } + + [Test] + public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping() + { + IMethodInvocation mockInvocation = A.Fake(); + IAfterReturningAdvice mockAdvice = A.Fake(); + A.CallTo(() => mockAdvice.AfterReturning(null, null, null, null)).WithAnyArguments().Throws(); + + A.CallTo(() => mockInvocation.Method).Returns(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { })); + A.CallTo(() => mockInvocation.Arguments).Returns(null); + A.CallTo(() => mockInvocation.This).Returns(new object()); + A.CallTo(() => mockInvocation.Proceed()).Returns(null); try { AfterReturningAdviceInterceptor interceptor = new AfterReturningAdviceInterceptor(mockAdvice); @@ -102,12 +85,6 @@ public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping() catch (FormatException) { } - repository.VerifyAll(); - - - - - - } - } + } + } } \ No newline at end of file diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/ThrowsAdviceInterceptorTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/ThrowsAdviceInterceptorTests.cs index 86d68e777..38c1badb5 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/ThrowsAdviceInterceptorTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/Adapter/ThrowsAdviceInterceptorTests.cs @@ -18,18 +18,18 @@ #endregion -#region Imports - using System; using System.Reflection; using System.Runtime.Remoting; using System.Web; + using AopAlliance.Intercept; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; -using Spring.Util; -#endregion +using Spring.Util; namespace Spring.Aop.Framework.Adapter { @@ -56,21 +56,16 @@ public void PassNullAdviceToCtor() [Test] public void NotInvoked() { - MockRepository repository = new MockRepository(); - IMethodInvocation mi = (IMethodInvocation) repository.CreateMock(typeof (IMethodInvocation)); + IMethodInvocation mi = A.Fake(); MyThrowsHandler th = new MyThrowsHandler(); ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); object ret = new object(); - Expect.Call(mi.Proceed()).Return(ret); - repository.ReplayAll(); + A.CallTo(() => mi.Proceed()).Returns(ret); + Assert.AreEqual(ret, ti.Invoke(mi)); Assert.AreEqual(0, th.GetCalls()); - repository.VerifyAll(); - - - } [Test] @@ -81,10 +76,9 @@ public void NoHandlerMethodForThrowable() Assert.AreEqual(2, ti.HandlerMethodCount); Exception ex = new Exception(); - MockRepository repository = new MockRepository(); - IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); - Expect.Call(mi.Proceed()).Throw(ex); - repository.ReplayAll(); + IMethodInvocation mi = A.Fake(); + A.CallTo(() => mi.Proceed()).Throws(ex); + try { ti.Invoke(mi); @@ -95,8 +89,6 @@ public void NoHandlerMethodForThrowable() Assert.AreEqual(ex, caught); } Assert.AreEqual(0, th.GetCalls()); - repository.VerifyAll(); - } [Test] @@ -107,14 +99,13 @@ public void CorrectHandlerUsed() ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th); HttpException ex = new HttpException(); - MockRepository repository = new MockRepository(); - IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); + IMethodInvocation mi = A.Fake(); + + A.CallTo(() => mi.Method).Returns(ReflectionUtils.GetMethod(typeof (object), "HashCode", new Type[] {})); + A.CallTo(() => mi.Arguments).Returns(null); + A.CallTo(() => mi.This).Returns(new object()); + A.CallTo(() => mi.Proceed()).Throws(ex); - Expect.Call(mi.Method).Return(ReflectionUtils.GetMethod(typeof (object), "HashCode", new Type[] {})); - Expect.Call(mi.Arguments).Return(null); - Expect.Call(mi.This).Return(new object()); - Expect.Call(mi.Proceed()).Throw(ex); - repository.ReplayAll(); try { ti.Invoke(mi); @@ -126,9 +117,6 @@ public void CorrectHandlerUsed() } Assert.AreEqual(1, th.GetCalls()); Assert.AreEqual(1, th.GetCalls("HttpException")); - - repository.VerifyAll(); - } [Test] @@ -138,10 +126,10 @@ public void NestedInnerExceptionsAreNotPickedUp() ThrowsAdviceInterceptor throwsInterceptor = new ThrowsAdviceInterceptor(throwsHandler); // nest the exceptions; make sure the advice gets applied because of the inner exception... Exception exception = new FormatException("Parent", new HttpException("Inner")); - MockRepository repository = new MockRepository(); - IMethodInvocation invocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); - Expect.Call(invocation.Proceed()).Throw(exception); - repository.ReplayAll(); + + IMethodInvocation invocation = A.Fake(); + A.CallTo(() => invocation.Proceed()).Throws(exception); + try { throwsInterceptor.Invoke(invocation); @@ -157,8 +145,7 @@ public void NestedInnerExceptionsAreNotPickedUp() Assert.AreEqual(0, throwsHandler.GetCalls("HttpException"), "Similarly, must NOT have been handled, 'cos the HttpException was wrapped by " + "another Exception that did not have a handler."); - repository.VerifyAll(); - } + } [Test] public void ChokesOnHandlerWhereMultipleMethodsAreApplicable() @@ -175,10 +162,9 @@ public void CorrectHandlerUsedForSubclass() // Extends RemotingException RemotingTimeoutException ex = new RemotingTimeoutException(); - MockRepository repository = new MockRepository(); - IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); - Expect.Call(mi.Proceed()).Throw(ex); - repository.ReplayAll(); + IMethodInvocation mi = A.Fake(); + A.CallTo(() => mi.Proceed()).Throws(ex); + try { ti.Invoke(mi); @@ -190,8 +176,6 @@ public void CorrectHandlerUsedForSubclass() } Assert.AreEqual(1, th.GetCalls()); Assert.AreEqual(1, th.GetCalls("RemotingException")); - - repository.VerifyAll(); } [Test] @@ -200,13 +184,10 @@ public void HandlerMethodThrowsException() Exception exception = new Exception(); MyThrowsHandler handler = new ThrowingMyHandler(exception); ThrowsAdviceInterceptor interceptor = new ThrowsAdviceInterceptor(handler); - // extends RemotingException... - RemotingTimeoutException ex = new RemotingTimeoutException(); - MockRepository repository = new MockRepository(); - IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation)); - Expect.Call(mi.Proceed()).Throw(ex); - repository.ReplayAll(); + IMethodInvocation mi = A.Fake(); + A.CallTo(() => mi.Proceed()).Throws(new RemotingTimeoutException()); + try { interceptor.Invoke(mi); @@ -217,9 +198,7 @@ public void HandlerMethodThrowsException() Assert.AreEqual(exception, caught); } Assert.AreEqual(1, handler.GetCalls()); - Assert.AreEqual(1, handler.GetCalls("RemotingException")); - repository.VerifyAll(); - + Assert.AreEqual(1, handler.GetCalls("RemotingException")); } #region Helper Classes diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AbstractAopProxyTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AbstractAopProxyTests.cs index c7229e632..bb7485294 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AbstractAopProxyTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AbstractAopProxyTests.cs @@ -18,8 +18,6 @@ #endregion -#region Imports - using System; using System.IO; using System.Runtime.Serialization; @@ -32,7 +30,9 @@ using AopAlliance.Aop; using AopAlliance.Intercept; -using Rhino.Mocks; + +using FakeItEasy; + using Spring.Aop.Framework.Adapter; using Spring.Aop.Interceptor; using Spring.Aop.Support; @@ -44,8 +44,6 @@ using NUnit.Framework; -#endregion - namespace Spring.Aop.Framework.DynamicProxy { /// @@ -288,19 +286,19 @@ public string Company [Test(Description = "http://jira.springframework.org/browse/SPRNET-1174")] public void ImplementsInterfaceHierarchy() { - IMethodInterceptor mi = MockRepository.GenerateMock(); + IMethodInterceptor mi = A.Fake(); - mi.Stub(x => x.Invoke(Arg.Is.NotNull)).Return((long)5).Repeat.Once(); - mi.Stub(x => x.Invoke(Arg.Is.NotNull)).Return("Customer Name").Repeat.Once(); - mi.Stub(x => x.Invoke(Arg.Is.NotNull)).Return("Customer Company").Repeat.Once(); + A.CallTo(() => mi.Invoke(A.That.Matches(x => x.Method.Name == "get_Id"))).Returns((long) 5).Once(); + A.CallTo(() => mi.Invoke(A.That.Matches(x => x.Method.Name == "get_Name"))).Returns("Customer Name").Once(); + A.CallTo(() => mi.Invoke(A.That.Matches(x => x.Method.Name == "get_Company"))).Returns("Customer Company").Once(); AdvisedSupport advised = new AdvisedSupport(); advised.AddAdvice(mi); - advised.Interfaces = new Type[] { typeof(ITestCustomer) }; + advised.Interfaces = new[] { typeof(ITestCustomer) }; ITestCustomer to = CreateProxy(advised) as ITestCustomer; Assert.IsNotNull(to); - Assert.AreEqual((long)5, to.Id, "Incorrect Id"); + Assert.AreEqual((long) 5, to.Id, "Incorrect Id"); Assert.AreEqual("Customer Name", to.Name, "Incorrect Name"); Assert.AreEqual("Customer Company", to.Company, "Incorrect Company"); } @@ -407,8 +405,8 @@ public void NoInterceptorWithNoTarget() public void InterceptorHandledCallWithNoTarget() { int age = 26; - IMethodInterceptor mock = MockRepository.GenerateMock(); - mock.Stub(x => x.Invoke(Arg.Is.NotNull)).Return(age); + IMethodInterceptor mock = A.Fake(); + A.CallTo(() => mock.Invoke(A.That.Not.IsNull())).Returns(age); AdvisedSupport advised = new AdvisedSupport(); advised.AddAdvice(mock); diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AopUtilsTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AopUtilsTests.cs index 7431b9021..114afaa68 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AopUtilsTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/DynamicProxy/AopUtilsTests.cs @@ -18,20 +18,18 @@ #endregion -#region Imports - using System; using System.Collections; using System.Reflection; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Aop.Interceptor; using Spring.Aop.Support; using Spring.Collections; using Spring.Objects; -#endregion - namespace Spring.Aop.Framework.DynamicProxy { /// @@ -42,12 +40,9 @@ namespace Spring.Aop.Framework.DynamicProxy [TestFixture] public sealed class AopUtilsTests { - private MockRepository mocks; - [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] @@ -80,17 +75,17 @@ public void PointcutAppliesToOneInterfaceOfSeveral() { IPointcut pointcut = new OneInterfaceTestPointcut(); - // Will return true if we're proxying interfaces including ITestObject + // Will return true if we're proxying interfaces including ITestObject Assert.IsTrue(AopUtils.CanApply(pointcut, typeof (TestObject), new Type[] {typeof (ITestObject), typeof (IComparable)})); - // Will return true if we're proxying interfaces including ITestObject + // Will return true if we're proxying interfaces including ITestObject Assert.IsFalse(AopUtils.CanApply(pointcut, typeof (TestObject), new Type[] {typeof (IComparable)})); } [Test] public void CanApplyWithAdvisorYieldsTrueIfAdvisorIsNotKnownAdvisorType() { - IAdvisor advisor = (IAdvisor) mocks.CreateMock(typeof (IAdvisor)); + IAdvisor advisor = A.Fake(); Assert.IsTrue(AopUtils.CanApply(advisor, typeof (TestObject), null)); } @@ -171,12 +166,10 @@ public void GetAllInterfacesWithObjectThatInheritsInterfaces() [Test] public void CanApplyWithTrueIntroductionAdvisor() { - IIntroductionAdvisor mockIntroAdvisor = (IIntroductionAdvisor) mocks.CreateMock(typeof(IIntroductionAdvisor)); - Expect.Call(mockIntroAdvisor.TypeFilter).Return(TrueTypeFilter.True); - mocks.ReplayAll(); + IIntroductionAdvisor mockIntroAdvisor = A.Fake(); + A.CallTo(() => mockIntroAdvisor.TypeFilter).Returns(TrueTypeFilter.True); Assert.IsTrue(AopUtils.CanApply(mockIntroAdvisor, typeof (TestObject), null)); - mocks.VerifyAll(); } #region Helper Classes diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryObjectTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryObjectTests.cs index 89d352bcd..f3a9ce3fd 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryObjectTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryObjectTests.cs @@ -31,8 +31,10 @@ using AopAlliance.Aop; using AopAlliance.Intercept; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Aop.Advice; using Spring.Aop.Framework.Adapter; using Spring.Aop.Interceptor; @@ -61,17 +63,14 @@ namespace Spring.Aop.Framework [TestFixture] public sealed class ProxyFactoryObjectTests { - private MockRepository mocks; private IObjectFactory factory; [SetUp] public void SetUp() { - mocks = new MockRepository(); factory = new XmlObjectFactory(new ReadOnlyXmlTestResource("proxyFactoryTests.xml", GetType())); } - [Test] public void TargetThrowsInvalidCastException() { @@ -477,9 +476,8 @@ public void GlobalsCanAddAspectInterfaces() public void IsSingletonFalseReturnsNew_ProxyInstance_NotNewProxyTargetSource() { GoodCommand target = new GoodCommand(); - IObjectFactory mock = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory)); - Expect.Call(mock.GetObject("singleton")).Return(target).Repeat.Twice(); - mocks.ReplayAll(); + IObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObject("singleton")).Returns(target).Twice(); ProxyFactoryObject fac = new ProxyFactoryObject(); fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName }; @@ -491,17 +489,14 @@ public void IsSingletonFalseReturnsNew_ProxyInstance_NotNewProxyTargetSource() ICommand one = (ICommand)fac.GetObject(); ICommand two = (ICommand)fac.GetObject(); Assert.IsFalse(ReferenceEquals(one, two)); - - mocks.VerifyAll(); } [Test] public void IsSingletonTrueReturnsNew_ProxyInstance_NotNewProxyTargetSource() { GoodCommand target = new GoodCommand(); - IObjectFactory mock = (IObjectFactory)mocks.CreateMock(typeof(IObjectFactory)); - Expect.Call(mock.GetObject("singleton")).Return(target); - mocks.ReplayAll(); + IObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObject("singleton")).Returns(target); ProxyFactoryObject fac = new ProxyFactoryObject(); fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName }; @@ -513,8 +508,6 @@ public void IsSingletonTrueReturnsNew_ProxyInstance_NotNewProxyTargetSource() ICommand one = (ICommand)fac.GetObject(); ICommand two = (ICommand)fac.GetObject(); Assert.IsTrue(ReferenceEquals(one, two)); - - mocks.VerifyAll(); } private ProxyFactoryObject CreateFrozenProxyFactory() @@ -562,11 +555,10 @@ public void TargetAtEndOfInterceptorList() GoodCommand target = new GoodCommand(); NopInterceptor advice = new NopInterceptor(); - IObjectFactory mock = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory)); - Expect.Call(mock.GetObject("advice")).Return(advice); - Expect.Call(mock.GetObject("singleton")).Return(target); - Expect.Call(mock.GetType("singleton")).Return(typeof(GoodCommand)); - mocks.ReplayAll(); + IObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObject("advice")).Returns(advice); + A.CallTo(() => mock.GetObject("singleton")).Returns(target); + A.CallTo(() => mock.GetType("singleton")).Returns(typeof(GoodCommand)); ProxyFactoryObject fac = new ProxyFactoryObject(); fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName }; @@ -581,8 +573,6 @@ public void TargetAtEndOfInterceptorList() Assert.AreEqual(1, advice.Count); two.Execute(); Assert.AreEqual(2, advice.Count); - - mocks.VerifyAll(); } [Test] @@ -591,32 +581,20 @@ public void MakeSurePrototypeTargetIsNotNeedlesslyCreatedDuringInitialization_Un GoodCommand target = new GoodCommand(); NopInterceptor advice = new NopInterceptor(); - MockRepository mocks = new MockRepository(); - IObjectFactory factory = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory)); + IObjectFactory factory = A.Fake(); ProxyFactoryObject fac = new ProxyFactoryObject(); - fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName }; + fac.ProxyInterfaces = new[] {typeof(ICommand).FullName}; fac.IsSingleton = false; - fac.InterceptorNames = new string[] { "advice", "prototype" }; + fac.InterceptorNames = new[] {"advice", "prototype"}; fac.ObjectFactory = factory; -// using (mocks.Record()) - { - using (mocks.Unordered()) - { - Expect.Call(factory.IsSingleton("advice")).Return(true); - Expect.Call(factory.GetObject("advice")).Return(advice); - Expect.Call(factory.GetType("prototype")).Return(target.GetType()); - Expect.Call(factory.GetObject("prototype")).Return(target); - } - } - mocks.ReplayAll(); + A.CallTo(() => factory.IsSingleton("advice")).Returns(true); + A.CallTo(() => factory.GetObject("advice")).Returns(advice); + A.CallTo(() => factory.GetType("prototype")).Returns(target.GetType()); + A.CallTo(() => factory.GetObject("prototype")).Returns(target); -// using(mocks.Playback()) - { - fac.GetObject(); - } - mocks.VerifyAll(); + fac.GetObject(); } [Test] @@ -706,26 +684,20 @@ public void Execute() [Test] public void NullNameInInterceptorNamesArrayThrowAopConfigException() { - IObjectFactory factory = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory)); + IObjectFactory factory = A.Fake(); ProxyFactoryObject fac = new ProxyFactoryObject(); fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName }; fac.IsSingleton = false; fac.InterceptorNames = new string[] { null, null }; fac.ObjectFactory = factory; - try - { - fac.GetObject(); - Assert.Fail(); - } - catch (AopConfigException) - {} + Assert.Throws(() => fac.GetObject()); } [Test] public void PassEmptyInterceptorNamesArray_WithTargetThatImplementsAnInterfaceCanBeCastToSaidInterface() { - IObjectFactory factory = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory)); + IObjectFactory factory = A.Fake(); ProxyFactoryObject fac = new ProxyFactoryObject(); fac.ProxyInterfaces = new string[] { }; diff --git a/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryTests.cs index 7987ea7d4..cc54de186 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Framework/ProxyFactoryTests.cs @@ -18,21 +18,19 @@ #endregion -#region Imports - using System; using System.Runtime.Serialization; using AopAlliance.Aop; using AopAlliance.Intercept; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Aop.Interceptor; using Spring.Aop.Support; using Spring.Objects; using Spring.Util; -#endregion - namespace Spring.Aop.Framework { /// @@ -44,15 +42,6 @@ namespace Spring.Aop.Framework [TestFixture] public sealed class ProxyFactoryTests { - - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - public interface IDoubleClickable { event EventHandler DoubleClick; @@ -132,7 +121,7 @@ public void CacheTest() object proxy = pf.GetProxy(); } - // fails when running in resharper/testdriven.net + // fails when running in resharper/testdriven.net // DynamicProxyManager.SaveAssembly(); } @@ -523,24 +512,21 @@ public void AddAdvisedSupportListener() //MLP SPRNET-1367 //IDynamicMock mock = new DynamicMock(typeof(IAdvisedSupportListener)); //IAdvisedSupportListener listener = (IAdvisedSupportListener)mock.Object; - IAdvisedSupportListener listener = - (IAdvisedSupportListener) mocks.CreateMock(typeof (IAdvisedSupportListener)); - listener.Activated(null); - LastCall.On(listener).IgnoreArguments(); + IAdvisedSupportListener listener = A.Fake(); //listener.Activated(); //mock.Expect("Activated"); - mocks.ReplayAll(); ProxyFactory factory = new ProxyFactory(new TestObject()); factory.AddListener(listener); factory.GetProxy(); - mocks.VerifyAll(); + + A.CallTo(() => listener.Activated(A._)).MustHaveHappened(); } [Test] public void AdvisedSupportListenerMethodsAreCalledAppropriately() { - IAdvisedSupportListener listener = MockRepository.GenerateMock(); + IAdvisedSupportListener listener = A.Fake(); ProxyFactory factory = new ProxyFactory(new TestObject()); factory.AddListener(listener); @@ -552,15 +538,15 @@ public void AdvisedSupportListenerMethodsAreCalledAppropriately() // must fire the InterfacesChanged callback... factory.AddInterface(typeof(ISerializable)); - listener.AssertWasCalled(x => x.Activated(Arg.Is.NotNull)); - listener.AssertWasCalled(x => x.AdviceChanged(Arg.Is.NotNull)); - listener.AssertWasCalled(x => x.InterfacesChanged(Arg.Is.NotNull)); + A.CallTo(() => listener.Activated(A.That.Not.IsNull())).MustHaveHappened(); + A.CallTo(() => listener.AdviceChanged(A.That.Not.IsNull())).MustHaveHappened(); + A.CallTo(() => listener.InterfacesChanged(A.That.Not.IsNull())).MustHaveHappened(); } [Test] public void AdvisedSupportListenerMethodsAre_NOT_CalledIfProxyHasNotBeenCreated() { - IAdvisedSupportListener listener = MockRepository.GenerateMock(); + IAdvisedSupportListener listener = A.Fake(); ProxyFactory factory = new ProxyFactory(new TestObject()); factory.AddListener(listener); @@ -570,8 +556,8 @@ public void AdvisedSupportListenerMethodsAre_NOT_CalledIfProxyHasNotBeenCreated( // must not fire the InterfacesChanged callback... factory.AddInterface(typeof(ISerializable)); - listener.AssertWasNotCalled(x => x.AdviceChanged(Arg.Is.Anything)); - listener.AssertWasNotCalled(x => x.InterfacesChanged(Arg.Is.Anything)); + A.CallTo(() => listener.AdviceChanged(A._)).MustNotHaveHappened(); + A.CallTo(() => listener.InterfacesChanged(A._)).MustNotHaveHappened(); } [Test] @@ -591,7 +577,7 @@ public void RemoveNullAdvisedSupportListenerIsOk() [Test] public void RemoveAdvisedSupportListener() { - IAdvisedSupportListener listener = MockRepository.GenerateMock(); + IAdvisedSupportListener listener = A.Fake(); ProxyFactory factory = new ProxyFactory(new TestObject()); factory.AddListener(listener); @@ -600,9 +586,9 @@ public void RemoveAdvisedSupportListener() factory.GetProxy(); // check that no lifecycle callback methods were invoked on the listener... - listener.AssertWasNotCalled(x => x.Activated(Arg.Is.Anything)); - listener.AssertWasNotCalled(x => x.AdviceChanged(Arg.Is.Anything)); - listener.AssertWasNotCalled(x => x.InterfacesChanged(Arg.Is.Anything)); + A.CallTo(() => listener.Activated(null)).WithAnyArguments().MustNotHaveHappened(); + A.CallTo(() => listener.AdviceChanged(null)).WithAnyArguments().MustNotHaveHappened(); + A.CallTo(() => listener.InterfacesChanged(null)).WithAnyArguments().MustNotHaveHappened(); } [Test] @@ -657,7 +643,7 @@ public void NestedProxiesDontInvokeSameAdviceOrIntroductionTwice() NopInterceptor diUnused = new NopInterceptor(1); // // make instance unique (see SPRNET-847) TestCountingIntroduction countingMixin = new TestCountingIntroduction(); - pf1.AddAdvice(diUnused); + pf1.AddAdvice(diUnused); pf1.AddAdvisor(new DefaultPointcutAdvisor(di)); pf1.AddIntroduction(new DefaultIntroductionAdvisor(countingMixin)); diff --git a/test/Spring/Spring.Aop.Tests/Aop/Support/DelegatingIntroductionInterceptorTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Support/DelegatingIntroductionInterceptorTests.cs index 0fe68b0b8..b14c4d630 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Support/DelegatingIntroductionInterceptorTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Support/DelegatingIntroductionInterceptorTests.cs @@ -1,13 +1,13 @@ #region License /* * Copyright 2002-2010 the original author or authors. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -16,14 +16,14 @@ */ #endregion -#region Imports using System; using NUnit.Framework; using AopAlliance.Aop; -using Rhino.Mocks; + +using FakeItEasy; + using Spring.Aop.Framework; using Spring.Objects; -#endregion namespace Spring.Aop.Support { @@ -58,9 +58,9 @@ public void TestIntroductionInterceptorWithDelegation() TestObject raw = new TestObject(); Assert.IsTrue(! (raw is ITimeStamped)); ProxyFactory factory = new ProxyFactory(raw); - - ITimeStampedIntroduction ts = MockRepository.GenerateMock(); - ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP); + + ITimeStampedIntroduction ts = A.Fake(); + A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP); DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts); factory.AddIntroduction(advisor); @@ -74,17 +74,18 @@ public void TestIntroductionInterceptorWithDelegation() public interface ISubTimeStampedIntroduction: ISubTimeStamped, IAdvice { } - - public void TestIntroductionInterceptorWithInterfaceHierarchy() + + [Test] + public void TestIntroductionInterceptorWithInterfaceHierarchy() { TestObject raw = new TestObject(); Assert.IsTrue(! (raw is ISubTimeStamped)); ProxyFactory factory = new ProxyFactory(raw); - ISubTimeStampedIntroduction ts = MockRepository.GenerateMock(); - ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP); + ISubTimeStampedIntroduction ts = A.Fake(); + A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP); - DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts); + DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts); // we must add introduction, not an advisor factory.AddIntroduction(advisor); @@ -93,17 +94,18 @@ public void TestIntroductionInterceptorWithInterfaceHierarchy() Assert.IsTrue(tsp.TimeStamp == EXPECTED_TIMESTAMP); } - public void TestIntroductionInterceptorWithSuperInterface() + [Test] + public void TestIntroductionInterceptorWithSuperInterface() { TestObject raw = new TestObject(); Assert.IsTrue(! (raw is ITimeStamped)); ProxyFactory factory = new ProxyFactory(raw); - ISubTimeStamped ts = MockRepository.GenerateMock(); - ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP); + ISubTimeStampedIntroduction ts = A.Fake(); + A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP); - factory.AddIntroduction(0, new DefaultIntroductionAdvisor( - (ISubTimeStampedIntroduction)ts, + factory.AddIntroduction(0, new DefaultIntroductionAdvisor( + ts, typeof(ITimeStamped)) ); @@ -121,42 +123,42 @@ private class Test : ITimeStamped, ITest, IAdvice { private DateTime _timestamp; - public Test(DateTime timestamp) + public Test(DateTime timestamp) { _timestamp = timestamp; } - public void Foo() + public void Foo() { } - public DateTime TimeStamp + public DateTime TimeStamp { - get + get { return _timestamp; } } } - public void TestAutomaticInterfaceRecognitionInDelegate() + public void TestAutomaticInterfaceRecognitionInDelegate() { IIntroductionAdvisor ia = new DefaultIntroductionAdvisor(new Test(EXPECTED_TIMESTAMP)); - + TestObject target = new TestObject(); ProxyFactory pf = new ProxyFactory(target); pf.AddIntroduction(0, ia); ITimeStamped ts = (ITimeStamped) pf.GetProxy(); - + Assert.IsTrue(ts.TimeStamp == EXPECTED_TIMESTAMP); ((ITest) ts).Foo(); - + int age = ((ITestObject) ts).Age; } /* * The rest of the tests in the original tested subclassing the * DelegatingIntroductionInterceptor. - * + * * Since we don't need to subclass anything to make a delegating * introduction, the rest of the tests are not necessary. */ @@ -164,12 +166,12 @@ public void TestAutomaticInterfaceRecognitionInDelegate() // must be public to be used for AOP // AOP creates a new assembly which must have access to the // interfaces that it intends to expose. - public interface ITest + public interface ITest { void Foo(); } - public interface ISubTimeStamped : ITimeStamped + public interface ISubTimeStamped : ITimeStamped { } diff --git a/test/Spring/Spring.Aop.Tests/Aop/Target/PrototypeTargetSourceTests.cs b/test/Spring/Spring.Aop.Tests/Aop/Target/PrototypeTargetSourceTests.cs index 6e09f7f06..151af21cc 100644 --- a/test/Spring/Spring.Aop.Tests/Aop/Target/PrototypeTargetSourceTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aop/Target/PrototypeTargetSourceTests.cs @@ -18,17 +18,17 @@ #endregion -#region Imports - using System; + using Common.Logging; using Common.Logging.Simple; + +using FakeItEasy; + using NUnit.Framework; + using Spring.Objects.Factory; using Spring.Objects.Factory.Xml; -using Rhino.Mocks; - -#endregion namespace Spring.Aop.Target { @@ -79,24 +79,16 @@ public void PrototypeAndSingletonBehaveDifferently() [Test] public void TargetType() { - MockRepository mocks = new MockRepository(); SideEffectObject target = new SideEffectObject(); - IObjectFactory factory = mocks.CreateMock(); - - using (mocks.Record()) - { - Expect.Call(factory.IsPrototype(null)).Return(true); - Expect.Call(factory.GetType(null)).Return(typeof(SideEffectObject)); - } + IObjectFactory factory = A.Fake(); - using (mocks.Playback()) - { - PrototypeTargetSource source = new PrototypeTargetSource(); - source.ObjectFactory = factory; - Assert.AreEqual(target.GetType(), source.TargetType, "Wrong TargetType being returned."); - } + A.CallTo(() => factory.IsPrototype(null)).Returns(true); + A.CallTo(() => factory.GetType(null)).Returns(typeof(SideEffectObject)); + PrototypeTargetSource source = new PrototypeTargetSource(); + source.ObjectFactory = factory; + Assert.AreEqual(target.GetType(), source.TargetType, "Wrong TargetType being returned."); } [Test] @@ -109,49 +101,30 @@ public void IsStatic() [Test] public void WithNonSingletonTargetObject() { - MockRepository mocks = new MockRepository(); - - IObjectFactory factory = mocks.CreateMock(); + IObjectFactory factory = A.Fake(); const string objectName = "Foo"; - using (mocks.Record()) - { - Expect.Call(factory.IsPrototype(objectName)).Return(false); - } - - using (mocks.Playback()) - { - PrototypeTargetSource source = new PrototypeTargetSource(); - source.TargetObjectName = objectName; + A.CallTo(() => factory.IsPrototype(objectName)).Returns(false); + PrototypeTargetSource source = new PrototypeTargetSource(); + source.TargetObjectName = objectName; - Assert.Throws(delegate { source.ObjectFactory = factory; }); - } + Assert.Throws(delegate { source.ObjectFactory = factory; }); } [Test] public void GetTarget() { - MockRepository mocks = new MockRepository(); - - IObjectFactory factory = mocks.CreateMock(); + IObjectFactory factory = A.Fake(); SideEffectObject target = new SideEffectObject(); + A.CallTo(() => factory.IsPrototype("foo")).Returns(true); + A.CallTo(() => factory.GetObject("foo")).Returns(target); + A.CallTo(() => factory.GetType("foo")).Returns(typeof(string)); - using (mocks.Record()) - { - Expect.Call(factory.IsPrototype("foo")).Return(true); - Expect.Call(factory.GetObject("foo")).Return(target); - Expect.Call(factory.GetType("foo")).Return(typeof(string)); - } - - using (mocks.Playback()) - { - PrototypeTargetSource source = new PrototypeTargetSource(); - source.TargetObjectName = "foo"; - source.ObjectFactory = factory; - Assert.IsTrue(object.ReferenceEquals(source.GetTarget(), target), - "Initial target source reference not being returned by GetTarget()."); - } - + PrototypeTargetSource source = new PrototypeTargetSource(); + source.TargetObjectName = "foo"; + source.ObjectFactory = factory; + Assert.IsTrue(object.ReferenceEquals(source.GetTarget(), target), + "Initial target source reference not being returned by GetTarget()."); } [Test] diff --git a/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheParameterAdviceTests.cs b/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheParameterAdviceTests.cs index 86c677e23..ec3f9e056 100644 --- a/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheParameterAdviceTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheParameterAdviceTests.cs @@ -18,17 +18,15 @@ #endregion -#region Imports - using System; using System.Reflection; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Caching; using Spring.Context; -#endregion - namespace Spring.Aspects.Cache { /// @@ -38,7 +36,6 @@ namespace Spring.Aspects.Cache [TestFixture] public sealed class CacheParameterAdviceTests { - private MockRepository mocks; private IApplicationContext mockContext; private CacheParameterAdvice advice; private ICache cache; @@ -46,8 +43,7 @@ public sealed class CacheParameterAdviceTests [SetUp] public void SetUp() { - mocks = new MockRepository(); - mockContext = (IApplicationContext) mocks.CreateMock(typeof (IApplicationContext)); + mockContext = A.Fake(); advice = new CacheParameterAdvice(); advice.ApplicationContext = mockContext; @@ -62,14 +58,11 @@ public void TestSimpleParameterCaching() object[] args = new object[] {new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian")}; ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); // parameter value should be added to cache advice.AfterReturning(null, method, args, null); Assert.AreEqual(1, cache.Count); Assert.AreEqual(args[0], cache.Get("Nikola Tesla")); - - mocks.VerifyAll(); } [Test] @@ -79,14 +72,11 @@ public void TestSimpleWithMethodInfoParameterCaching() object[] args = new object[] { new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian") }; ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); // parameter value should be added to cache advice.AfterReturning(null, method, args, null); Assert.AreEqual(1, cache.Count); Assert.AreEqual(args[0], cache.Get("Save-Nikola Tesla")); - - mocks.VerifyAll(); } [Test] @@ -96,16 +86,13 @@ public void TestMultipleParameterCaching() object[] args = new object[] { new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian") }; ExpectCacheInstanceRetrieval("cache", cache); - ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); + ExpectCacheInstanceRetrieval("cache", cache); // parameter value should be added to both cache advice.AfterReturning(null, method, args, null); Assert.AreEqual(2, cache.Count); Assert.AreEqual(args[0], cache.Get("Nikola Tesla")); Assert.AreEqual(args[0], cache.Get("Serbian")); - - mocks.VerifyAll(); } [Test] @@ -119,18 +106,12 @@ public void TestConditionParameterCaching() Assert.AreEqual(0, cache.Count); } - #region Helper methods - private void ExpectCacheInstanceRetrieval(string cacheName, ICache cacheToReturn) { - Expect.Call(mockContext.GetObject(cacheName)).Return(cacheToReturn); + A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cacheToReturn).Once(); } - - #endregion } - #region Inner Class : CacheParameterTarget - public interface ICacheParameterTarget { void Save(Inventor inventor); @@ -163,6 +144,4 @@ public void Save([CacheParameter("cache", "Name", Condition = "Nationality == 'F { } } - - #endregion } \ No newline at end of file diff --git a/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheResultAdviceTests.cs b/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheResultAdviceTests.cs index b3060b652..8aac6ea1e 100644 --- a/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheResultAdviceTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aspects/Cache/CacheResultAdviceTests.cs @@ -18,20 +18,18 @@ #endregion -#region Imports - using System.Collections; using System.IO; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using AopAlliance.Intercept; -using Rhino.Mocks; + +using FakeItEasy; + using NUnit.Framework; using Spring.Caching; using Spring.Context; -#endregion - namespace Spring.Aspects.Cache { /// @@ -50,14 +48,12 @@ public sealed class CacheResultAdviceTests private ICache itemCache; private ICache binaryFormatterCache; private CacheResultTarget cacheResultTarget = new CacheResultTarget(); - private MockRepository mocks; [SetUp] public void SetUp() { - mocks = new MockRepository(); - mockInvocation = mocks.CreateMock(); - mockContext = mocks.CreateMock(); + mockInvocation = A.Fake(); + mockContext = A.Fake(); advice = new CacheResultAdvice(); advice.ApplicationContext = mockContext; @@ -77,24 +73,16 @@ public void CacheResultOfMethodThatReturnsNull() MethodInfo method = new VoidMethod(cacheResultTarget.ReturnsNothing).Method; object expectedReturnValue = null; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, null); - ExpectCacheInstanceRetrieval("results", resultCache); - ExpectCallToProceed(expectedReturnValue); - } - - using (mocks.Playback()) - { - // check that the null retVal is cached as well - it might be - // the result of an expensive webservice/database call etc. - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(1, resultCache.Count); - } - + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, null); + ExpectCacheInstanceRetrieval("results", resultCache); + ExpectCallToProceed(expectedReturnValue); + // check that the null retVal is cached as well - it might be + // the result of an expensive webservice/database call etc. + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(1, resultCache.Count); } [Test] @@ -103,26 +91,20 @@ public void CacheResultOfMethodThatReturnsNullWithSerializingCache() MethodInfo method = new VoidMethod(cacheResultTarget.ReturnsNothing).Method; object expectedReturnValue = null; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, null); - ExpectCacheInstanceRetrieval("results", binaryFormatterCache); - ExpectCallToProceed(expectedReturnValue); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, null); + ExpectCacheInstanceRetrieval("results", binaryFormatterCache); + ExpectCallToProceed(expectedReturnValue); - using (mocks.Playback()) - { - // check that the null retVal is cached as well - it might be - // the result of an expensive webservice/database call etc. - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(1, binaryFormatterCache.Count); - - // cached value should be returned - object cachedValue = advice.Invoke(mockInvocation); - Assert.IsNull(cachedValue, "Should recognize cached value as null-value marker."); - } + // check that the null retVal is cached as well - it might be + // the result of an expensive webservice/database call etc. + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(1, binaryFormatterCache.Count); + + // cached value should be returned + object cachedValue = advice.Invoke(mockInvocation); + Assert.IsNull(cachedValue, "Should recognize cached value as null-value marker."); } [Test] @@ -131,96 +113,76 @@ public void CacheResultOfMethodThatReturnsObject() MethodInfo method = new IntMethod(cacheResultTarget.ReturnsScalar).Method; object expectedReturnValue = CacheResultTarget.Scalar; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, null); - ExpectCacheInstanceRetrieval("results", resultCache); - ExpectCallToProceed(expectedReturnValue); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, null); + ExpectCacheInstanceRetrieval("results", resultCache); + ExpectCallToProceed(expectedReturnValue); - using (mocks.Playback()) - { - // return value should be added to cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(1, resultCache.Count); - - // cached value should be returned - object cachedValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, cachedValue); - Assert.AreEqual(1, resultCache.Count); - Assert.AreSame(returnValue, cachedValue); - } + // return value should be added to cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(1, resultCache.Count); + + // cached value should be returned + object cachedValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, cachedValue); + Assert.AreEqual(1, resultCache.Count); + Assert.AreSame(returnValue, cachedValue); } [Test] public void CacheResultOfMethodThatReturnsCollection() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsCollection).Method; - object expectedReturnValue = new object[] { "one", "two", "three" }; + object expectedReturnValue = new object[] {"one", "two", "three"}; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - ExpectCacheInstanceRetrieval("results", resultCache); - ExpectCallToProceed(new object[] { "one", "two", "three" }); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, 5, expectedReturnValue); + ExpectCacheInstanceRetrieval("results", resultCache); + ExpectCallToProceed(new object[] {"one", "two", "three"}); - using (mocks.Playback()) - { - // return value should be added to cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(1, resultCache.Count); - - // cached value should be returned - object cachedValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, cachedValue); - Assert.AreNotSame(expectedReturnValue, cachedValue); - Assert.AreEqual(expectedReturnValue, resultCache.Get(5)); - Assert.AreEqual(1, resultCache.Count); - Assert.AreSame(returnValue, cachedValue); - Assert.AreSame(cachedValue, resultCache.Get(5)); - } + // return value should be added to cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(1, resultCache.Count); + + // cached value should be returned + object cachedValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, cachedValue); + Assert.AreNotSame(expectedReturnValue, cachedValue); + Assert.AreEqual(expectedReturnValue, resultCache.Get(5)); + Assert.AreEqual(1, resultCache.Count); + Assert.AreSame(returnValue, cachedValue); + Assert.AreSame(cachedValue, resultCache.Get(5)); } [Test] public void CacheResultAndItemsOfMethodThatReturnsCollection() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsCollectionAndItems).Method; - object expectedReturnValue = new object[] { "one", "two", "three" }; + object expectedReturnValue = new object[] {"one", "two", "three"}; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - ExpectCacheInstanceRetrieval("results", resultCache); - ExpectCallToProceed(new object[] { "one", "two", "three" }); - ExpectCacheInstanceRetrieval("items", itemCache); - - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, 5, expectedReturnValue); + ExpectCacheInstanceRetrieval("results", resultCache); + ExpectCallToProceed(new object[] {"one", "two", "three"}); + ExpectCacheInstanceRetrieval("items", itemCache); - using (mocks.Playback()) - { - // return value should be added to result cache and each item to item cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(1, resultCache.Count); - Assert.AreEqual(3, itemCache.Count); - - // cached value should be returned - object cachedValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, cachedValue); - Assert.AreNotSame(expectedReturnValue, cachedValue); - Assert.AreEqual(expectedReturnValue, resultCache.Get(5)); - Assert.AreEqual(1, resultCache.Count); - Assert.AreEqual(3, itemCache.Count); - Assert.AreSame(returnValue, cachedValue); - Assert.AreSame(cachedValue, resultCache.Get(5)); + // return value should be added to result cache and each item to item cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(1, resultCache.Count); + Assert.AreEqual(3, itemCache.Count); - } + // cached value should be returned + object cachedValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, cachedValue); + Assert.AreNotSame(expectedReturnValue, cachedValue); + Assert.AreEqual(expectedReturnValue, resultCache.Get(5)); + Assert.AreEqual(1, resultCache.Count); + Assert.AreEqual(3, itemCache.Count); + Assert.AreSame(returnValue, cachedValue); + Assert.AreSame(cachedValue, resultCache.Get(5)); } [Test] @@ -229,74 +191,51 @@ public void CacheOnlyItemsOfMethodThatReturnsCollection() MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsItems).Method; object expectedReturnValue = new object[] { "one", "two", "three" }; - mocks.Record(); - ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, expectedReturnValue); ExpectCallToProceed(new object[] { "one", "two", "three" }); ExpectCacheInstanceRetrieval("items", itemCache); - mocks.ReplayAll(); - // return value should be added to result cache and each item to item cache object returnValue = advice.Invoke(mockInvocation); Assert.AreEqual(expectedReturnValue, returnValue); Assert.AreEqual(0, resultCache.Count); Assert.AreEqual(3, itemCache.Count); - mocks.Verify(mockInvocation); - - mocks.BackToRecord(mockInvocation); - ExpectAttributeRetrieval(method); ExpectCallToProceed(new object[] { "one", "two", "three" }); ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - mocks.Replay(mockInvocation); - object newReturnValue = advice.Invoke(mockInvocation); Assert.AreEqual(expectedReturnValue, newReturnValue); Assert.AreEqual(0, resultCache.Count); Assert.AreEqual(3, itemCache.Count); Assert.AreEqual("two", itemCache.Get("two")); Assert.AreNotSame(returnValue, newReturnValue); - - mocks.VerifyAll(); } - [Test] public void CacheOnlyItemsOfMethodThatReturnsCollectionWithinTwoDifferentCaches() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.MultipleCacheResultItems).Method; object expectedReturnValue = new object[] { "one", "two", "three" }; - mocks.Record(); - ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, expectedReturnValue); ExpectCallToProceed(new object[] { "one", "two", "three" }); ExpectCacheInstanceRetrieval("items", itemCache); - mocks.ReplayAll(); - // return value should be added to result cache and each item to item cache object returnValue = advice.Invoke(mockInvocation); Assert.AreEqual(expectedReturnValue, returnValue); Assert.AreEqual(0, resultCache.Count); Assert.AreEqual(6, itemCache.Count); - mocks.Verify(mockInvocation); - - mocks.BackToRecord(mockInvocation); - // and again, but without Proceed() and item cache access... ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, expectedReturnValue); ExpectCallToProceed(new object[] { "one", "two", "three" }); - mocks.Replay(mockInvocation); - // new return value should be returned object newReturnValue = advice.Invoke(mockInvocation); Assert.AreEqual(expectedReturnValue, newReturnValue); @@ -305,57 +244,42 @@ public void CacheOnlyItemsOfMethodThatReturnsCollectionWithinTwoDifferentCaches( Assert.AreEqual("two", itemCache.Get("two")); Assert.AreEqual("two", itemCache.Get("TWO")); Assert.AreNotSame(returnValue, newReturnValue); - - mocks.VerifyAll(); } [Test] public void CacheOnlyItemsOfMethodThatReturnsCollectionOnCondition() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultItemsWithCondition).Method; - object expectedReturnValue = new object[] { "one", "two", "three" }; - - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - ExpectCallToProceed(new object[] { "one", "two", "three" }); - ExpectCacheInstanceRetrieval("items", itemCache); - } + object expectedReturnValue = new object[] {"one", "two", "three"}; - using (mocks.Playback()) - { - // return value should be added to result cache and each item to item cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(2, itemCache.Count); - Assert.AreEqual("two", itemCache.Get("two")); - Assert.AreEqual("three", itemCache.Get("three")); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, 5, expectedReturnValue); + ExpectCallToProceed(new object[] {"one", "two", "three"}); + ExpectCacheInstanceRetrieval("items", itemCache); + // return value should be added to result cache and each item to item cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(2, itemCache.Count); + Assert.AreEqual("two", itemCache.Get("two")); + Assert.AreEqual("three", itemCache.Get("three")); } [Test] public void CacheResultOfMethodThatReturnsCollectionOnCondition() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultWithCondition).Method; - object expectedReturnValue = new object[] { }; + object expectedReturnValue = new object[] {}; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - ExpectCacheInstanceRetrieval("results", resultCache); - ExpectCallToProceed(new object[] { }); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, 5, expectedReturnValue); + ExpectCacheInstanceRetrieval("results", resultCache); + ExpectCallToProceed(new object[] {}); - using (mocks.Playback()) - { - // return value should not be added to cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(0, resultCache.Count); - } + // return value should not be added to cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(0, resultCache.Count); } [Test] @@ -365,16 +289,12 @@ public void AcceptsEnumerableOnlyReturn() object[] args = new object[] { "one", "two", "three" }; EnumerableOnlyResult expectedReturnValue = new EnumerableOnlyResult(args); - mocks.Record(); - ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, expectedReturnValue.InnerArray); ExpectCacheInstanceRetrieval("results", resultCache); ExpectCallToProceed(expectedReturnValue); ExpectCacheInstanceRetrieval("items", itemCache); - mocks.ReplayAll(); - // return value should be added to result cache and each item to item cache object returnValue = advice.Invoke(mockInvocation); Assert.AreEqual(1, resultCache.Count); @@ -382,16 +302,10 @@ public void AcceptsEnumerableOnlyReturn() Assert.AreSame(expectedReturnValue, returnValue); Assert.AreSame(expectedReturnValue, resultCache.Get(5)); - mocks.Verify(mockInvocation); - - mocks.BackToRecord(mockInvocation); - // and again, but without Proceed() and item cache access... ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, IGNORED_ARGS); - mocks.Replay(mockInvocation); - // cached value should be returned, cache remains unchanged object cachedValue = advice.Invoke(mockInvocation); Assert.AreSame(expectedReturnValue, cachedValue); @@ -399,42 +313,30 @@ public void AcceptsEnumerableOnlyReturn() Assert.AreSame(expectedReturnValue, resultCache.Get(5)); Assert.AreEqual(1, resultCache.Count); Assert.AreEqual(3, itemCache.Count); - - mocks.VerifyAll(); } - + [Test] public void CacheResultOfMethodThatReturnsCollectionContainingNullItems() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsEnumerableOnlyAndItems).Method; object expectedReturnValue = new object[] { null, "two", null }; - mocks.Record(); - ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, expectedReturnValue); ExpectCacheInstanceRetrieval("results", resultCache); ExpectCallToProceed(expectedReturnValue); ExpectCacheInstanceRetrieval("items", itemCache); - mocks.ReplayAll(); - // return value should be added to result cache and each item to item cache object returnValue = advice.Invoke(mockInvocation); Assert.AreSame(expectedReturnValue, returnValue); Assert.AreEqual(1, resultCache.Count); Assert.AreEqual(2, itemCache.Count); // 2 null items result into 1 cached item - mocks.Verify(mockInvocation); - - mocks.BackToRecord(mockInvocation); - // and again, but without Proceed() and item cache access... ExpectAttributeRetrieval(method); ExpectCacheKeyGeneration(method, 5, IGNORED_ARGS); - mocks.Replay(mockInvocation); - // cached value should be returned object cachedValue = advice.Invoke(mockInvocation); Assert.AreSame(expectedReturnValue, cachedValue); @@ -442,95 +344,74 @@ public void CacheResultOfMethodThatReturnsCollectionContainingNullItems() Assert.AreSame(expectedReturnValue, resultCache.Get(5)); Assert.AreEqual(1, resultCache.Count); Assert.AreEqual(2, itemCache.Count); - - mocks.VerifyAll(); } [Test] public void CacheResultWithMethodInfo() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultWithMethodInfo).Method; - object expectedReturnValue = new object[] { "one", "two", "three" }; + object expectedReturnValue = new object[] {"one", "two", "three"}; - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - ExpectCacheInstanceRetrieval("results", resultCache); - ExpectCallToProceed(new object[] { "one", "two", "three" }); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, 5, expectedReturnValue); + ExpectCacheInstanceRetrieval("results", resultCache); + ExpectCallToProceed(new object[] {"one", "two", "three"}); - using (mocks.Playback()) - { - // return value should be added to cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(1, resultCache.Count); - Assert.AreEqual(returnValue, resultCache.Get("CacheResultWithMethodInfo-5")); - } + // return value should be added to cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(1, resultCache.Count); + Assert.AreEqual(returnValue, resultCache.Get("CacheResultWithMethodInfo-5")); } [Test] public void CacheResultItemsWithMethodInfo() { MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultItemsWithMethodInfo).Method; - object expectedReturnValue = new object[] { "one", "two", "three" }; - - using (mocks.Record()) - { - ExpectAttributeRetrieval(method); - ExpectCacheKeyGeneration(method, 5, expectedReturnValue); - ExpectCallToProceed(new object[] { "one", "two", "three" }); - ExpectCacheInstanceRetrieval("items", itemCache); - } + object expectedReturnValue = new object[] {"one", "two", "three"}; - using (mocks.Playback()) - { - // return value should be added to result cache and each item to item cache - object returnValue = advice.Invoke(mockInvocation); - Assert.AreEqual(expectedReturnValue, returnValue); - Assert.AreEqual(0, resultCache.Count); - Assert.AreEqual(3, itemCache.Count); - Assert.AreEqual("two", itemCache.Get("CacheResultItemsWithMethodInfo-two")); - } + ExpectAttributeRetrieval(method); + ExpectCacheKeyGeneration(method, 5, expectedReturnValue); + ExpectCallToProceed(new object[] {"one", "two", "three"}); + ExpectCacheInstanceRetrieval("items", itemCache); + // return value should be added to result cache and each item to item cache + object returnValue = advice.Invoke(mockInvocation); + Assert.AreEqual(expectedReturnValue, returnValue); + Assert.AreEqual(0, resultCache.Count); + Assert.AreEqual(3, itemCache.Count); + Assert.AreEqual("two", itemCache.Get("CacheResultItemsWithMethodInfo-two")); } - - #region Helper methods - private void ExpectAttributeRetrieval(MethodInfo method) { - Expect.Call(mockInvocation.Method).Return(method).Repeat.AtLeastOnce(); + A.CallTo(() => mockInvocation.Method).Returns(method); } private void ExpectCacheKeyGeneration(MethodInfo method, params object[] arguments) { - Expect.Call(mockInvocation.Arguments).Return(arguments).Repeat.AtLeastOnce(); + A.CallTo(() => mockInvocation.Arguments).Returns(arguments); } private void ExpectCacheInstanceRetrieval(string cacheName, ICache cache) { - Expect.Call(mockContext.GetObject(cacheName)).Return(cache).Repeat.AtLeastOnce(); + A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cache); } private void ExpectCacheInstanceRetrieval(string cacheName, ICache cache, int repeatTimes) { - Expect.Call(mockContext.GetObject(cacheName)).Return(cache).Repeat.Times(repeatTimes); + A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cache).NumberOfTimes(repeatTimes); } private void ExpectCallToProceed(object expectedReturnValue, int repeatTimes) { - Expect.Call(mockInvocation.Proceed()).Return(expectedReturnValue).Repeat.Times(repeatTimes); + A.CallTo(() => mockInvocation.Proceed()).Returns(expectedReturnValue).NumberOfTimes(repeatTimes); } private void ExpectCallToProceed(object expectedReturnValue) { - Expect.Call(mockInvocation.Proceed()).Return(expectedReturnValue); + A.CallTo(() => mockInvocation.Proceed()).Returns(expectedReturnValue); } - - #endregion - } #region Inner Class : CacheResultTarget diff --git a/test/Spring/Spring.Aop.Tests/Aspects/Cache/InvalidateCacheAdviceTests.cs b/test/Spring/Spring.Aop.Tests/Aspects/Cache/InvalidateCacheAdviceTests.cs index 1519157c9..98b26327d 100644 --- a/test/Spring/Spring.Aop.Tests/Aspects/Cache/InvalidateCacheAdviceTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aspects/Cache/InvalidateCacheAdviceTests.cs @@ -18,18 +18,15 @@ #endregion -#region Imports - using System.Reflection; -using NUnit.Framework; -using Rhino.Mocks; +using FakeItEasy; + +using NUnit.Framework; using Spring.Caching; using Spring.Context; -#endregion - namespace Spring.Aspects.Cache { /// @@ -42,13 +39,11 @@ public sealed class InvalidateCacheAdviceTests private IApplicationContext mockContext; private InvalidateCacheAdvice advice; private ICache cache; - private MockRepository mocks; [SetUp] public void SetUp() { - mocks = new MockRepository(); - mockContext = (IApplicationContext) mocks.CreateMock(typeof (IApplicationContext)); + mockContext = A.Fake(); advice = new InvalidateCacheAdvice(); advice.ApplicationContext = mockContext; @@ -66,7 +61,6 @@ public void TestSingleKeyInvalidation() object[] args = new object[] { 2 }; ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); Assert.AreEqual(3, cache.Count); @@ -74,8 +68,6 @@ public void TestSingleKeyInvalidation() advice.AfterReturning(null, method, args, null); Assert.AreEqual(2, cache.Count); Assert.IsNull(cache.Get(2)); - - mocks.VerifyAll(); } [Test] @@ -85,7 +77,6 @@ public void TestMultiKeyInvalidation() object[] args = new object[] { 2 }; ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); Assert.AreEqual(3, cache.Count); @@ -93,8 +84,6 @@ public void TestMultiKeyInvalidation() advice.AfterReturning(null, method, args, null); Assert.AreEqual(1, cache.Count); Assert.AreEqual("two", cache.Get(2)); - - mocks.VerifyAll(); } [Test] @@ -103,15 +92,12 @@ public void TestWholeCacheInvalidation() MethodInfo method = typeof(InvalidateCacheTarget).GetMethod("InvalidateAll"); ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); Assert.AreEqual(3, cache.Count); // all items should be removed from cache advice.AfterReturning(null, method, null, null); Assert.AreEqual(0, cache.Count); - - mocks.VerifyAll(); } [Test] @@ -122,7 +108,6 @@ public void TestMultipleCachesInvalidation() ExpectCacheInstanceRetrieval("cache", cache); ExpectCacheInstanceRetrieval("cache", cache); - mocks.ReplayAll(); Assert.AreEqual(3, cache.Count); @@ -130,8 +115,6 @@ public void TestMultipleCachesInvalidation() // all items except item "two" should be removed from cache advice.AfterReturning(null, method, args, null); Assert.AreEqual(0, cache.Count); - - mocks.VerifyAll(); } [Test] @@ -148,14 +131,10 @@ public void TestConditionInvalidation() Assert.AreEqual("three", cache.Get(3)); } - #region Helper methods - private void ExpectCacheInstanceRetrieval(string cacheName, ICache cacheToReturn) { - Expect.Call(mockContext.GetObject(cacheName)).Return(cacheToReturn); + A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cacheToReturn).Once(); } - - #endregion } #region Inner Class : InvalidateCacheTarget diff --git a/test/Spring/Spring.Aop.Tests/Aspects/Logging/SimpleLoggingAdviceTests.cs b/test/Spring/Spring.Aop.Tests/Aspects/Logging/SimpleLoggingAdviceTests.cs index 716e0c7cc..853c71265 100644 --- a/test/Spring/Spring.Aop.Tests/Aspects/Logging/SimpleLoggingAdviceTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aspects/Logging/SimpleLoggingAdviceTests.cs @@ -18,19 +18,17 @@ #endregion -#region Imports - using System; using System.Reflection; using AopAlliance.Intercept; using Common.Logging; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Aop.Framework; -#endregion - namespace Spring.Aspects.Logging { /// @@ -51,12 +49,9 @@ public void DoSomething() { } } - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } [Test] @@ -64,101 +59,76 @@ public void IntegrationTest() { ProxyFactory pf = new ProxyFactory(new TestTarget()); - ILog log = (ILog)mocks.CreateMock(typeof(ILog)); + ILog log = A.Fake(); SimpleLoggingAdvice loggingAdvice = new SimpleLoggingAdvice(log); pf.AddAdvice(loggingAdvice); - Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); - log.Trace("Entering DoSomething"); - log.Trace("Exiting DoSomething"); - - mocks.ReplayAll(); + A.CallTo(() => log.IsTraceEnabled).Returns(true); object proxy = pf.GetProxy(); ITestTarget ptt = (ITestTarget)proxy; ptt.DoSomething(); - mocks.VerifyAll(); + A.CallTo(() => log.Trace("Entering DoSomething")).MustHaveHappened(); + A.CallTo(() => log.Trace("Exiting DoSomething")).MustHaveHappened(); } [Test] public void SunnyDayLoggingCorrectly() { - ILog log = (ILog)mocks.CreateMock(typeof(ILog)); - IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); + ILog log = A.Fake(); + IMethodInvocation methodInvocation = A.Fake(); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); //two additional calls the method are to retrieve the method name on entry/exit... - Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any(); - - Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); - log.Trace("Entering ToString"); - - Expect.Call(methodInvocation.Proceed()).Return(null); - - log.Trace("Exiting ToString"); - - mocks.ReplayAll(); + A.CallTo(() => methodInvocation.Method).Returns(mi); + A.CallTo(() => log.IsTraceEnabled).Returns(true); + A.CallTo(() => methodInvocation.Proceed()).Returns(null); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); loggingAdvice.CallInvokeUnderLog(methodInvocation, log); - mocks.VerifyAll(); - + A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened(); + A.CallTo(() => log.Trace("Exiting ToString")).MustHaveHappened(); } [Test] public void SunnyDayLoggingCorrectlyDebugLevel() { - ILog log = (ILog)mocks.CreateMock(typeof(ILog)); - IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); + ILog log = A.Fake(); + IMethodInvocation methodInvocation = A.Fake(); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); //two additional calls the method are to retrieve the method name on entry/exit... - Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any(); - - Expect.Call(log.IsTraceEnabled).Return(false).Repeat.Any(); - Expect.Call(log.IsDebugEnabled).Return(true).Repeat.Any(); - log.Debug("Entering ToString"); - - Expect.Call(methodInvocation.Proceed()).Return(null); + A.CallTo(() => methodInvocation.Method).Returns(mi); - log.Debug("Exiting ToString"); + A.CallTo(() => log.IsTraceEnabled).Returns(false); + A.CallTo(() => log.IsDebugEnabled).Returns(true); - mocks.ReplayAll(); + A.CallTo(() => methodInvocation.Proceed()).Returns(null); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); loggingAdvice.LogLevel = LogLevel.Debug; Assert.IsTrue(loggingAdvice.CallIsInterceptorEnabled(methodInvocation, log)); loggingAdvice.CallInvokeUnderLog(methodInvocation, log); - mocks.VerifyAll(); - + A.CallTo(() => log.Debug("Entering ToString")).MustHaveHappened(); + A.CallTo(() => log.Debug("Exiting ToString")).MustHaveHappened(); } - [Test] public void ExceptionPathStillLogsCorrectly() { - ILog log = (ILog)mocks.CreateMock(typeof(ILog)); - IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); + ILog log = A.Fake(); + IMethodInvocation methodInvocation = A.Fake(); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); //two additional calls the method are to retrieve the method name on entry/exit... - Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any(); - - Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); - log.Trace("Entering..."); - - LastCall.On(log).IgnoreArguments(); + A.CallTo(() => methodInvocation.Method).Returns(mi); + A.CallTo(() => log.IsTraceEnabled).Returns(true); Exception e = new ArgumentException("bad value"); - Expect.Call(methodInvocation.Proceed()).Throw(e); - - log.Trace("Exception...", e); - LastCall.On(log).IgnoreArguments(); - - mocks.ReplayAll(); + A.CallTo(() => methodInvocation.Proceed()).Throws(e); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); try @@ -168,39 +138,27 @@ public void ExceptionPathStillLogsCorrectly() } catch (ArgumentException) { - } - mocks.VerifyAll(); - + A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened(); + A.CallTo(() => log.Trace("Exception thrown in ToString, ToString", e)).MustHaveHappened(); } - [Test] public void SunnyDayLoggingAllOptionalInformationCorrectly() { - ILog log = (ILog)mocks.CreateMock(typeof(ILog)); - IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); + ILog log = A.Fake(); + IMethodInvocation methodInvocation = A.Fake(); MethodInfo mi = typeof(Dog).GetMethod("Bark"); //two additional calls the method are to retrieve the method name on entry/exit... - Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any(); + A.CallTo(() => methodInvocation.Method).Returns(mi); int[] luckyNumbers = new int[] { 1, 2, 3 }; object[] args = new object[] { "hello", luckyNumbers }; - - Expect.Call(methodInvocation.Arguments).Return(args); - - Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); - log.Trace("Entering..."); - LastCall.IgnoreArguments(); - - Expect.Call(methodInvocation.Proceed()).Return(4); - - log.Trace("Exiting..."); - LastCall.IgnoreArguments(); - - mocks.ReplayAll(); + A.CallTo(() => methodInvocation.Arguments).Returns(args); + A.CallTo(() => log.IsTraceEnabled).Returns(true); + A.CallTo(() => methodInvocation.Proceed()).Returns(4); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); loggingAdvice.LogExecutionTime = true; @@ -209,7 +167,8 @@ public void SunnyDayLoggingAllOptionalInformationCorrectly() loggingAdvice.CallInvokeUnderLog(methodInvocation, log); - mocks.VerifyAll(); + A.CallTo(() => log.Trace(A.That.StartsWith("Entering Bark"))).MustHaveHappened(); + A.CallTo(() => log.Trace(A.That.StartsWith("Exiting Bark"))).MustHaveHappened(); } } diff --git a/test/Spring/Spring.Aop.Tests/Aspects/Validation/ParameterValidationAdviceTests.cs b/test/Spring/Spring.Aop.Tests/Aspects/Validation/ParameterValidationAdviceTests.cs index 638fc40c8..94a025c9a 100644 --- a/test/Spring/Spring.Aop.Tests/Aspects/Validation/ParameterValidationAdviceTests.cs +++ b/test/Spring/Spring.Aop.Tests/Aspects/Validation/ParameterValidationAdviceTests.cs @@ -18,18 +18,16 @@ #endregion -#region Imports - using System; using System.Reflection; -using Rhino.Mocks; + +using FakeItEasy; + using NUnit.Framework; using Spring.Context; using Spring.Validation; using Spring.Validation.Actions; -#endregion - namespace Spring.Aspects.Validation { /// @@ -42,13 +40,11 @@ public sealed class ParameterValidationAdviceTests private IApplicationContext mockContext; private ParameterValidationAdvice advice; private RequiredValidator requiredValidator; - private MockRepository mocks; [SetUp] public void SetUp() { - mocks = new MockRepository(); - mockContext = mocks.CreateMock(); + mockContext = A.Fake(); advice = new ParameterValidationAdvice(); advice.ApplicationContext = mockContext; @@ -65,18 +61,11 @@ public void TestValidArgument() ValidationTarget target = new ValidationTarget(); object[] args = new object[] {inventor}; - using (mocks.Record()) - { - ExpectValidatorRetrieval("required", requiredValidator); - } - - using (mocks.Playback()) - { - advice.Before(method, args, target); - method.Invoke(target, args); - Assert.AreEqual("NIKOLA TESLA", inventor.Name); - } + ExpectValidatorRetrieval("required", requiredValidator); + advice.Before(method, args, target); + method.Invoke(target, args); + Assert.AreEqual("NIKOLA TESLA", inventor.Name); } [Test] @@ -84,25 +73,15 @@ public void TestInvalidArgument() { MethodInfo method = typeof(ValidationTarget).GetMethod("Save"); - using (mocks.Record()) - { - ExpectValidatorRetrieval("required", requiredValidator); - } + ExpectValidatorRetrieval("required", requiredValidator); - using (mocks.Playback()) - { - Assert.Throws(() => advice.Before(method, new object[] { null }, new ValidationTarget())); - } + Assert.Throws(() => advice.Before(method, new object[] {null}, new ValidationTarget())); } - #region Helper methods - private void ExpectValidatorRetrieval(string validatorName, IValidator validator) { - Expect.Call(mockContext.GetObject(validatorName)).Return(validator); + A.CallTo(() => mockContext.GetObject(validatorName)).Returns(validator).Once(); } - - #endregion } #region Inner Class : ValidationTarget diff --git a/test/Spring/Spring.Aop.Tests/Spring.Aop.Tests.2010.csproj b/test/Spring/Spring.Aop.Tests/Spring.Aop.Tests.2010.csproj index 2dd4c4a7a..18f5893fa 100644 --- a/test/Spring/Spring.Aop.Tests/Spring.Aop.Tests.2010.csproj +++ b/test/Spring/Spring.Aop.Tests/Spring.Aop.Tests.2010.csproj @@ -7,10 +7,11 @@ + + - diff --git a/test/Spring/Spring.Core.Tests/Caching/AbstractCacheTests.cs b/test/Spring/Spring.Core.Tests/Caching/AbstractCacheTests.cs index 342567a97..1c0cd4b77 100644 --- a/test/Spring/Spring.Core.Tests/Caching/AbstractCacheTests.cs +++ b/test/Spring/Spring.Core.Tests/Caching/AbstractCacheTests.cs @@ -18,19 +18,17 @@ #endregion -#region Imports - using System; using System.Threading; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Caching { /// - /// Tests behaviour to ensure, + /// Tests behaviour to ensure, /// that derived classes maybe rely on this default behaviour /// /// Erich Eichinger @@ -56,15 +54,13 @@ protected override void DoInsert(object key, object value, TimeSpan timeToLive) TimeSpan expectedPerItemTTL; TimeSpan expectedPerCacheTTL; - MockRepository mocks; ExposingAbstractCache cache; - string[] KEYS = new string[] { "keyA", "keyB" }; + string[] KEYS = new string[] {"keyA", "keyB"}; [SetUp] public void SetUp() { - mocks = new MockRepository(); - cache = (ExposingAbstractCache)mocks.PartialMock(typeof(ExposingAbstractCache)); + cache = A.Fake(options => options.CallsBaseMethods()); expectedPerItemTTL = new TimeSpan(0, 0, 10); expectedPerCacheTTL = new TimeSpan(0, 0, 20); @@ -75,7 +71,7 @@ public void SetUp() [Test] public void TestDefaults() { - ExposingAbstractCache localCache = (ExposingAbstractCache)mocks.PartialMock(typeof(ExposingAbstractCache)); + ExposingAbstractCache localCache = A.Fake(); Assert.AreEqual(TimeSpan.Zero, localCache.TimeToLive); Assert.AreEqual(false, localCache.EnforceTimeToLive); } @@ -85,96 +81,78 @@ public void AppliesPerCacheDefaultsIfNoPerItemValuesGiven() { // set expectations cache.DoInsertExposed("key", "value", expectedPerCacheTTL); - mocks.ReplayAll(); - // verify cache.Insert("key", "value", expectedPerCacheTTL); - mocks.VerifyAll(); + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened(); } [Test] public void AppliesPerCacheDefaultsIfTTLLessThanZero() { - // set expectations - cache.DoInsertExposed("key", "value", expectedPerCacheTTL); - cache.DoInsertExposed("key", "value", expectedPerCacheTTL); - cache.DoInsertExposed("key", "value", expectedPerCacheTTL); - cache.DoInsertExposed("key", "value", expectedPerCacheTTL); - mocks.ReplayAll(); - // verify cache.Insert("key", "value", new TimeSpan(Timeout.Infinite)); + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened(); + cache.Insert("key", "value", new TimeSpan(-1)); - cache.Insert("key", "value", new TimeSpan(Int64.MinValue)); + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened(); + + cache.Insert("key", "value", new TimeSpan(long.MinValue)); + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened(); + cache.Insert("key", "value", TimeSpan.MinValue); - mocks.VerifyAll(); + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened(); } [Test] public void AppliesPerCacheDefaultsIfEnfored() { - // set expectations - cache.DoInsertExposed("key", "value", expectedPerCacheTTL); - mocks.ReplayAll(); - // verify cache.EnforceTimeToLive = true; cache.Insert("key", "value", expectedPerItemTTL); - mocks.VerifyAll(); + + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened(); } [Test] public void AppliesZeroTTLIfTTLIsZero() { - // set expectations - cache.DoInsertExposed("key", "value", TimeSpan.Zero); - mocks.ReplayAll(); - // verify cache.Insert("key", "value", TimeSpan.Zero); - mocks.VerifyAll(); + + A.CallTo(() => cache.DoInsertExposed("key", "value", TimeSpan.Zero)).MustHaveHappened(); } [Test] public void AppliesPerItemTTLIfTTLGreaterZero() { - // set expectations - cache.DoInsertExposed("key", "value", expectedPerItemTTL); - mocks.ReplayAll(); - // verify cache.Insert("key", "value", expectedPerItemTTL); - mocks.VerifyAll(); + + A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerItemTTL)).MustHaveHappened(); } [Test] public void RemoveAllCausesCallsToRemove() { - // set expectations - cache.Remove(KEYS[0]); - cache.Remove(KEYS[1]); - mocks.ReplayAll(); - // verify cache.RemoveAll(KEYS); - mocks.VerifyAll(); + + A.CallTo(() => cache.Remove(KEYS[0])).MustHaveHappened(); + A.CallTo(() => cache.Remove(KEYS[1])).MustHaveHappened(); } [Test] public void ClearCausesCallToRemoveAllUsingKeys() { - // set expectations - Expect.Call(cache.Keys).Return(KEYS); - cache.RemoveAll(KEYS); - mocks.ReplayAll(); - // verify + A.CallTo(() => cache.Keys).Returns(this.KEYS); + cache.Clear(); - mocks.VerifyAll(); + + A.CallTo(() => cache.Keys).MustHaveHappened(); + A.CallTo(() => cache.RemoveAll(KEYS)).MustHaveHappened(); } [Test] public void CountUsingKeys() { // set expectations - Expect.Call(cache.Keys).Return(this.KEYS); - mocks.ReplayAll(); - // verify - Assert.AreEqual( this.KEYS.Length, cache.Count ); - mocks.VerifyAll(); + A.CallTo(() => cache.Keys).Returns(this.KEYS); + + Assert.AreEqual(this.KEYS.Length, cache.Count); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Collections/PriorityQueueTests.cs b/test/Spring/Spring.Core.Tests/Collections/PriorityQueueTests.cs index ec98005a4..89f9b2257 100644 --- a/test/Spring/Spring.Core.Tests/Collections/PriorityQueueTests.cs +++ b/test/Spring/Spring.Core.Tests/Collections/PriorityQueueTests.cs @@ -70,7 +70,7 @@ public void ThrowsArgumentExceptionForZeroCapacity() [Test] public void ThrowsArgumentNullExceptionForNullCollection() { - Assert.Throws(() => new PriorityQueue((ICollection) null)); + Assert.Throws(() => new PriorityQueue(null)); } [Test] diff --git a/test/Spring/Spring.Core.Tests/Context/Support/AbstractApplicationContextTests.cs b/test/Spring/Spring.Core.Tests/Context/Support/AbstractApplicationContextTests.cs index decbc1a37..e502ed7a4 100644 --- a/test/Spring/Spring.Core.Tests/Context/Support/AbstractApplicationContextTests.cs +++ b/test/Spring/Spring.Core.Tests/Context/Support/AbstractApplicationContextTests.cs @@ -18,11 +18,11 @@ #endregion -#region Imports - using System; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Core; using Spring.Core.IO; using Spring.Objects; @@ -32,8 +32,6 @@ using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Xml; -#endregion - namespace Spring.Context.Support { [TestFixture] @@ -60,7 +58,7 @@ public void Destroy() public void ContextAwareDisplayName() { - + } [Test] @@ -96,8 +94,7 @@ public void ExecutesAllContextEventHandlersAndRethrowsExceptionsThrownDuringCont [Test] public void DoesNotSearchParentContextForMessageSource() { - MockRepository mocks = new MockRepository(); - IMessageSource msgSource = (IMessageSource) mocks.DynamicMock(typeof (IMessageSource)); + IMessageSource msgSource = A.Fake(); MockApplicationContext parentCtx = new MockApplicationContext("parentContext"); parentCtx.ObjectFactory.RegisterSingleton(AbstractApplicationContext.MessageSourceObjectName, msgSource); MockApplicationContext childContext = new MockApplicationContext("childContext", parentCtx); @@ -112,8 +109,7 @@ public void DoesNotSearchParentContextForMessageSource() [Test] public void DoesNotSearchParentContextForEventRegistry() { - MockRepository mocks = new MockRepository(); - IEventRegistry eventRegistry = (IEventRegistry)mocks.DynamicMock(typeof(IEventRegistry)); + IEventRegistry eventRegistry = A.Fake(); MockApplicationContext parentCtx = new MockApplicationContext("parentContext"); parentCtx.ObjectFactory.RegisterSingleton(AbstractApplicationContext.EventRegistryObjectName, eventRegistry); MockApplicationContext childContext = new MockApplicationContext("childContext", parentCtx); @@ -398,7 +394,7 @@ public void ThrowsCannotLoadObjectTypeExceptionOnInvalidTypename() -")); +")); myContext.Refresh(); } catch (Exception e) diff --git a/test/Spring/Spring.Core.Tests/Context/Support/AbstractMessageSourceTests.cs b/test/Spring/Spring.Core.Tests/Context/Support/AbstractMessageSourceTests.cs index 616a3061d..ef3998c1e 100644 --- a/test/Spring/Spring.Core.Tests/Context/Support/AbstractMessageSourceTests.cs +++ b/test/Spring/Spring.Core.Tests/Context/Support/AbstractMessageSourceTests.cs @@ -18,36 +18,30 @@ #endregion -#region Imports - using System.Globalization; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Context.Support { [TestFixture] public sealed class AbstractMessageSourceTests : AbstractMessageSource { - private MockRepository mocks; [SetUp] public void Init() { - mocks = new MockRepository(); - resetMe(); + ResetMe(); } [Test] public void GetResolvableNullCodes() - { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.GetCodes()).Return(null); - Expect.Call(res.DefaultMessage).Return(null); - mocks.ReplayAll(); + { + var res = A.Fake(); + A.CallTo(() => res.DefaultMessage).Returns(null); + Assert.Throws(() => GetMessage(res, CultureInfo.CurrentCulture)); - mocks.VerifyAll(); } [Test] @@ -56,92 +50,79 @@ public void GetResolvableDefaultsToParentMessageSource() string MSGCODE = "nullCode"; object[] MSGARGS = new object[] { "arg1", "arg2" }; - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.GetArguments()).Return(MSGARGS); - Expect.Call(res.GetCodes()).Return(new string[] {MSGCODE}).Repeat.Once(); - - IMessageSource parentSource = mocks.StrictMock(); - Expect.Call(parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, MSGARGS)).Return( - "MockMessageSource"); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.GetArguments()).Returns(MSGARGS); + A.CallTo(() => res.GetCodes()).Returns(new string[] {MSGCODE}).Once(); + + IMessageSource parentSource = A.Fake(); + A.CallTo(() => parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, A._)).Returns("MockMessageSource"); ParentMessageSource = parentSource; - mocks.ReplayAll(); Assert.AreEqual("MockMessageSource", GetMessage(res, CultureInfo.CurrentCulture), "My Message"); - mocks.VerifyAll(); } [Test] public void GetMessageParentMessageSource() { object[] args = new object[] {"arguments"}; - IMessageSource parentSource = mocks.StrictMock(); - Expect.Call(parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, args)).Return( - "my parent message"); + IMessageSource parentSource = A.Fake(); + A.CallTo(() => parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, A._)).Returns("my parent message"); ParentMessageSource = parentSource; - mocks.ReplayAll(); Assert.AreEqual("my parent message", GetMessage("null", "message", CultureInfo.CurrentCulture, args[0])); - mocks.VerifyAll(); } [Test] public void GetMessageResolvableDefaultMessage() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.DefaultMessage).Return("MyDefaultMessage").Repeat.AtLeastOnce(); - Expect.Call(res.GetCodes()).Return(null); - Expect.Call(res.GetArguments()).Return(null); - mocks.ReplayAll(); - + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.DefaultMessage).Returns("MyDefaultMessage"); + A.CallTo(() => res.GetCodes()).Returns(null); + A.CallTo(() => res.GetArguments()).Returns(null); + Assert.AreEqual("MyDefaultMessage", GetMessage(res, CultureInfo.CurrentCulture), "Default"); - - mocks.VerifyAll(); } [Test] public void GetMessageResolvableReturnsFirstCode() { + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.DefaultMessage).Returns(null); + A.CallTo(() => res.GetCodes()).Returns(new string[] {"null"}); + A.CallTo(() => res.GetArguments()).Returns(null); - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce(); - Expect.Call(res.GetCodes()).Return(new string[] {"null"}); - Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce(); - mocks.ReplayAll(); UseCodeAsDefaultMessage = true; - Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code"); - mocks.VerifyAll(); + Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code"); } [Test] public void GetMessageResolvableNoValidMessage() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce(); - Expect.Call(res.GetCodes()).Return(null); - Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce(); - mocks.ReplayAll(); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.DefaultMessage).Returns(null); + A.CallTo(() => res.GetCodes()).Returns(null); + A.CallTo(() => res.GetArguments()).Returns(null); + Assert.Throws(() => GetMessage(res, CultureInfo.CurrentCulture)); } [Test] public void GetMessageResolvableValidMessageAndCode() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.GetCodes()).Return(new string[] {"code1"}); - Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce(); - mocks.ReplayAll(); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.GetCodes()).Returns(new string[] {"code1"}); + A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "arguments" }); + Assert.AreEqual("my arguments", GetMessage(res, CultureInfo.CurrentCulture), "Resolve"); - mocks.VerifyAll(); } [Test] public void GetMessageResolvableValidMessageAndCodeNullCulture() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.GetCodes()).Return(new string[] { "code1" }); - Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce(); - mocks.ReplayAll(); - Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve"); - mocks.VerifyAll(); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1" }); + A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "arguments" }); + + Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve"); } [Test] @@ -179,28 +160,25 @@ public void GetMessageNoValidMessage() [Test] public void GetMessageWithResolvableArguments() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.GetCodes()).Return(new string[] { "code1" }); - Expect.Call(res.GetArguments()).Return(new object[] { "my", "resolvable" }).Repeat.AtLeastOnce(); - mocks.ReplayAll(); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1" }); + A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "resolvable" }); + Assert.AreEqual("spring my resolvable", GetMessage("code2", CultureInfo.CurrentCulture, new object[] {"spring", res}), "Resolve"); - mocks.VerifyAll(); } [Test] public void GetMessageResolvableValidMessageAndCodNullMessageFormat() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.DefaultMessage).Return("myDefaultMessage").Repeat.AtLeastOnce(); - Expect.Call(res.GetCodes()).Return(new string[] { "nullCode" }); - Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce(); - mocks.ReplayAll(); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.DefaultMessage).Returns("myDefaultMessage"); + A.CallTo(() => res.GetCodes()).Returns(new string[] { "nullCode" }); + A.CallTo(() => res.GetArguments()).Returns(null); Assert.AreEqual("myDefaultMessage", GetMessage(res, null), "Resolve"); - mocks.VerifyAll(); } - private void resetMe() + private void ResetMe() { ParentMessageSource = null; UseCodeAsDefaultMessage = false; @@ -215,7 +193,7 @@ protected override string ResolveMessage(string code, CultureInfo cultureInfo) else if (code.Equals("nullCode")) { return null; - } + } else { return "{0} {1}"; diff --git a/test/Spring/Spring.Core.Tests/Context/Support/DefaultMessageSourceResolvableTests.cs b/test/Spring/Spring.Core.Tests/Context/Support/DefaultMessageSourceResolvableTests.cs index 2f5237d1b..5c7c19853 100644 --- a/test/Spring/Spring.Core.Tests/Context/Support/DefaultMessageSourceResolvableTests.cs +++ b/test/Spring/Spring.Core.Tests/Context/Support/DefaultMessageSourceResolvableTests.cs @@ -18,13 +18,11 @@ #endregion -#region Imports - using System.Text; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Context.Support { @@ -34,14 +32,11 @@ namespace Spring.Context.Support [TestFixture] public sealed class DefaultMessageSourceResolvableTests { - private MockRepository mocks; [SetUp] public void Init() { - mocks = new MockRepository(); } - [Test] public void InstantiationWithASingleCodeDefaultsToEmptyDefaultMessage() { @@ -49,7 +44,7 @@ public void InstantiationWithASingleCodeDefaultsToEmptyDefaultMessage() Assert.AreEqual(string.Empty, dmr.DefaultMessage, "Not defaulting to non null empty string value (it must)."); } - + [Test] public void NullLastCode() { @@ -86,16 +81,15 @@ public void ResolvableToStringNullArguments() [Test] public void DefaultResolvableFromExistingResolvable() { - IMessageSourceResolvable res = mocks.StrictMock(); - Expect.Call(res.DefaultMessage).Return("defaultMessageFromMock").Repeat.AtLeastOnce(); - Expect.Call(res.GetCodes()).Return(new string[] { "code1FromMock" }); - Expect.Call(res.GetArguments()).Return(new object[] { "ArgumentFromMock" }).Repeat.AtLeastOnce(); - mocks.ReplayAll(); - DefaultMessageSourceResolvable dmr = new DefaultMessageSourceResolvable(res); + IMessageSourceResolvable res = A.Fake(); + A.CallTo(() => res.DefaultMessage).Returns("defaultMessageFromMock"); + A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1FromMock" }); + A.CallTo(() => res.GetArguments()).Returns(new object[] { "ArgumentFromMock" }); + + DefaultMessageSourceResolvable dmr = new DefaultMessageSourceResolvable(res); Assert.AreEqual("defaultMessageFromMock", dmr.DefaultMessage, "default"); Assert.AreEqual("code1FromMock", dmr.LastCode, "codes"); Assert.AreEqual("ArgumentFromMock", (dmr.GetArguments())[0], "arguments"); - mocks.VerifyAll(); } private string getResolvableString() diff --git a/test/Spring/Spring.Core.Tests/Context/Support/DelegatingMessageSourceTests.cs b/test/Spring/Spring.Core.Tests/Context/Support/DelegatingMessageSourceTests.cs index f772a8598..9fbd48126 100644 --- a/test/Spring/Spring.Core.Tests/Context/Support/DelegatingMessageSourceTests.cs +++ b/test/Spring/Spring.Core.Tests/Context/Support/DelegatingMessageSourceTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,12 @@ #endregion -#region Imports - using System; using System.Globalization; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Context.Support { @@ -36,16 +34,14 @@ namespace Spring.Context.Support [TestFixture] public sealed class DelegatingMessageSourceTests { - private MockRepository mocks; - - private const string LookupKey = "rick"; + private const string LookupKey = "rick"; private IMessageSource _messageSource; private IMessageSource MockMessageSource { get { - return _messageSource; + return _messageSource; } } @@ -55,16 +51,14 @@ private IMessageSource MockMessageSource [SetUp] public void SetUp() { - mocks = new MockRepository(); - _messageSource = mocks.StrictMock(); + _messageSource = A.Fake(); } [Test] public void Instantiation() { DelegatingMessageSource source = new DelegatingMessageSource(); - Assert.IsNotNull(source.ParentMessageSource, - "ParentMessageSource property must *never* be null."); + Assert.IsNotNull(source.ParentMessageSource, "ParentMessageSource property must *never* be null."); } [Test] @@ -80,14 +74,11 @@ DelegatingMessageSource source [Test] public void GetMessage() { - const string expectedName = "Rick Evans"; - Expect.Call(MockMessageSource.GetMessage(LookupKey)).Return(expectedName); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); + const string expectedName = "Rick Evans"; + A.CallTo(() => MockMessageSource.GetMessage(LookupKey)).Returns(expectedName); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); string name = source.GetMessage(LookupKey); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -101,13 +92,10 @@ public void GetMessageNoDelegateTarget() public void GetMessageWithCulture() { const string expectedName = "Rick Evans"; - Expect.Call(MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture)).Return(expectedName); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); + A.CallTo(() => MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture)).Returns(expectedName); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); string name = source.GetMessage(LookupKey, CultureInfo.InvariantCulture); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -121,13 +109,10 @@ public void GetMessageWithCultureNoDelegateTarget() public void GetMessageWithParams() { const string expectedName = "Rick Evans"; - Expect.Call(MockMessageSource.GetMessage(LookupKey, new string[] {"Rick", "Evans"})).Return(expectedName); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); - string name = source.GetMessage(LookupKey, "Rick", "Evans"); + A.CallTo(() => MockMessageSource.GetMessage(LookupKey, new string[] {"Rick", "Evans"})).Returns(expectedName); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); + string name = source.GetMessage(LookupKey, "Rick", "Evans"); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -141,14 +126,10 @@ public void GetMessageWithParamsNoDelegateTarget() public void GetMessageWithCultureAndParams() { const string expectedName = "Rick Evans"; - Expect.Call(MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture, new string[] {"Rick", "Evans"})) - .Return(expectedName); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); + A.CallTo(() => MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture, new string[] {"Rick", "Evans"})).Returns(expectedName); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); string name = source.GetMessage(LookupKey, CultureInfo.InvariantCulture, "Rick", "Evans"); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -162,14 +143,11 @@ public void GetMessageWithCultureAndParamsNoDelegateTarget() public void GetMessageWithMessageSourceResolvableAndCulture() { const string expectedName = "Rick Evans"; - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - Expect.Call(MockMessageSource.GetMessage((IMessageSourceResolvable)null, CultureInfo.InvariantCulture)).Return(expectedName); - mocks.ReplayAll(); - string name = source.GetMessage( - (IMessageSourceResolvable) null, CultureInfo.InvariantCulture); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); + A.CallTo(() => MockMessageSource.GetMessage((IMessageSourceResolvable)null, CultureInfo.InvariantCulture)).Returns(expectedName); + + string name = source.GetMessage((IMessageSourceResolvable) null, CultureInfo.InvariantCulture); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -177,16 +155,12 @@ public void GetMessageWithNoParentMessageSourceAndMessageSourceResolvableAndCult { const string expectedName = "Rick Evans"; - IMessageSourceResolvable resolvable = mocks.StrictMock(); - Expect.Call(resolvable.DefaultMessage).Return(expectedName); - Expect.Call(resolvable.DefaultMessage).Return(expectedName); + IMessageSourceResolvable resolvable = A.Fake(); + A.CallTo(() => resolvable.DefaultMessage).Returns(expectedName); DelegatingMessageSource source = new DelegatingMessageSource(); - mocks.ReplayAll(); string name = source.GetMessage(resolvable, CultureInfo.InvariantCulture); Assert.AreEqual(expectedName, name); - //mock.Verify(); - mocks.VerifyAll(); } [Test] @@ -211,13 +185,10 @@ public void GetMessageWithNoParentMessageSourceAndNullDefaultMessageSourceResolv public void GetResourceObject() { const string expectedName = "Rick Evans"; - Expect.Call(MockMessageSource.GetResourceObject(LookupKey)).Return(expectedName); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); + A.CallTo(() => MockMessageSource.GetResourceObject(LookupKey)).Returns(expectedName); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); string name = (string) source.GetResourceObject(LookupKey); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -231,13 +202,10 @@ public void GetResourceObjectWithNoParentMessageSource() public void GetResourceObjectWithCulture() { const string expectedName = "Rick Evans"; - Expect.Call(MockMessageSource.GetResourceObject(LookupKey, CultureInfo.InvariantCulture)).Return(expectedName); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); + A.CallTo(() => MockMessageSource.GetResourceObject(LookupKey, CultureInfo.InvariantCulture)).Returns(expectedName); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); string name = (string) source.GetResourceObject(LookupKey, CultureInfo.InvariantCulture); Assert.AreEqual(expectedName, name); - mocks.VerifyAll(); } [Test] @@ -250,12 +218,9 @@ public void GetResourceObjectWithNoParentMessageSourceWithCulture() [Test] public void ApplyResources() { - MockMessageSource.ApplyResources((object) 12, "rick", CultureInfo.InvariantCulture); - DelegatingMessageSource source - = new DelegatingMessageSource(MockMessageSource); - mocks.ReplayAll(); + MockMessageSource.ApplyResources(12, "rick", CultureInfo.InvariantCulture); + DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource); source.ApplyResources(12, "rick", CultureInfo.InvariantCulture); - mocks.VerifyAll(); } [Test] diff --git a/test/Spring/Spring.Core.Tests/Context/Support/MessageSourceAccessorTests.cs b/test/Spring/Spring.Core.Tests/Context/Support/MessageSourceAccessorTests.cs index 10345a7b3..f9a8ac388 100644 --- a/test/Spring/Spring.Core.Tests/Context/Support/MessageSourceAccessorTests.cs +++ b/test/Spring/Spring.Core.Tests/Context/Support/MessageSourceAccessorTests.cs @@ -20,8 +20,9 @@ using System.Globalization; +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Globalization; namespace Spring.Context.Support @@ -47,29 +48,25 @@ public void TestFixtureTearDown() private readonly string MSGRESULT = "my message"; - private MockRepository mocks; private IMessageSource mockMsgSource; private IMessageSourceResolvable mockMsgSourceResolvable; [SetUp] public void SetUp() { - mocks = new MockRepository(); - mockMsgSource = mocks.StrictMock(); - mockMsgSourceResolvable = mocks.StrictMock(); + mockMsgSource = A.Fake(); + mockMsgSourceResolvable = A.Fake(); } [TearDown] public void TearDown() { - mocks.VerifyAll(); } [Test] public void GetMessageCodeCultureArgs() { - Expect.Call(mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)); @@ -78,8 +75,7 @@ public void GetMessageCodeCultureArgs() [Test] public void GetMessageCodeArgs() { - Expect.Call(mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource, MSGCULTURE); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGARGS)); @@ -88,8 +84,7 @@ public void GetMessageCodeArgs() [Test] public void GetMessageCodeArgsDefaultsToCurrentUICulture() { - Expect.Call(mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture, MSGARGS)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture, MSGARGS)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGARGS)); @@ -98,8 +93,7 @@ public void GetMessageCodeArgsDefaultsToCurrentUICulture() [Test] public void GetMessageCodeCulture() { - Expect.Call(mockMsgSource.GetMessage(MSGCODE, MSGCULTURE)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, MSGCULTURE)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGCULTURE)); @@ -108,8 +102,7 @@ public void GetMessageCodeCulture() [Test] public void GetMessageCodeDefaultsToCurrentUICulture() { - Expect.Call(mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE)); @@ -118,8 +111,7 @@ public void GetMessageCodeDefaultsToCurrentUICulture() [Test] public void GetMessageResolvableCulture() { - Expect.Call(mockMsgSource.GetMessage(mockMsgSourceResolvable, MSGCULTURE)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(mockMsgSourceResolvable, MSGCULTURE)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(mockMsgSourceResolvable, MSGCULTURE)); @@ -128,8 +120,7 @@ public void GetMessageResolvableCulture() [Test] public void GetMessageResolvableDefaultsToCurrentUICulture() { - Expect.Call(mockMsgSource.GetMessage(mockMsgSourceResolvable, CultureInfo.CurrentUICulture)).Return(MSGRESULT); - mocks.ReplayAll(); + A.CallTo(() => mockMsgSource.GetMessage(mockMsgSourceResolvable, CultureInfo.CurrentUICulture)).Returns(MSGRESULT); MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource); Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(mockMsgSourceResolvable)); diff --git a/test/Spring/Spring.Core.Tests/Context/Support/ResourceSetMessageSourceTests.cs b/test/Spring/Spring.Core.Tests/Context/Support/ResourceSetMessageSourceTests.cs index e87407e19..f8758104d 100644 --- a/test/Spring/Spring.Core.Tests/Context/Support/ResourceSetMessageSourceTests.cs +++ b/test/Spring/Spring.Core.Tests/Context/Support/ResourceSetMessageSourceTests.cs @@ -108,17 +108,17 @@ public void DoTestMessageAccess(bool hasParentContext, bool useCodeAsDefaultMess // MessageSourceAccessor functionality MessageSourceAccessor accessor = new MessageSourceAccessor(ac); - Assert.AreEqual("message3", accessor.GetMessage("code3", CultureInfo.CurrentUICulture, (object[])null)); + Assert.AreEqual("message3", accessor.GetMessage("code3", CultureInfo.CurrentUICulture, null)); // IMessageSourceResolveable - Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, (object[])null)); + Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, null)); IMessageSourceResolvable resolvable = new DefaultMessageSourceResolvable("code3"); Assert.AreEqual("message3", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture)); resolvable = new DefaultMessageSourceResolvable(new string[] { "code4", "code3" }); Assert.AreEqual("message3", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture)); - Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, (object[])null)); + Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, null)); resolvable = new DefaultMessageSourceResolvable(new string[] { "code4", "code3" }); Assert.AreEqual("message3", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture)); @@ -130,7 +130,7 @@ public void DoTestMessageAccess(bool hasParentContext, bool useCodeAsDefaultMess Assert.AreEqual("default", ac.GetMessage(null, "default", CultureInfo.CurrentUICulture, null)); Assert.AreEqual("default", ac.GetMessage(null, "default", CultureInfo.CurrentUICulture, arguments)); - /* not supported + /* not supported Assert.AreEqual("{0}, default", ac.GetMessage(null, "{0}, default", CultureInfo.CurrentUICulture, null)); */ @@ -142,7 +142,7 @@ public void DoTestMessageAccess(bool hasParentContext, bool useCodeAsDefaultMess resolvable = new DefaultMessageSourceResolvable(null, arguments, "default"); Assert.AreEqual("default", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture)); - /* not supported + /* not supported resolvable = new DefaultMessageSourceResolvable(null, null, "{0}, default"); Assert.AreEqual("{0}, default", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture)); */ @@ -154,12 +154,12 @@ public void DoTestMessageAccess(bool hasParentContext, bool useCodeAsDefaultMess // test message args Assert.AreEqual("Arg1, Arg2", ac.GetMessage("hello", CultureInfo.CurrentUICulture, new object[] { "Arg1", "Arg2" })); - /* not supported + /* not supported Assert.AreEqual("{0}, {1}", ac.GetMessage("hello", CultureInfo.CurrentUICulture, null)); */ - /* not supported + /* not supported Assert.AreEqual("Hello\nWorld", ac.GetMessage("escaped")); } else @@ -277,7 +277,7 @@ private void GetMessageLocalizationFallbacks(IMessageSource msgSource) Assert.AreEqual("Ово је Spring.NET", msgSource.GetMessage("MyMessage", new CultureInfo(CultureInfoUtils.SerbianCyrillicCultureName), new object[] { "Spring", ".NET" }), "message not as expected"); - + Assert.AreEqual("Visual Studio voli Spring.NET", msgSource.GetMessage("MyNewMessage", new CultureInfo(CultureInfoUtils.SerbianCyrillicCultureName), new object[] { "Spring", ".NET" }), "message not as expected"); diff --git a/test/Spring/Spring.Core.Tests/Core/TypeResolution/CachedTypeResolverTests.cs b/test/Spring/Spring.Core.Tests/Core/TypeResolution/CachedTypeResolverTests.cs index 9e7863b02..287ae2390 100644 --- a/test/Spring/Spring.Core.Tests/Core/TypeResolution/CachedTypeResolverTests.cs +++ b/test/Spring/Spring.Core.Tests/Core/TypeResolution/CachedTypeResolverTests.cs @@ -18,45 +18,39 @@ #endregion -#region Imports - using System; -using NUnit.Framework; -using Rhino.Mocks; +using FakeItEasy; -#endregion +using NUnit.Framework; namespace Spring.Core.TypeResolution { - /// - /// Unit tests for the CachedTypeResolver class. + /// + /// Unit tests for the CachedTypeResolver class. /// /// Rick Evans - [TestFixture] + [TestFixture] public sealed class CachedTypeResolverTests { - private MockRepository mocks; - [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] - public void ResolveWithNullTypeName() { - - ITypeResolver mockResolver = (ITypeResolver) mocks.DynamicMock(typeof(ITypeResolver)); + public void ResolveWithNullTypeName() + { + ITypeResolver mockResolver = A.Fake(); CachedTypeResolver resolver = new CachedTypeResolver(mockResolver); Assert.Throws(() => resolver.Resolve(null)); } - [Test] - public void InstantiateWithNullTypeResolver() - { + [Test] + public void InstantiateWithNullTypeResolver() + { Assert.Throws(() => new CachedTypeResolver(null)); - } + } } -} +} \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Expressions/ExpressionEvaluatorTests.cs b/test/Spring/Spring.Core.Tests/Expressions/ExpressionEvaluatorTests.cs index 468142dfa..baa489053 100644 --- a/test/Spring/Spring.Core.Tests/Expressions/ExpressionEvaluatorTests.cs +++ b/test/Spring/Spring.Core.Tests/Expressions/ExpressionEvaluatorTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -324,7 +324,7 @@ public void TestExpandoObjectWithNotExistedProperty() [Test(Description = "SPRNET-944")] public void DateTests() { - string dateLiteral = (string)ExpressionEvaluator.GetValue(null, "'date'"); + string dateLiteral = (string)ExpressionEvaluator.GetValue(null, "'date'"); Assert.AreEqual("date", dateLiteral); } @@ -1739,11 +1739,11 @@ public void TestDelegateFunctionExpressions() result = (double) ExpressionEvaluator.GetValue(null, "#max(5,25)", vars); Assert.AreEqual(25, result); - + } private delegate double DoubleFunction(double arg); - + private double Sqrt(double arg) { return Math.Sqrt(arg); @@ -1820,7 +1820,7 @@ public void TestCountAggregator() [Test] public void TestCustomCollectionProcessor() { - // Test for the purposes of creating documentation example. + // Test for the purposes of creating documentation example. Dictionary vars = new Dictionary(); vars["EvenSum"] = new IntEvenSumCollectionProcessor(); Assert.AreEqual(6, ExpressionEvaluator.GetValue(null, "{1, 2, 3, 4}.EvenSum()", vars)); @@ -1841,7 +1841,7 @@ public object Process(ICollection source, object[] args) if ((int)item % 2 == 0) { total = NumberUtils.Add(total, item); - } + } } else { @@ -2308,26 +2308,26 @@ public void TestSetEnumTypePropertyOrFieldFromNumeric() expField.SetValue(o, TestEnumTypePropertyClass.ESampleEnumType.Trunk); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); - expField.SetValue(o, ((Int16)1)); + expField.SetValue(o, (short) 1); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); - expField.SetValue(o, ((Int32)1)); + expField.SetValue(o, 1); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); - expField.SetValue(o, ((Int64)1)); + expField.SetValue(o, (long) 1); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); // test property set operations expProperty.SetValue(o, TestEnumTypePropertyClass.ESampleEnumType.Trunk); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); - expProperty.SetValue(o, ((Int16)1)); + expProperty.SetValue(o, (short) 1); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); - expProperty.SetValue(o, ((Int32)1)); + expProperty.SetValue(o, 1); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); - expProperty.SetValue(o, ((Int64)1)); + expProperty.SetValue(o, (long) 1); Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField); expProperty.SetValue(o, "Trunk"); @@ -2335,7 +2335,7 @@ public void TestSetEnumTypePropertyOrFieldFromNumeric() try { - expProperty.SetValue(o, ((double)1.0)); + expProperty.SetValue(o, 1.0); Assert.Fail("should throw"); } catch (TypeMismatchException e) diff --git a/test/Spring/Spring.Core.Tests/Globalization/Formatters/FilteringFormatterTests.cs b/test/Spring/Spring.Core.Tests/Globalization/Formatters/FilteringFormatterTests.cs index 893f58d4c..26767e08c 100644 --- a/test/Spring/Spring.Core.Tests/Globalization/Formatters/FilteringFormatterTests.cs +++ b/test/Spring/Spring.Core.Tests/Globalization/Formatters/FilteringFormatterTests.cs @@ -18,17 +18,14 @@ #endregion -#region Imports +using FakeItEasy; using NUnit.Framework; -using Rhino.Mocks; - -#endregion namespace Spring.Globalization.Formatters { /// - /// + /// /// /// Erich Eichinger [TestFixture] @@ -47,7 +44,7 @@ protected override string FilterValueToParse(string value) public virtual string DoFilterValueToParse(string value) { - return base.FilterValueToParse(value); + return base.FilterValueToParse(value); } protected override object FilterValueToFormat(object value) @@ -65,29 +62,24 @@ public virtual object DoFilterValueToFormat(object value) [Test] public void FiltersOnParseAndFormat() { - MockRepository mocks = new MockRepository(); - IFormatter underlyingFormatter = mocks.StrictMock(); - TestFilteringFormatter formatter = (TestFilteringFormatter) mocks.PartialMock(typeof (TestFilteringFormatter), underlyingFormatter); + IFormatter underlyingFormatter = A.Fake(); + TestFilteringFormatter formatter = A.Fake(x => x + .CallsBaseMethods() + .WithArgumentsForConstructor(new[] {underlyingFormatter})); string inputText = "inputText"; string filteredInputText = "filteredInputText"; object outputValue = new object(); object filteredOutputValue = new object(); - using(mocks.Ordered()) - { - Expect.Call(formatter.DoFilterValueToParse(inputText)).Return(filteredInputText); - Expect.Call(underlyingFormatter.Parse(filteredInputText)).Return(outputValue); + A.CallTo(() => formatter.DoFilterValueToParse(inputText)).Returns(filteredInputText); + A.CallTo(() => underlyingFormatter.Parse(filteredInputText)).Returns(outputValue); - Expect.Call(formatter.DoFilterValueToFormat(outputValue)).Return(filteredOutputValue); - Expect.Call(underlyingFormatter.Format(filteredOutputValue)).Return(inputText); - } - mocks.ReplayAll(); + A.CallTo(() => formatter.DoFilterValueToFormat(outputValue)).Returns(filteredOutputValue); + A.CallTo(() => underlyingFormatter.Format(filteredOutputValue)).Returns(inputText); Assert.AreSame(outputValue, formatter.Parse(inputText)); Assert.AreEqual(inputText, formatter.Format(outputValue)); - - mocks.VerifyAll(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/AbstractFactoryObjectTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/AbstractFactoryObjectTests.cs index 5185be19c..e467a3d47 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/AbstractFactoryObjectTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/AbstractFactoryObjectTests.cs @@ -18,13 +18,11 @@ #endregion -#region Imports - using System; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Objects.Factory.Config { @@ -35,41 +33,38 @@ namespace Spring.Objects.Factory.Config [TestFixture] public sealed class AbstractFactoryObjectTests { - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } [Test] public void DisposeCallbackIsNotInvokedOnDisposeIfInPrototypeMode() { - IDisposable disposable = mocks.StrictMock(); + IDisposable disposable = A.Fake(); DummyFactoryObject factory = new DummyFactoryObject(disposable); - mocks.ReplayAll(); + factory.IsSingleton = false; factory.GetObject(); factory.Dispose(); + // in prototype mode, so the Dispose() method of the object must not be called... - mocks.VerifyAll(); + A.CallTo(() => disposable.Dispose()).MustNotHaveHappened(); } [Test] public void DisposeCallbackIsInvokedOnDispose() { - IDisposable disposable = mocks.StrictMock(); - disposable.Dispose(); - LastCall.On(disposable).Repeat.Once(); - DummyFactoryObject factory = new DummyFactoryObject(disposable); - mocks.ReplayAll(); + IDisposable disposable = A.Fake(); + + DummyFactoryObject factory = new DummyFactoryObject(disposable); factory.AfterPropertiesSet(); factory.Dispose(); - mocks.VerifyAll(); + + A.CallTo(() => disposable.Dispose()).MustHaveHappenedOnceExactly(); } - private sealed class DummyFactoryObject : AbstractFactoryObject + private sealed class DummyFactoryObject : AbstractFactoryObject { public object theObject; diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CommandLineArgsVariableSourceTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CommandLineArgsVariableSourceTests.cs index fe739a110..b52230814 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CommandLineArgsVariableSourceTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CommandLineArgsVariableSourceTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ public void TestVariablesResolutionWithCustomPrefixAndSeparator() public void TestLiveVariablesResolutionWithTestDriven() { CommandLineArgsVariableSource vs = new CommandLineArgsVariableSource(); - Assert.IsTrue(((string) vs.ResolveVariable("AssemblyName")).StartsWith("TestDriven.TestRunner.Server")); + Assert.IsTrue(vs.ResolveVariable("AssemblyName").StartsWith("TestDriven.TestRunner.Server")); } } } diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CustomConverterConfigurerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CustomConverterConfigurerTests.cs index 53cb8ceeb..b54bc325b 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CustomConverterConfigurerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/CustomConverterConfigurerTests.cs @@ -18,16 +18,14 @@ #endregion -#region Imports - using System; using System.Collections; using System.ComponentModel; using System.Drawing; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Objects.Factory.Config { @@ -38,15 +36,12 @@ namespace Spring.Objects.Factory.Config [TestFixture] public sealed class CustomConverterConfigurerTests { - private MockRepository mocks; private IConfigurableListableObjectFactory factory; [SetUp] public void SetUp() { - mocks = new MockRepository(); - factory = mocks.StrictMock(); - + factory = A.Fake(); } [Test] @@ -93,9 +88,6 @@ public void DontSupplyAnyCustomConverters() CustomConverterConfigurer config = new CustomConverterConfigurer(); config.CustomConverters = null; config.PostProcessObjectFactory(factory); - mocks.ReplayAll(); - - mocks.VerifyAll(); } [Test] @@ -106,21 +98,16 @@ public void SunnyDayScenario() DateTimeConverter dateTimeConverter = new DateTimeConverter(); Type colorType = typeof(Color); ColorConverter colorConverter = new ColorConverter(); - + converters.Add(dateTimeType, dateTimeConverter); converters.Add(colorType, colorConverter); factory.RegisterCustomConverter(dateTimeType, dateTimeConverter); factory.RegisterCustomConverter(colorType, colorConverter); - mocks.ReplayAll(); - CustomConverterConfigurer config = new CustomConverterConfigurer(); config.CustomConverters = converters; config.PostProcessObjectFactory(factory); - - mocks.VerifyAll(); - } } } diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectFactoryCreatingFactoryObjectTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectFactoryCreatingFactoryObjectTests.cs index 4747c1fe9..cd9b035c6 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectFactoryCreatingFactoryObjectTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectFactoryCreatingFactoryObjectTests.cs @@ -18,13 +18,11 @@ #endregion -#region Imports - using System; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Objects.Factory.Config { @@ -36,28 +34,23 @@ namespace Spring.Objects.Factory.Config [TestFixture] public sealed class ObjectFactoryCreatingFactoryObjectTests { - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } [Test] public void SunnyDay() { TestObject dude = new TestObject("Rick Evans", 30); - IObjectFactory objectFactory = mocks.StrictMock(); + IObjectFactory objectFactory = A.Fake(); const string lookupObjectName = "rick"; - Expect.Call(objectFactory.GetObject(lookupObjectName)).Return(dude).Repeat.Twice(); + A.CallTo(() => objectFactory.GetObject(lookupObjectName)).Returns(dude).Twice(); ObjectFactoryCreatingFactoryObject factory = new ObjectFactoryCreatingFactoryObject(); factory.ObjectFactory = objectFactory; factory.TargetObjectName = lookupObjectName; factory.AfterPropertiesSet(); - mocks.ReplayAll(); - IGenericObjectFactory gof = (IGenericObjectFactory) factory.GetObject(); IGenericObjectFactory gofOther = (IGenericObjectFactory) factory.GetObject(); Assert.IsTrue(Object.ReferenceEquals(gof, gofOther), @@ -68,23 +61,21 @@ public void SunnyDay() Assert.IsNotNull(two, "Must never return null (IFactoryObject contract)."); Assert.IsTrue(Object.ReferenceEquals(one, two), "Not returning the same instance."); - mocks.VerifyAll(); } [Test] public void PrototypeModeWithSingletonTarget() { - TestObject dude = new TestObject("Rick Evans", 30); - IObjectFactory objectFactory = mocks.StrictMock(); - const string lookupObjectName = "rick"; - Expect.Call(objectFactory.GetObject(lookupObjectName)).Return(dude).Repeat.Twice(); + TestObject dude = new TestObject("Rick Evans", 30); + IObjectFactory objectFactory = A.Fake(); + const string lookupObjectName = "rick"; + A.CallTo(() => objectFactory.GetObject(lookupObjectName)).Returns(dude).Twice(); ObjectFactoryCreatingFactoryObject factory = new ObjectFactoryCreatingFactoryObject(); factory.ObjectFactory = objectFactory; factory.TargetObjectName = lookupObjectName; factory.IsSingleton = false; factory.AfterPropertiesSet(); - mocks.ReplayAll(); IGenericObjectFactory gofOne = (IGenericObjectFactory) factory.GetObject(); IGenericObjectFactory gofTwo = (IGenericObjectFactory) factory.GetObject(); Assert.IsFalse(Object.ReferenceEquals(gofOne, gofTwo), @@ -95,7 +86,6 @@ public void PrototypeModeWithSingletonTarget() Assert.IsNotNull(two, "Must never return null (IFactoryObject contract)."); Assert.IsTrue(Object.ReferenceEquals(one, two), "Not returning the same instance to singleton object."); - mocks.VerifyAll(); } [Test] diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectReferenceFactoryObjectTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectReferenceFactoryObjectTests.cs index a5dc0d68c..4c11d6334 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectReferenceFactoryObjectTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ObjectReferenceFactoryObjectTests.cs @@ -18,115 +18,98 @@ #endregion -#region Imports - using System; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Objects.Factory.Config { - /// - /// Unit tests for the ObjectReferenceFactoryObject class. + /// + /// Unit tests for the ObjectReferenceFactoryObject class. /// /// Rick Evans - [TestFixture] + [TestFixture] public sealed class ObjectReferenceFactoryObjectTests { - private MockRepository mocks; - private IObjectFactory factory; + private IObjectFactory factory; [SetUp] public void SetUp() { - mocks = new MockRepository(); - factory = mocks.StrictMock(); + factory = A.Fake(); } [Test] public void NullTargetObjectName() - { - ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); + { + ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); // simulate IFactoryObjectAware interface... Assert.Throws(() => fac.ObjectFactory = null); } - - [Test] - public void WhitespaceTargetObjectName() - { - ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); - fac.TargetObjectName = string.Empty; + + [Test] + public void WhitespaceTargetObjectName() + { + ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); + fac.TargetObjectName = string.Empty; // simulate IFactoryObjectAware interface... Assert.Throws(() => fac.ObjectFactory = null); - } - - [Test] - public void FactoryDoesNotContainTargetObject() - { - Expect.Call(factory.ContainsObject("bojangles")).Return(false); - mocks.ReplayAll(); - - ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); - fac.TargetObjectName = "bojangles"; - try - { - // simulate IFactoryObjectAware interface... - fac.ObjectFactory = factory; - Assert.Fail("Must have bailed with a " + - "NoSuchObjectDefinitionException 'cos the object doesn't " + - "exist in the associated factory."); - } - catch (NoSuchObjectDefinitionException) - { - mocks.VerifyAll(); - } - } - - [Test] - public void DelegatesThroughToFactoryFor_IsSingleton() - { - Expect.Call(factory.ContainsObject("bojangles")).Return(true); - Expect.Call(factory.IsSingleton("bojangles")).Return(true); - mocks.ReplayAll(); + } + + [Test] + public void FactoryDoesNotContainTargetObject() + { + A.CallTo(() => factory.ContainsObject("bojangles")).Returns(false); ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); - fac.TargetObjectName = "bojangles"; - fac.ObjectFactory = factory; - - Assert.IsTrue(fac.IsSingleton); - mocks.VerifyAll(); - } - - [Test] - public void DelegatesThroughToFactoryFor_GetObject() - { - Expect.Call(factory.ContainsObject("bojangles")).Return(true); - Expect.Call(factory.GetObject("bojangles")).Return("Rick"); - mocks.ReplayAll(); - - ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); - fac.TargetObjectName = "bojangles"; - fac.ObjectFactory = factory; - - Assert.AreEqual("Rick", fac.GetObject()); - mocks.VerifyAll(); - } - - [Test] - public void DelegatesThroughToFactoryFor_ObjectType() - { - Expect.Call(factory.ContainsObject("bojangles")).Return(true); - Expect.Call(factory.GetType("bojangles")).Return(GetType()); - mocks.ReplayAll(); - - ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); - fac.TargetObjectName = "bojangles"; - fac.ObjectFactory = factory; - - Assert.AreEqual(GetType(), fac.ObjectType); - mocks.VerifyAll(); - } + fac.TargetObjectName = "bojangles"; + + // simulate IFactoryObjectAware interface... + Assert.Throws(() => fac.ObjectFactory = factory, + "Must have bailed with a " + + "NoSuchObjectDefinitionException 'cos the object doesn't " + + "exist in the associated factory."); + } + + [Test] + public void DelegatesThroughToFactoryFor_IsSingleton() + { + A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true); + A.CallTo(() => factory.IsSingleton("bojangles")).Returns(true); + + ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); + fac.TargetObjectName = "bojangles"; + fac.ObjectFactory = factory; + + Assert.IsTrue(fac.IsSingleton); + } + + [Test] + public void DelegatesThroughToFactoryFor_GetObject() + { + A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true); + A.CallTo(() => factory.GetObject("bojangles")).Returns("Rick"); + + ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); + fac.TargetObjectName = "bojangles"; + fac.ObjectFactory = factory; + + Assert.AreEqual("Rick", fac.GetObject()); + } + + [Test] + public void DelegatesThroughToFactoryFor_ObjectType() + { + A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true); + A.CallTo(() => factory.GetType("bojangles")).Returns(GetType()); + + ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); + fac.TargetObjectName = "bojangles"; + fac.ObjectFactory = factory; + + Assert.AreEqual(GetType(), fac.ObjectType); + } } -} +} \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyOverrideConfigurerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyOverrideConfigurerTests.cs index 80753be10..f12a1e1d2 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyOverrideConfigurerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyOverrideConfigurerTests.cs @@ -18,19 +18,17 @@ #endregion -#region Imports - using System.Collections.Specialized; using Common.Logging; using Common.Logging.Simple; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Context.Support; using Spring.Core.IO; using Spring.Objects.Factory.Xml; -#endregion - namespace Spring.Objects.Factory.Config { /// @@ -40,13 +38,9 @@ namespace Spring.Objects.Factory.Config [TestFixture] public sealed class PropertyOverrideConfigurerTests { - - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } /// @@ -56,7 +50,7 @@ public void Setup() public void FixtureSetUp() { // enable (null appender) logging, just to ensure that the logging code is correct - LogManager.Adapter = new NoOpLoggerFactoryAdapter(); + LogManager.Adapter = new NoOpLoggerFactoryAdapter(); } [Test] @@ -90,7 +84,7 @@ public void OverridePropertyValue() pvs.Add("Age", 27); pvs.Add("Name", "Bruno"); ac.RegisterSingleton("tb1", typeof(TestObject), pvs); - + pvs = new MutablePropertyValues(); pvs.Add("Properties", ""); ac.RegisterSingleton("configurer", typeof (PropertyOverrideConfigurer), pvs); @@ -105,11 +99,11 @@ public void OverridePropertyValue() public void OverridePropertyReference() { StaticApplicationContext ac = new StaticApplicationContext(); - + MutablePropertyValues pvs = new MutablePropertyValues(); pvs.Add("Spouse", new RuntimeObjectReference("spouse1")); ac.RegisterSingleton("tb1", typeof(TestObject), pvs); - + ac.RegisterSingleton("spouse1", typeof(TestObject), new MutablePropertyValues()); ac.RegisterSingleton("spouse2", typeof(TestObject), new MutablePropertyValues()); @@ -144,23 +138,15 @@ public void OverridePropertyExpression() [Test] public void MalformedOverrideKey() { - IConfigurableListableObjectFactory objectFactory = mocks.StrictMock(); + IConfigurableListableObjectFactory objectFactory = A.Fake(); IConfigurableListableObjectFactory fac = objectFactory; PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer(); NameValueCollection defaultProperties = new NameValueCollection(); defaultProperties.Add("malformedKey", "Rick Evans"); cfg.Properties = defaultProperties; - mocks.ReplayAll(); - try - { - cfg.PostProcessObjectFactory(fac); - Assert.Fail("Should have had a FatalObjectException at this point because of a malformed key."); - } - catch (FatalObjectException) - { - } - mocks.VerifyAll(); + + Assert.Throws(() => cfg.PostProcessObjectFactory(fac)); } [Test] @@ -168,20 +154,17 @@ public void MissingObjectDefinitionDoesntRaiseFatalException() { const string valueTo_NOT_BeOveridden = "Jenny Lewis"; TestObject foo = new TestObject(valueTo_NOT_BeOveridden, 30); - IConfigurableListableObjectFactory objectFactory = mocks.StrictMock(); - Expect.Call(objectFactory.GetObjectDefinition("rubbish")).Return(null); + IConfigurableListableObjectFactory objectFactory = A.Fake(); + A.CallTo(() => objectFactory.GetObjectDefinition("rubbish")).Returns(null); IConfigurableListableObjectFactory fac = objectFactory; PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer(); NameValueCollection defaultProperties = new NameValueCollection(); defaultProperties.Add("rubbish.Name", "Rick Evans"); cfg.Properties = defaultProperties; - mocks.ReplayAll(); - cfg.PostProcessObjectFactory(fac); - Assert.AreEqual(valueTo_NOT_BeOveridden, foo.Name, - "Property value was overridden, but a rubbish objectName root was supplied."); - mocks.VerifyAll(); + cfg.PostProcessObjectFactory(fac); + Assert.AreEqual(valueTo_NOT_BeOveridden, foo.Name, "Property value was overridden, but a rubbish objectName root was supplied."); } [Test] diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPathFactoryObjectTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPathFactoryObjectTests.cs index 5e35eeca9..4cce955d4 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPathFactoryObjectTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPathFactoryObjectTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,12 @@ #endregion -#region Imports - using System; + +using FakeItEasy; using NUnit.Framework; -using Rhino.Mocks; -using Spring.Core; -#endregion +using Spring.Core; namespace Spring.Objects.Factory.Config { @@ -36,22 +34,19 @@ namespace Spring.Objects.Factory.Config [TestFixture] public sealed class PropertyPathFactoryObjectTests { - private MockRepository mocks; private IObjectFactory mockFactory; [SetUp] public void SetUp() { - mocks = new MockRepository(); - mockFactory = mocks.StrictMock(); + mockFactory = A.Fake(); } [Test] public void GetObject_ViaTargetObjectName() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); - Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28)); - mocks.ReplayAll(); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); + A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28)); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.TargetObjectName = "foo"; @@ -59,17 +54,15 @@ public void GetObject_ViaTargetObjectName() fac.ObjectFactory = mockFactory; string name = (string) fac.GetObject(); Assert.AreEqual("Fiona Apple", name); - mocks.VerifyAll(); } [Test] public void GetObject_ViaTargetObjectNameWithNestedPropertyPath() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); TestObject target = new TestObject("Fiona Apple", 28); - target.Spouse = target; - Expect.Call(mockFactory.GetObject("foo")).Return(target); - mocks.ReplayAll(); + target.Spouse = target; + A.CallTo(() => mockFactory.GetObject("foo")).Returns(target); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.TargetObjectName = "foo"; @@ -77,30 +70,26 @@ public void GetObject_ViaTargetObjectNameWithNestedPropertyPath() fac.ObjectFactory = mockFactory; string name = (string) fac.GetObject(); Assert.AreEqual("Fiona Apple", name); - mocks.VerifyAll(); } [Test] public void GetObject_ViaObjectName() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); - Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28)); - mocks.ReplayAll(); + A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28)); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.ObjectName = "foo.name"; fac.ObjectFactory = mockFactory; string name = (string) fac.GetObject(); Assert.AreEqual("Fiona Apple", name); - mocks.VerifyAll(); } [Test] public void GetObject_ViaObjectNameThatStartsWithAPeriod() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); - Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28)); - mocks.ReplayAll(); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); + A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28)); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.ObjectName = ".foo.name"; @@ -110,41 +99,36 @@ public void GetObject_ViaObjectNameThatStartsWithAPeriod() [Test] public void GetObject_MakeSureLeadingAndTrailingWhitspaceIsTrimmed() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); - Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28)); - mocks.ReplayAll(); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); + A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28)); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.ObjectName = " \nfoo.name "; fac.ObjectFactory = mockFactory; string name = (string) fac.GetObject(); Assert.AreEqual("Fiona Apple", name); - mocks.VerifyAll(); } [Test] public void GetObject_ViaObjectNameWithNestedPropertyPath() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); TestObject target = new TestObject("Fiona Apple", 28); - target.Spouse = target; - Expect.Call(mockFactory.GetObject("foo")).Return(target); - mocks.ReplayAll(); + target.Spouse = target; + A.CallTo(() => mockFactory.GetObject("foo")).Returns(target); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.ObjectName = "foo.spouse.name"; fac.ObjectFactory = mockFactory; string name = (string) fac.GetObject(); Assert.AreEqual("Fiona Apple", name); - mocks.VerifyAll(); } [Test] public void GetObject_ViaObjectNameWithNullInNestedPropertyPath() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); - Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28)); - mocks.ReplayAll(); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); + A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28)); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.ObjectName = "foo.spouse.name"; @@ -154,9 +138,8 @@ public void GetObject_ViaObjectNameWithNullInNestedPropertyPath() [Test] public void GetObject_PropertyPathEvaluatesToNull() { - Expect.Call(mockFactory.IsSingleton("foo")).Return(true); - Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject(null, 28)); - mocks.ReplayAll(); + A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true); + A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject(null, 28)); PropertyPathFactoryObject fac = new PropertyPathFactoryObject(); fac.ObjectName = "foo.name"; diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPlaceholderConfigurerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPlaceholderConfigurerTests.cs index d15490a64..d74e8e9ca 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPlaceholderConfigurerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/PropertyPlaceholderConfigurerTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,22 +18,21 @@ #endregion -#region Imports - using System; using System.Collections; using System.Collections.Specialized; using System.IO; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Collections; using Spring.Context; using Spring.Context.Support; using Spring.Core.IO; using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Xml; - -#endregion +using Spring.Util; namespace Spring.Objects.Factory.Config { @@ -44,37 +43,34 @@ namespace Spring.Objects.Factory.Config [TestFixture] public sealed class PropertyPlaceholderConfigurerTests { - private MockRepository mocks; private static string testConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Northwind.mdb;User ID=Admin;Password=;"; private static string testConnectionStringTwo = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Northwind.mdb;User ID=Admin;Password=Ernie;"; [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] public void MismatchBetweenNumberOfConfigNamesAndNumberOfLocations() { PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); - cfg.Locations = new IResource[] { mocks.StrictMock() }; // will never get to the point where we check the validity + cfg.Locations = new IResource[] { A.Fake() }; // will never get to the point where we check the validity cfg.ConfigSections = new string[] { "", "" }; - Assert.Throws(() => cfg.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)))); + Assert.Throws(() => cfg.PostProcessObjectFactory(A.Fake())); } [Test] public void OneConfigNameIsOKForLotsOfLocations() { PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); - IResource mock = mocks.StrictMock(); - Expect.Call(mock.Exists).Return(true); - Expect.Call(mock.InputStream).Throw(new FileNotFoundException()); - mocks.ReplayAll(); + IResource mock = A.Fake(); + A.CallTo(() => mock.Exists).Returns(true); + A.CallTo(() => mock.InputStream).Throws(new FileNotFoundException()); cfg.Locations = new IResource [] {mock}; cfg.ConfigSections = new string[] { "" }; - Assert.Throws(() => cfg.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)))); + Assert.Throws(() => cfg.PostProcessObjectFactory(A.Fake())); } [Test] @@ -82,13 +78,12 @@ public void ChokesOnBadResourceLocationIfIgnoreBadResourcesFlagNotSetToTrue() { PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.IgnoreResourceNotFound = false; - IResource mock = mocks.StrictMock(); - Expect.Call(mock.Exists).Return(false); - mocks.ReplayAll(); + IResource mock = A.Fake(); + A.CallTo(() => mock.Exists).Returns(false); cfg.Locations = new IResource [] { mock}; cfg.ConfigSections = new string[] { "" }; - Assert.Throws(() => cfg.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)))); + Assert.Throws(() => cfg.PostProcessObjectFactory(A.Fake())); } [Test] @@ -96,17 +91,14 @@ public void DoesNotChokeOnBadResourceLocationIfIgnoreBadResourcesFlagSetToTrue() { PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.IgnoreResourceNotFound = true; - IResource mockResource = mocks.StrictMock(); - Expect.Call(mockResource.Exists).Return(false); + IResource mockResource = A.Fake(); + A.CallTo(() => mockResource.Exists).Returns(false); cfg.Location = mockResource; cfg.ConfigSections = new string[] { "" }; - IConfigurableListableObjectFactory mockFactory = (IConfigurableListableObjectFactory)mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)); - Expect.Call(mockFactory.GetObjectDefinitionNames(false)).Return(new string[] {}); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mockFactory = A.Fake(); + A.CallTo(() => mockFactory.GetObjectDefinitionNames(false)).Returns(new string[] {}); cfg.PostProcessObjectFactory(mockFactory); - - mocks.VerifyAll(); } [Test] @@ -143,12 +135,10 @@ public void WithDefaultProperties() pvs.Add(theProperty, placeholder); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string [] {defName}); - Expect.Call(mock.GetObjectDefinition(defName, false)).Return(def); - Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments(); - mocks.ReplayAll(); - + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string [] {defName}); + A.CallTo(() => mock.GetObjectDefinition(defName, false)).Returns(def); + PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); NameValueCollection defaultProperties = new NameValueCollection(); const string expectedName = "Rick Evans"; @@ -158,7 +148,7 @@ public void WithDefaultProperties() Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value, "Property placeholder value was not replaced with the resolved value."); - mocks.VerifyAll(); + A.CallTo(() => mock.AddEmbeddedValueResolver(A._)).MustHaveHappened(); } [Test] @@ -173,11 +163,9 @@ public void IncludingAncestors() pvs.Add(theProperty, placeholder); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(true)).Return(new string[] { defName }); - Expect.Call(mock.GetObjectDefinition(defName, true)).Return(def); - Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments(); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(true)).Returns(new string[] { defName }); + A.CallTo(() => mock.GetObjectDefinition(defName, true)).Returns(def); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.IncludeAncestors = true; @@ -190,14 +178,14 @@ public void IncludingAncestors() Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value, "Property placeholder value was not replaced with the resolved value."); - mocks.VerifyAll(); + A.CallTo(() => mock.AddEmbeddedValueResolver(A._)).MustHaveHappened(); } - /// - /// Fallback is the default mode. Check if the PROCESSOR_ARCHITECTURE - /// variable is replaced. - /// - [Test] + /// + /// Fallback is the default mode. Check if the PROCESSOR_ARCHITECTURE + /// variable is replaced. + /// + [Test] public void WithEnvironmentVariableFallback() { StaticApplicationContext ac = new StaticApplicationContext(); @@ -415,10 +403,9 @@ public void ChokesOnCircularReferenceToPlaceHolder() const string expectedName = "ba${foo}r"; properties.Add("foo", expectedName); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string[] {"foo"}); - Expect.Call(mock.GetObjectDefinition(null, false)).IgnoreArguments().Return(def); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string[] {"foo"}); + A.CallTo(() => mock.GetObjectDefinition(null, false)).WithAnyArguments().Returns(def); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.Properties = properties; @@ -430,7 +417,6 @@ public void ChokesOnCircularReferenceToPlaceHolder() catch (ObjectDefinitionStoreException) { } - mocks.VerifyAll(); } [Test] @@ -446,19 +432,17 @@ public void ReplacesNamedCtorArgument() const string expectedName = "Rick"; properties.Add("hope.floats", expectedName); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string[] {"foo"}); - Expect.Call(mock.GetObjectDefinition(null, false)).IgnoreArguments().Return(def); - Expect.Call(delegate { mock.AddEmbeddedValueResolver(null); }).IgnoreArguments(); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string[] {"foo"}); + A.CallTo(() => mock.GetObjectDefinition(null, false)).WithAnyArguments().Returns(def); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.Properties = properties; cfg.PostProcessObjectFactory(mock); - mocks.VerifyAll(); + A.CallTo(() => mock.AddEmbeddedValueResolver(A._)).MustHaveHappened(); - Assert.AreEqual(expectedName, + Assert.AreEqual(expectedName, def.ConstructorArgumentValues.GetNamedArgumentValue("name").Value, "Named argument placeholder value was not replaced."); } @@ -476,20 +460,18 @@ public void UsingCustomMarkers() const string expectedName = "Rick"; properties.Add("hope.floats", expectedName); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string[] {"foo"}); - Expect.Call(mock.GetObjectDefinition(null, false)).IgnoreArguments().Return(def); - Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments(); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string[] {"foo"}); + A.CallTo(() => mock.GetObjectDefinition(null, false)).WithAnyArguments().Returns(def); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.PlaceholderPrefix = cfg.PlaceholderSuffix = "#"; cfg.Properties = properties; cfg.PostProcessObjectFactory(mock); - mocks.VerifyAll(); + A.CallTo(() => mock.AddEmbeddedValueResolver(null)).WithAnyArguments().MustHaveHappened(); - Assert.AreEqual(expectedName, + Assert.AreEqual(expectedName, def.ConstructorArgumentValues.GetNamedArgumentValue("name").Value, "Named argument placeholder value was not replaced."); } @@ -574,21 +556,19 @@ public void WithIgnoreUnresolvablePlaceholder() pvs.Add("name", placeholder); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string [] {defName}); - Expect.Call(mock.GetObjectDefinition(defName, false)).Return(def); - Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments(); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string [] {defName}); + A.CallTo(() => mock.GetObjectDefinition(defName, false)).Returns(def); PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer(); cfg.IgnoreUnresolvablePlaceholders = true; cfg.PostProcessObjectFactory(mock); Assert.AreEqual(placeholder, foo.Name); - mocks.VerifyAll(); + A.CallTo(() => mock.AddEmbeddedValueResolver(null)).WithAnyArguments().MustHaveHappened(); } - [Test] + [Test] public void ViaXML() { IResource resource = new ReadOnlyXmlTestResource("PropertyResourceConfigurerTests.xml", GetType()); diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ResourceHandlerConfigurerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ResourceHandlerConfigurerTests.cs index 37c1357c4..c028bab44 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ResourceHandlerConfigurerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/ResourceHandlerConfigurerTests.cs @@ -19,16 +19,16 @@ #endregion using System.Collections; -using NUnit.Framework; -using Rhino.Mocks; +using FakeItEasy; + +using NUnit.Framework; using Spring.Core.IO; using Spring.Util; namespace Spring.Objects.Factory.Config { - /// /// Unit tests for the TypeAliasConfigurer class /// @@ -36,12 +36,9 @@ namespace Spring.Objects.Factory.Config [TestFixture] public class ResourceHandlerConfigurerTests { - private MockRepository mocks; - [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] @@ -68,7 +65,7 @@ public void UseInvalidTypeForDictionaryValue() ResourceHandlerConfigurer resourceHandlerConfiguer = new ResourceHandlerConfigurer(); resourceHandlerConfiguer.ResourceHandlers = resourceHandlers; - Assert.Throws(() => resourceHandlerConfiguer.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)))); + Assert.Throws(() => resourceHandlerConfiguer.PostProcessObjectFactory(A.Fake())); } [Test] @@ -81,7 +78,7 @@ public void UseNonResolvableTypeForDictionaryValue() resourceHandlerConfiguer.ResourceHandlers = resourceHandlers; - Assert.Throws(() => resourceHandlerConfiguer.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)))); + Assert.Throws(() => resourceHandlerConfiguer.PostProcessObjectFactory(A.Fake())); } [Test] @@ -112,7 +109,7 @@ private void CreateConfigurerAndTestNewProtcol(IDictionary resourceHandlers) resourceHandlerConfiguer.Order = 1; - resourceHandlerConfiguer.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory))); + resourceHandlerConfiguer.PostProcessObjectFactory(A.Fake()); //todo investigate mocking the typeregistry, for now ask the actual one for information. Assert.IsTrue(ResourceHandlerRegistry.IsHandlerRegistered("httpsss"), diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/SharedStateAwareProcessorTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/SharedStateAwareProcessorTests.cs index c113e93e3..70d615f9d 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/SharedStateAwareProcessorTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/SharedStateAwareProcessorTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,10 @@ using System; using System.Collections; + +using FakeItEasy; using NUnit.Framework; -using Rhino.Mocks; + using Spring.Objects.Factory.Support; using Spring.Objects.Support; @@ -113,25 +115,19 @@ public void IgnoresAlreadyPopulatedState() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); - MockRepository mocks = new MockRepository(); - ISharedStateFactory ssf1 = mocks.StrictMock(); - ISharedStateAware ssa = (ISharedStateAware)mocks.DynamicMock( typeof( ISharedStateAware ) ); + ISharedStateFactory ssf1 = A.Fake(); + ISharedStateAware ssa = A.Fake(); SharedStateAwareProcessor ssap = new SharedStateAwareProcessor(); - ssap.SharedStateFactories = new ISharedStateFactory[] { ssf1 }; - of.RegisterSingleton( "ssap", ssap ); + ssap.SharedStateFactories = new ISharedStateFactory[] {ssf1}; + of.RegisterSingleton("ssap", ssap); - using (Record( mocks )) - { - // preset SharedState - ssap must ignore it - Expect.Call( ssa.SharedState ).Return( new Hashtable() ); - // expect nothing else! - } + // preset SharedState - ssap must ignore it + A.CallTo(() => ssa.SharedState).Returns(new Hashtable()); - using (Playback( mocks )) - { - ssap.PostProcessBeforeInitialization( ssa, "myPage" ); - } + ssap.PostProcessBeforeInitialization(ssa, "myPage"); + + A.CallTo(ssa).Where(x => x.Method.Name == "set_SharedState").MustNotHaveHappened(); } [Test] @@ -139,53 +135,33 @@ public void ProbesSharedStateFactories() { DefaultListableObjectFactory of = new DefaultListableObjectFactory(); - MockRepository mocks = new MockRepository(); - ISharedStateFactory ssf1 = mocks.StrictMock(); - ISharedStateFactory ssf2 = mocks.StrictMock(); - ISharedStateFactory ssf3 = mocks.StrictMock(); - ISharedStateFactory ssf4 = mocks.StrictMock(); + ISharedStateFactory ssf1 = A.Fake(); + ISharedStateFactory ssf2 = A.Fake(); + ISharedStateFactory ssf3 = A.Fake(); + ISharedStateFactory ssf4 = A.Fake(); IDictionary ssf3ProvidedState = new Hashtable(); SharedStateAwareProcessor ssap = new SharedStateAwareProcessor(); - ssap.SharedStateFactories = new ISharedStateFactory[] { ssf1, ssf2, ssf3, ssf4 }; - of.RegisterSingleton( "ssap", ssap ); + ssap.SharedStateFactories = new ISharedStateFactory[] {ssf1, ssf2, ssf3, ssf4}; + of.RegisterSingleton("ssap", ssap); - ISharedStateAware ssa = (ISharedStateAware)mocks.DynamicMock( typeof( ISharedStateAware ) ); + ISharedStateAware ssa = A.Fake(); // Ensure we iterate over configured SharedStateFactories until // the first provider is found that // a) true == provider.CanProvideState( instance, name ) // b) null != provider.GetSharedState( instance, name ) - using (Record( mocks )) - { - Expect.Call( ssa.SharedState ).Return( null ); - Expect.Call( ssf1.CanProvideState( ssa, "pageName" ) ).Return( false ); - Expect.Call( ssf2.CanProvideState( ssa, "pageName" ) ).Return( true ); - Expect.Call( ssf2.GetSharedStateFor( ssa, "pageName" ) ).Return( null ); - Expect.Call( ssf3.CanProvideState( ssa, "pageName" ) ).Return( true ); - Expect.Call( ssf3.GetSharedStateFor( ssa, "pageName" ) ).Return( ssf3ProvidedState ); - Expect.Call( ssa.SharedState = ssf3ProvidedState ); - } - - using (Playback( mocks )) - { - ssap.PostProcessBeforeInitialization( ssa, "pageName" ); - } - } + A.CallTo(() => ssa.SharedState).Returns(null).Once(); + A.CallTo(() => ssf1.CanProvideState(ssa, "pageName")).Returns(false).Once(); + A.CallTo(() => ssf2.CanProvideState(ssa, "pageName")).Returns(true).Once(); + A.CallTo(() => ssf2.GetSharedStateFor(ssa, "pageName")).Returns(null); + A.CallTo(() => ssf3.CanProvideState(ssa, "pageName")).Returns(true).Once(); + A.CallTo(() => ssf3.GetSharedStateFor(ssa, "pageName")).Returns(ssf3ProvidedState).Once(); - #region Rhino.Mocks Compatibility Adapter + ssap.PostProcessBeforeInitialization(ssa, "pageName"); - private static IDisposable Record( MockRepository mocks ) - { - return mocks.Record(); + Assert.That(Equals(ssa.SharedState, ssf3ProvidedState)); } - - private static IDisposable Playback( MockRepository mocks ) - { - return mocks.Playback(); - } - - #endregion Rhino.Mocks Compatibility Adapter } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/TypeAliasConfigurerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/TypeAliasConfigurerTests.cs index f1f71e943..fd827aa0f 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/TypeAliasConfigurerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/TypeAliasConfigurerTests.cs @@ -20,8 +20,10 @@ using System; using System.Collections; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Collections; using Spring.Context.Support; using Spring.Core.TypeResolution; @@ -37,14 +39,12 @@ namespace Spring.Objects.Factory.Config [TestFixture] public class TypeAliasConfigurerTests { - private MockRepository mocks; private IConfigurableListableObjectFactory factory; [SetUp] public void SetUp() { - mocks = new MockRepository(); - factory = mocks.StrictMock(); + factory = A.Fake(); } [Test] diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/VariablePlaceholderConfigurerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/VariablePlaceholderConfigurerTests.cs index 825f49ee2..7db159398 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Config/VariablePlaceholderConfigurerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Config/VariablePlaceholderConfigurerTests.cs @@ -21,9 +21,9 @@ using System; using System.Collections; -using NUnit.Framework; +using FakeItEasy; -using Rhino.Mocks; +using NUnit.Framework; using Spring.Context.Support; using Spring.Objects.Factory.Support; @@ -31,18 +31,15 @@ namespace Spring.Objects.Factory.Config { /// - /// This class contains tests for + /// This class contains tests for /// /// Mark Pollack [TestFixture] public class VariablePlaceholderConfigurerTests { - private MockRepository mocks; - [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] @@ -68,7 +65,7 @@ public void ThrowsOnInvalidVariableSourcesElement() StaticApplicationContext ac = new StaticApplicationContext(); VariablePlaceholderConfigurer vphc = new VariablePlaceholderConfigurer(); vphc.VariableSources = new ArrayList(new object[] { new object() }); - + try { vphc.PostProcessObjectFactory(ac.ObjectFactory); @@ -300,10 +297,9 @@ public void InlcludeAncestors() pvs.Add(theProperty, placeholder); RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs); - IConfigurableListableObjectFactory mock = mocks.StrictMock(); - Expect.Call(mock.GetObjectDefinitionNames(true)).Return(new string[] { defName }); - Expect.Call(mock.GetObjectDefinition(defName, true)).Return(def); - mocks.ReplayAll(); + IConfigurableListableObjectFactory mock = A.Fake(); + A.CallTo(() => mock.GetObjectDefinitionNames(true)).Returns(new string[] { defName }); + A.CallTo(() => mock.GetObjectDefinition(defName, true)).Returns(def); VariablePlaceholderConfigurer vpc = new VariablePlaceholderConfigurer(); vpc.IgnoreUnresolvablePlaceholders = true; @@ -311,8 +307,6 @@ public void InlcludeAncestors() vpc.IncludeAncestors = true; vpc.PostProcessObjectFactory(mock); - - mocks.VerifyAll(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/DefaultListableObjectFactoryTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/DefaultListableObjectFactoryTests.cs index 8a0829bc6..e87214b5d 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/DefaultListableObjectFactoryTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/DefaultListableObjectFactoryTests.cs @@ -18,8 +18,6 @@ #endregion -#region Imports - using System; using System.Collections; using System.Collections.Generic; @@ -27,15 +25,12 @@ using System.Reflection; using System.Runtime.Serialization; using NUnit.Framework; -using Rhino.Mocks; using Spring.Core.TypeConversion; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Xml; using Spring.Objects.Support; -#endregion - namespace Spring.Objects.Factory { /// @@ -46,13 +41,11 @@ namespace Spring.Objects.Factory [TestFixture] public sealed class DefaultListableObjectFactoryTests { - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } + /// /// The setup logic executed before the execution of this test fixture. /// @@ -79,7 +72,7 @@ public Class1( ICollaborator collaborator, IStrategy strategy) TheStrategy = strategy; } } - + class Class2 { private IStrategy _strategy; @@ -293,8 +286,8 @@ public void Dispose() [Test] public void GetObjectPostProcessorCount() { - IObjectPostProcessor proc1 = mocks.StrictMock(); - IObjectPostProcessor proc2 = mocks.StrictMock(); + IObjectPostProcessor proc1 = FakeItEasy.A.Fake(); + IObjectPostProcessor proc2 = FakeItEasy.A.Fake(); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); @@ -315,9 +308,8 @@ public void GetObjectPostProcessorCount() [Test] public void GetObjectPostProcessorCountDoesntRespectHierarchy() { - - IObjectPostProcessor proc1 = mocks.StrictMock(); - IObjectPostProcessor proc2 = mocks.StrictMock(); + IObjectPostProcessor proc1 = FakeItEasy.A.Fake(); + IObjectPostProcessor proc2 = FakeItEasy.A.Fake(); DefaultListableObjectFactory child = new DefaultListableObjectFactory(); DefaultListableObjectFactory parent = new DefaultListableObjectFactory(child); @@ -1535,7 +1527,7 @@ public void DoubleBooleanAutowire() DefaultListableObjectFactory fac = new DefaultListableObjectFactory(); fac.RegisterObjectDefinition("foo", def); - Assert.Throws(() => fac.GetObject("foo"), + Assert.Throws(() => fac.GetObject("foo"), "Error creating object with name 'foo' : Unsatisfied dependency " + "expressed through constructor argument with index 1 of type [System.Boolean] : " + "No unique object of type [System.Boolean] is defined : Unsatisfied dependency of type [System.Boolean]: expected at least 1 matching object to wire the [b2] parameter on the constructor of object [foo]"); @@ -1650,7 +1642,7 @@ public void GetObjectDefinitionResolvesAliases() [Test] public void IgnoreObjectPostProcessorDuplicates() { - IObjectPostProcessor proc1 = mocks.StrictMock(); + IObjectPostProcessor proc1 = FakeItEasy.A.Fake(); DefaultListableObjectFactory lof = new DefaultListableObjectFactory(); @@ -1706,7 +1698,7 @@ public void ConfigureObjectAppliesObjectPostProcessorsUsingDefinition() object testObject = "TestObject"; object resultObject = of.ConfigureObject(testObject, "myObjectDefinition"); - Assert.AreSame(wrapperObject, resultObject); + Assert.AreSame(wrapperObject, resultObject); } [Test] @@ -1715,10 +1707,10 @@ public void ConfigureObjectDoesNotApplyObjectPostProcessorsIfNoDefinition() DefaultListableObjectFactory of = new DefaultListableObjectFactory(); object wrapperObject = "WrapperObject"; of.AddObjectPostProcessor( new TestObjectPostProcessor(wrapperObject)); - + object testObject = "TestObject"; object resultObject = of.ConfigureObject(testObject, "non-existant definition"); - Assert.AreSame(testObject, resultObject); + Assert.AreSame(testObject, resultObject); } [Test] diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/ObjectDefinitionStoreExceptionTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/ObjectDefinitionStoreExceptionTests.cs index ad06f0cad..d03931d50 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/ObjectDefinitionStoreExceptionTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/ObjectDefinitionStoreExceptionTests.cs @@ -18,15 +18,12 @@ #endregion -#region Imports +using FakeItEasy; using NUnit.Framework; -using Rhino.Mocks; using Spring.Core.IO; using Spring.Util; -#endregion - namespace Spring.Objects.Factory { /// @@ -36,24 +33,20 @@ namespace Spring.Objects.Factory [TestFixture] public sealed class ObjectDefinitionStoreExceptionTests { - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } - [Test] + + [Test] public void FromResource() { string expectedName = "bing"; - string expectedResourceDescription = "mock.resource"; - IResource resource = mocks.StrictMock(); - Expect.Call(resource.Description).Return(expectedResourceDescription); - mocks.ReplayAll(); - ObjectDefinitionStoreException inex - = new ObjectDefinitionStoreException(resource, expectedName, "mmm..."); - mocks.VerifyAll(); + string expectedResourceDescription = "mock.resource"; + IResource resource = A.Fake(); + A.CallTo(() => resource.Description).Returns(expectedResourceDescription); + + ObjectDefinitionStoreException inex = new ObjectDefinitionStoreException(resource, expectedName, "mmm..."); CheckSerialization(inex, expectedName, expectedResourceDescription); } diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/DelegatingMethodReplacerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/DelegatingMethodReplacerTests.cs index 32d346675..cb1501c0c 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/DelegatingMethodReplacerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/DelegatingMethodReplacerTests.cs @@ -18,14 +18,12 @@ #endregion -#region Imports - using System; using System.Reflection; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Objects.Factory.Support { @@ -36,52 +34,46 @@ namespace Spring.Objects.Factory.Support [TestFixture] public sealed class DelegatingMethodReplacerTests { - private MockRepository mocks; - [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] public void InstantiationWithNullDefinition() { - IObjectFactory factory = mocks.StrictMock(); + IObjectFactory factory = A.Fake(); Assert.Throws(() => new DelegatingMethodReplacer(null, factory)); } [Test] public void InstantiationWithNullFactory() { - IConfigurableObjectDefinition mock = mocks.StrictMock(); + IConfigurableObjectDefinition mock = A.Fake(); Assert.Throws(() => new DelegatingMethodReplacer(mock, null)); } [Test] public void SunnyDayPath() { - IObjectFactory mockFactory = mocks.StrictMock(); - IConfigurableObjectDefinition mockDefinition = mocks.StrictMock(); - IMethodReplacer mockReplacer = mocks.StrictMock(); + IObjectFactory mockFactory = A.Fake(); + IConfigurableObjectDefinition mockDefinition = A.Fake(); + IMethodReplacer mockReplacer = A.Fake(); + - const string ReplacerObjectName = "replacer"; - Expect.Call(mockFactory.GetObject(ReplacerObjectName)).Return(mockReplacer); + A.CallTo(() => mockFactory.GetObject(ReplacerObjectName)).Returns(mockReplacer); ReplacedMethodOverride ovr = new ReplacedMethodOverride("SunnyDayPath", ReplacerObjectName); MethodOverrides overrides = new MethodOverrides(); overrides.Add(ovr); - Expect.Call(mockDefinition.MethodOverrides).Return(overrides); + A.CallTo(() => mockDefinition.MethodOverrides).Returns(overrides); + + A.CallTo(() => mockReplacer.Implement(null, null, null)).WithAnyArguments().Returns(null); - Expect.Call(mockReplacer.Implement(null, null, null)).IgnoreArguments().Return(null); - mocks.ReplayAll(); - DelegatingMethodReplacer replacer = new DelegatingMethodReplacer(mockDefinition, mockFactory); MethodInfo method = (MethodInfo) MethodBase.GetCurrentMethod(); replacer.Implement(this, method, new object[] {}); - - mocks.VerifyAll(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/LookupMethodReplacerTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/LookupMethodReplacerTests.cs index d569e093d..080fb867b 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/LookupMethodReplacerTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/LookupMethodReplacerTests.cs @@ -18,14 +18,12 @@ #endregion -#region Imports - using System; using System.Reflection; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Objects.Factory.Support { @@ -36,52 +34,46 @@ namespace Spring.Objects.Factory.Support [TestFixture] public sealed class LookupMethodReplacerTests { - private MockRepository mocks; - [SetUp] public void Setup() { - mocks = new MockRepository(); } [Test] public void InstantiationWithNullDefinition() { - IObjectFactory objectFactory = mocks.StrictMock(); + IObjectFactory objectFactory = A.Fake(); Assert.Throws(() => new LookupMethodReplacer(null, objectFactory)); } [Test] public void InstantiationWithNullFactory() { - var configurableObjectDefinition = mocks.StrictMock(); + var configurableObjectDefinition = A.Fake(); Assert.Throws(() => new LookupMethodReplacer(configurableObjectDefinition, null)); } [Test] public void SunnyDayPath() { - var objectFactory = mocks.StrictMock(); - var configurableObjectDefinition = mocks.StrictMock(); - + var objectFactory = A.Fake(); + var configurableObjectDefinition = A.Fake(); + object expectedLookup = new object(); const string LookupObjectName = "foo"; - - Expect.Call(objectFactory.GetObject(LookupObjectName)).Return(expectedLookup); + + A.CallTo(() => objectFactory.GetObject(LookupObjectName)).Returns(expectedLookup); LookupMethodOverride ovr = new LookupMethodOverride("SunnyDayPath", LookupObjectName); MethodOverrides overrides = new MethodOverrides(); overrides.Add(ovr); - Expect.Call(configurableObjectDefinition.MethodOverrides).Return(overrides); + A.CallTo(() => configurableObjectDefinition.MethodOverrides).Returns(overrides); LookupMethodReplacer replacer = new LookupMethodReplacer(configurableObjectDefinition, objectFactory); - mocks.ReplayAll(); MethodInfo method = (MethodInfo) MethodBase.GetCurrentMethod(); object lookup = replacer.Implement(this, method, new object[] {}); Assert.AreSame(expectedLookup, lookup); - - mocks.VerifyAll(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/ObjectDefinitionReaderUtilsTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/ObjectDefinitionReaderUtilsTests.cs index 661ee74ef..39629e721 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Support/ObjectDefinitionReaderUtilsTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Support/ObjectDefinitionReaderUtilsTests.cs @@ -18,15 +18,13 @@ #endregion -#region Imports - using System; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Objects.Factory.Config; -#endregion - namespace Spring.Objects.Factory.Support { /// @@ -36,44 +34,36 @@ namespace Spring.Objects.Factory.Support [TestFixture] public sealed class ObjectDefinitionReaderUtilsTests { - private MockRepository mocks; private IObjectDefinitionRegistry registry; private IObjectDefinition definition; [SetUp] public void SetUp() { - mocks = new MockRepository(); - registry = mocks.StrictMock(); - definition = mocks.StrictMock(); + registry = A.Fake(); + definition = A.Fake(); } [Test] public void RegisterObjectDefinitionSunnyDay() { - registry.RegisterObjectDefinition(null, null); - LastCall.IgnoreArguments(); - mocks.ReplayAll(); - ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo"); ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry); - mocks.VerifyAll(); + + A.CallTo(() => registry.RegisterObjectDefinition(null, null)).WithAnyArguments().MustHaveHappened(); } [Test] public void RegisterObjectDefinitionSunnyDayWithAliases() { - registry.RegisterObjectDefinition("foo", definition); - registry.RegisterAlias("foo", "bar"); - registry.RegisterAlias("foo", "baz"); - mocks.ReplayAll(); - ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo", new string[] {"bar", "baz"}); ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry); - - mocks.VerifyAll(); + + A.CallTo(() => registry.RegisterObjectDefinition("foo", definition)).MustHaveHappened(); + A.CallTo(() => registry.RegisterAlias("foo", "bar")).MustHaveHappened(); + A.CallTo(() => registry.RegisterAlias("foo", "baz")).MustHaveHappened(); } [Test] @@ -101,24 +91,12 @@ public void RegisterObjectDefinitionWithDuplicateAlias() registry.RegisterObjectDefinition("foo", definition); // we assume that some other object defition has already been associated with this alias... - registry.RegisterAlias(null, null); - LastCall.IgnoreArguments().Throw(new ObjectDefinitionStoreException()); - mocks.ReplayAll(); + A.CallTo(() => registry.RegisterAlias(null, null)).WithAnyArguments().Throws(); ObjectDefinitionHolder holder - = new ObjectDefinitionHolder(definition, "foo", new string[] { "bing" }); - - try - { - ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry); - Assert.Fail("Must have thrown an ObjectDefinitionStoreException store by this point."); - } - catch (ObjectDefinitionStoreException) - { - // expected... - } - - mocks.VerifyAll(); + = new ObjectDefinitionHolder(definition, "foo", new string[] {"bing"}); + + Assert.Throws(() => ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry)); } [Test] @@ -130,7 +108,7 @@ public void GenerateObjectNameWithNullDefinition() [Test] public void GenerateObjectNameWithNullRegistry() { - Assert.Throws(() => ObjectDefinitionReaderUtils.GenerateObjectName(mocks.StrictMock(), null)); + Assert.Throws(() => ObjectDefinitionReaderUtils.GenerateObjectName(A.Fake(), null)); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs index 93099970c..e4ffd8b8d 100644 --- a/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs +++ b/test/Spring/Spring.Core.Tests/Objects/Factory/Xml/XmlObjectFactoryTests.cs @@ -18,8 +18,6 @@ #endregion -#region Imports - using System; using System.Collections; using System.Collections.Generic; @@ -31,9 +29,10 @@ using System.Web.Services; using Common.Logging; using Common.Logging.Simple; -using NUnit.Framework; -using Rhino.Mocks; +using FakeItEasy; + +using NUnit.Framework; using Spring.Core.IO; using Spring.Core.TypeResolution; @@ -42,10 +41,8 @@ using Spring.Objects.Factory.Support; using Spring.Util; -#endregion - namespace Spring.Objects.Factory.Xml -{ +{ /// /// Unit tests for the XmlObjectFactory class. /// @@ -59,8 +56,6 @@ namespace Spring.Objects.Factory.Xml [TestFixture] public sealed class XmlObjectFactoryTests { - private MockRepository mocks; - /// /// The setup logic executed before the execution of this test fixture. /// @@ -75,7 +70,6 @@ public void FixtureSetUp() [SetUp] public void SetUp() { - mocks = new MockRepository(); } [Test] @@ -573,25 +567,25 @@ public void InnerObjects() xof.GetObject("innerObject"); TestObject hasInnerObjects = (TestObject) xof.GetObject("hasInnerObjects"); - Assert.AreEqual(5, hasInnerObjects.Age); + Assert.AreEqual(5, hasInnerObjects.Age); TestObject inner1 = (TestObject) hasInnerObjects.Spouse; - Assert.IsNotNull(inner1); - Assert.AreEqual("Spring.Objects.TestObject#", inner1.ObjectName.Substring(0, inner1.ObjectName.IndexOf("#")+1)); + Assert.IsNotNull(inner1); + Assert.AreEqual("Spring.Objects.TestObject#", inner1.ObjectName.Substring(0, inner1.ObjectName.IndexOf("#")+1)); Assert.AreEqual("inner1", inner1.Name); Assert.AreEqual(6, inner1.Age); - - + + Assert.IsNotNull(hasInnerObjects.Friends); IList friends = (IList) hasInnerObjects.Friends; Assert.AreEqual(2, friends.Count); DerivedTestObject inner2 = (DerivedTestObject) friends[0]; Assert.AreEqual("inner2", inner2.Name); Assert.AreEqual(7, inner2.Age); - Assert.AreEqual("Spring.Objects.DerivedTestObject#", inner2.ObjectName.Substring(0, inner2.ObjectName.IndexOf("#") + 1)); + Assert.AreEqual("Spring.Objects.DerivedTestObject#", inner2.ObjectName.Substring(0, inner2.ObjectName.IndexOf("#") + 1)); TestObject innerFactory = (TestObject) friends[1]; Assert.AreEqual(DummyFactory.SINGLETON_NAME, innerFactory.Name); - + Assert.IsNotNull(hasInnerObjects.SomeMap); Assert.IsFalse((hasInnerObjects.SomeMap.Count == 0)); TestObject inner3 = (TestObject) hasInnerObjects.SomeMap["someKey"]; @@ -636,11 +630,11 @@ public void InnerObjectsInPrototype() Assert.AreEqual("inner3", inner3.Name); Assert.AreEqual(8, inner3.Age); xof.Dispose(); - + Assert.IsFalse(inner2.WasDestroyed()); Assert.IsFalse(innerFactory.Name == null); Assert.IsFalse(innerFriendOfAFriend.WasDestroyed()); - + } [Test] @@ -661,7 +655,7 @@ public void SingletonInheritanceFromParentFactorySingleton() public void SingletonInheritanceFromParentFactorySingletonUsingCtor() { XmlObjectFactory parent = new XmlObjectFactory(new ReadOnlyXmlTestResource("parent.xml", GetType())); - XmlObjectFactory child = new XmlObjectFactory(new ReadOnlyXmlTestResource("child.xml", GetType()), parent); + XmlObjectFactory child = new XmlObjectFactory(new ReadOnlyXmlTestResource("child.xml", GetType()), parent); TestObject inherits = (TestObject)child.GetObject("inheritsFromParentFactoryUsingCtor"); // Name property value is overriden Assert.IsTrue(inherits.Name.Equals("child-name")); @@ -967,17 +961,17 @@ public void MultiThreadedLazyInit() { IResource resource = new ReadOnlyXmlTestResource("lazy-init-multithreaded.xml", GetType()); XmlObjectFactory xof = new XmlObjectFactory(resource); - + LazyWorker lw1 = new LazyWorker(xof); LazyWorker lw2 = new LazyWorker(xof); Thread thread1 = new Thread(new ThreadStart(lw1.DoWork)); Thread thread2 = new Thread(new ThreadStart(lw2.DoWork)); - + thread1.Start(); Thread.Sleep(1000); thread2.Start(); thread1.Join(); - thread2.Join(); + thread2.Join(); Assert.AreEqual(typeof(LazyTestObject), lw1.ObjectFromContext.GetType()); Assert.AreEqual(typeof(LazyTestObject), lw2.ObjectFromContext.GetType()); Assert.AreEqual(1, LazyTestObject.Count); @@ -1027,7 +1021,7 @@ public void DefaultLazyInitNoInObjectDef() Assert.IsTrue(ex.InnerException is FormatException); } } - + [Test] public void NoSuchXmlFile() { @@ -1057,7 +1051,7 @@ public void DefaultXmlResolverIsUsedIfNullSuppliedOrSet() XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(xof, null); try { - reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("invalid.xml", GetType())); + reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("invalid.xml", GetType())); Assert.Fail("Should have thrown XmlObjectDefinitionStoreException"); } catch (ObjectDefinitionStoreException e) @@ -1528,15 +1522,11 @@ public void InstanceFactoryMethodWithOverloadedArgs() //FactoryMethods fm = (FactoryMethods) factory.GetObject("instanceFactoryMethodOverloads", new object[] {row}); // Assert.AreEqual("DataRowCtor", fm.Name); - IDataRecord dataRecord = (IDataRecord) mocks.DynamicMock(typeof(IDataRecord)); + IDataRecord dataRecord = A.Fake(); FactoryMethods fm = (FactoryMethods)factory.GetObject("instanceFactoryMethodOverloads", new object[] { dataRecord }); Assert.AreEqual("DataRecordCtor", fm.Name); - - } - - #region Private Helper Methods for InstanceFactoryMethodWithOverloadedargs private DataTable MakeNamesTable() { // Create a new DataTable titled 'Names.' @@ -1569,7 +1559,6 @@ private DataTable MakeNamesTable() return namesTable; } - #endregion [Test] public void FactoryMethodNoMatchingStaticMethod() { @@ -1689,7 +1678,7 @@ public void BailsOnRubbishPropertyRetrievingFactoryMethod() /// /// Test creating an object using its 1 arg boolean constructor (amongst - /// others) by specifying the constructor arguments type and + /// others) by specifying the constructor arguments type and /// not its index number. /// [Test] @@ -1840,7 +1829,7 @@ private void _UseInstanceFactoryMethodInnerObjectDefinition(out Stream stream) public void TestExpressionAttribute() { TypeRegistry.RegisterType("WebMethod", typeof(WebMethodAttribute)); - + IResource resource = new ReadOnlyXmlTestResource("expressions.xml", GetType()); XmlObjectFactory xof = new XmlObjectFactory(resource); @@ -1886,7 +1875,7 @@ public class LazyWorker private Object objectFromContext; public LazyWorker(XmlObjectFactory xof) { - this.xof = xof; + this.xof = xof; } public void DoWork() { @@ -2069,5 +2058,5 @@ public void Dispose() #endregion } - + } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Pool/Support/SimplePoolTest.cs b/test/Spring/Spring.Core.Tests/Pool/Support/SimplePoolTest.cs index d2ac76bca..0c360abfa 100644 --- a/test/Spring/Spring.Core.Tests/Pool/Support/SimplePoolTest.cs +++ b/test/Spring/Spring.Core.Tests/Pool/Support/SimplePoolTest.cs @@ -2,13 +2,13 @@ /* * Copyright � 2002-2011 the original author or authors. -* +* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -* +* * http://www.apache.org/licenses/LICENSE-2.0 -* +* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,19 +18,17 @@ #endregion -#region Imports - using System; using System.Collections; using System.Runtime.InteropServices; using System.Threading; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Pool.Support; using Spring.Threading; -#endregion - namespace Spring.Pool { #region Inner Class : Helper @@ -111,23 +109,18 @@ public void PassivateObject(object o) } } - #endregion + #endregion - private MockRepository mocks; - private IPoolableObjectFactory factory; + private IPoolableObjectFactory factory; private SimplePool pool; [SetUp] public void SetUp() { - mocks = new MockRepository(); - factory = (IPoolableObjectFactory) mocks.DynamicMock(typeof(IPoolableObjectFactory)); - Expect.Call(factory.MakeObject()).Return(new object()).Repeat.Any(); + factory = A.Fake(); + A.CallTo(() => factory.MakeObject()).Returns(new object()); - mocks.ReplayAll(); pool = new SimplePool(factory, 1); - - mocks.BackToRecordAll(); } @@ -152,85 +145,70 @@ public void InstantiateSpecifyingNegativePooledItems() [Test] public void ActivateOnObjectOnBorrow() { - Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); - factory.ActivateObject(null); - LastCall.IgnoreArguments(); - mocks.ReplayAll(); + A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true); Assert.AreEqual(0, pool.NumActive, "active wrong"); Assert.AreEqual(1, pool.NumIdle, "idle wrong"); pool.BorrowObject(); Assert.AreEqual(1, pool.NumActive, "active wrong"); Assert.AreEqual(0, pool.NumIdle, "idle wrong"); - mocks.VerifyAll(); - } - // TODO fix test!!! - [Test] - [Ignore("Cannot figure out why this is failing?")] + A.CallTo(() => factory.ActivateObject(null)).WithAnyArguments().MustHaveHappened(); + } + + [Test] public void PassivateBusyObjectsBeforeClose() { - Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); - object o = pool.BorrowObject(); - factory.PassivateObject(o); - mocks.ReplayAll(); + A.CallTo(() => factory.ValidateObject(A._)).WithAnyArguments().Returns(true); + object o = pool.BorrowObject(); pool.Close(); - mocks.VerifyAll(); + A.CallTo(() => factory.PassivateObject(o)).MustHaveHappened(); } - [Test] + [Test] [Ignore("No longer expected behavior per SPRNET-1582 being resolved.")] public void NoMoreUsableAfterClose() { - object o = pool.BorrowObject(); - factory.PassivateObject(o); - mocks.ReplayAll(); - pool.Close(); Assert.Throws(() => pool.BorrowObject()); - mocks.VerifyAll(); + + A.CallTo(() => factory.PassivateObject(null)).WithAnyArguments().MustHaveHappened(); } - [Test] + [Test] [Ignore("No longer expected behavior per SPRNET-1582 being resolved.")] public void ThrowsExceptionWhenOutOfItemsBecauseFailedValidation() { object o = new object(); - Expect.Call(factory.MakeObject()).Return(o); - Expect.Call(factory.ValidateObject(o)).Return(false); - mocks.ReplayAll(); + A.CallTo(() => factory.MakeObject()).Returns(o); + A.CallTo(() => factory.ValidateObject(o)).Returns(false); pool = new SimplePool(factory, 1); Assert.Throws(() => pool.BorrowObject()); - mocks.VerifyAll(); } [Test] public void PassivateObjectOnReturn() { - Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); - factory.PassivateObject(null); - LastCall.IgnoreArguments(); - mocks.ReplayAll(); + A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true); pool.ReturnObject(pool.BorrowObject()); - mocks.VerifyAll(); + A.CallTo(() => factory.PassivateObject(null)).WithAnyArguments().MustHaveHappened(); } - [Test] + [Test] public void DestroyObjectOnClose() { - Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); - factory.DestroyObject(null); - LastCall.IgnoreArguments(); - mocks.ReplayAll(); + A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true); pool.BorrowObject(); pool.Close(); - } - [Test] + A.CallTo(() => factory.DestroyObject(null)).WithAnyArguments().MustHaveHappened(); + } + + [Test] public void WaitOnBorrowWhenExausted() { int n = 100; diff --git a/test/Spring/Spring.Core.Tests/Spring.Core.Tests.2010.csproj b/test/Spring/Spring.Core.Tests/Spring.Core.Tests.2010.csproj index 1d5bea44b..ef972f21a 100644 --- a/test/Spring/Spring.Core.Tests/Spring.Core.Tests.2010.csproj +++ b/test/Spring/Spring.Core.Tests/Spring.Core.Tests.2010.csproj @@ -11,10 +11,11 @@ + + - diff --git a/test/Spring/Spring.Core.Tests/Threading/SyncHolderTest.cs b/test/Spring/Spring.Core.Tests/Threading/SyncHolderTest.cs index d9026f8d1..1a8a17596 100644 --- a/test/Spring/Spring.Core.Tests/Threading/SyncHolderTest.cs +++ b/test/Spring/Spring.Core.Tests/Threading/SyncHolderTest.cs @@ -1,40 +1,37 @@ using System.Threading; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; namespace Spring.Threading { [TestFixture] - public class SyncHolderTest - { - private MockRepository mocks; + public class SyncHolderTest + { ISync sync; [SetUp] - public void SetUp () + public void SetUp() { - mocks = new MockRepository(); - sync = mocks.StrictMock(); + sync = A.Fake(); } [TearDown] - public void TearDown () + public void TearDown() { - mocks.VerifyAll(); } class MySemaphore : Semaphore { - public MySemaphore (long initialPermits) : base (initialPermits) - {} + public MySemaphore(long initialPermits) : base(initialPermits) + { + } } [Test] - public void CanBeUsedWithTheUsingCSharpIdiomToAttemptOnAnISync () + public void CanBeUsedWithTheUsingCSharpIdiomToAttemptOnAnISync() { - // no expectations - mocks.ReplayAll(); - MySemaphore sync = new MySemaphore(1); using (new SyncHolder(sync, 100)) { @@ -57,20 +54,18 @@ public void CanBeUsedWithTheUsingCSharpIdiomToAttemptOnAnISync () } [Test] - public void CanBeUsedWithTheUsingCSharpIdiomToAcquireAnIsync() - { + public void CanBeUsedWithTheUsingCSharpIdiomToAcquireAnIsync() + { sync.Acquire(); sync.Release(); - mocks.ReplayAll(); - Assert.Throws(() => - { - using (new SyncHolder(sync)) - { - throw new ThreadStateException(); - } - - }); - } - } -} + Assert.Throws(() => + { + using (new SyncHolder(sync)) + { + throw new ThreadStateException(); + } + }); + } + } +} \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Util/NumberUtilsTests.cs b/test/Spring/Spring.Core.Tests/Util/NumberUtilsTests.cs index 056f9d68c..f8200381e 100644 --- a/test/Spring/Spring.Core.Tests/Util/NumberUtilsTests.cs +++ b/test/Spring/Spring.Core.Tests/Util/NumberUtilsTests.cs @@ -21,55 +21,56 @@ #region Imports using System; + using NUnit.Framework; #endregion namespace Spring.Util { - /// - /// Unit tests for the NumberUtils class. - /// - /// Rick Evans - [TestFixture] - public sealed class NumberUtilsTests - { - [Test] - public void IsInteger() - { - Assert.IsTrue(NumberUtils.IsInteger(10)); - Assert.IsTrue(NumberUtils.IsInteger(10L)); - Assert.IsTrue(NumberUtils.IsInteger((short) 10)); - Assert.IsFalse(NumberUtils.IsInteger('e')); - Assert.IsFalse(NumberUtils.IsInteger(null)); - Assert.IsFalse(NumberUtils.IsInteger(9.5D)); - Assert.IsFalse(NumberUtils.IsInteger(9.5F)); - Assert.IsFalse(NumberUtils.IsInteger(this)); - Assert.IsFalse(NumberUtils.IsInteger(null)); - Assert.IsFalse(NumberUtils.IsInteger(string.Empty)); - } - - [Test] - public void IsDecimal() - { - Assert.IsFalse(NumberUtils.IsDecimal(10)); - Assert.IsFalse(NumberUtils.IsDecimal(10L)); - Assert.IsFalse(NumberUtils.IsDecimal((short) 10)); - Assert.IsFalse(NumberUtils.IsDecimal('e')); - Assert.IsFalse(NumberUtils.IsDecimal(null)); - Assert.IsTrue(NumberUtils.IsDecimal(9.5D)); - Assert.IsTrue(NumberUtils.IsDecimal(9.5F)); - Assert.IsFalse(NumberUtils.IsDecimal(this)); - Assert.IsFalse(NumberUtils.IsDecimal(null)); - Assert.IsFalse(NumberUtils.IsDecimal(string.Empty)); - } - - [Test] - public void IsNumber() - { + /// + /// Unit tests for the NumberUtils class. + /// + /// Rick Evans + [TestFixture] + public sealed class NumberUtilsTests + { + [Test] + public void IsInteger() + { + Assert.IsTrue(NumberUtils.IsInteger(10)); + Assert.IsTrue(NumberUtils.IsInteger(10L)); + Assert.IsTrue(NumberUtils.IsInteger((short) 10)); + Assert.IsFalse(NumberUtils.IsInteger('e')); + Assert.IsFalse(NumberUtils.IsInteger(null)); + Assert.IsFalse(NumberUtils.IsInteger(9.5D)); + Assert.IsFalse(NumberUtils.IsInteger(9.5F)); + Assert.IsFalse(NumberUtils.IsInteger(this)); + Assert.IsFalse(NumberUtils.IsInteger(null)); + Assert.IsFalse(NumberUtils.IsInteger(string.Empty)); + } + + [Test] + public void IsDecimal() + { + Assert.IsFalse(NumberUtils.IsDecimal(10)); + Assert.IsFalse(NumberUtils.IsDecimal(10L)); + Assert.IsFalse(NumberUtils.IsDecimal((short) 10)); + Assert.IsFalse(NumberUtils.IsDecimal('e')); + Assert.IsFalse(NumberUtils.IsDecimal(null)); + Assert.IsTrue(NumberUtils.IsDecimal(9.5D)); + Assert.IsTrue(NumberUtils.IsDecimal(9.5F)); + Assert.IsFalse(NumberUtils.IsDecimal(this)); + Assert.IsFalse(NumberUtils.IsDecimal(null)); + Assert.IsFalse(NumberUtils.IsDecimal(string.Empty)); + } + + [Test] + public void IsNumber() + { Assert.IsTrue(NumberUtils.IsNumber(10)); Assert.IsTrue(NumberUtils.IsNumber(10L)); - Assert.IsTrue(NumberUtils.IsNumber((short)10)); + Assert.IsTrue(NumberUtils.IsNumber((short) 10)); Assert.IsFalse(NumberUtils.IsNumber('e')); Assert.IsFalse(NumberUtils.IsNumber(null)); Assert.IsTrue(NumberUtils.IsNumber(9.5D)); @@ -77,169 +78,174 @@ public void IsNumber() Assert.IsFalse(NumberUtils.IsNumber(this)); Assert.IsFalse(NumberUtils.IsNumber(null)); Assert.IsFalse(NumberUtils.IsNumber(string.Empty)); - } + } [Test] public void IsZero() { - Assert.IsFalse(NumberUtils.IsZero((Int16)2)); - Assert.IsTrue(NumberUtils.IsZero((Int16)0)); + Assert.IsFalse(NumberUtils.IsZero((short) 2)); + Assert.IsTrue(NumberUtils.IsZero((short) 0)); - Assert.IsFalse(NumberUtils.IsZero((Int32)2)); - Assert.IsTrue(NumberUtils.IsZero((Int32)0)); + Assert.IsFalse(NumberUtils.IsZero(2)); + Assert.IsTrue(NumberUtils.IsZero(0)); - Assert.IsFalse(NumberUtils.IsZero((Int64)2)); - Assert.IsTrue(NumberUtils.IsZero((Int64)0)); + Assert.IsFalse(NumberUtils.IsZero((long) 2)); + Assert.IsTrue(NumberUtils.IsZero((long) 0)); - Assert.IsFalse(NumberUtils.IsZero((UInt16)2)); - Assert.IsTrue(NumberUtils.IsZero((UInt16)0)); + Assert.IsFalse(NumberUtils.IsZero((ushort) 2)); + Assert.IsTrue(NumberUtils.IsZero((ushort) 0)); - Assert.IsFalse(NumberUtils.IsZero((UInt32)2)); - Assert.IsTrue(NumberUtils.IsZero((UInt32)0)); + Assert.IsFalse(NumberUtils.IsZero((uint) 2)); + Assert.IsTrue(NumberUtils.IsZero((uint) 0)); - Assert.IsFalse(NumberUtils.IsZero((UInt64)2)); - Assert.IsTrue(NumberUtils.IsZero((UInt64)0)); + Assert.IsFalse(NumberUtils.IsZero((ulong) 2)); + Assert.IsTrue(NumberUtils.IsZero((ulong) 0)); - Assert.IsFalse(NumberUtils.IsZero((decimal)2)); - Assert.IsTrue(NumberUtils.IsZero((decimal)0)); + Assert.IsFalse(NumberUtils.IsZero((decimal) 2)); + Assert.IsTrue(NumberUtils.IsZero((decimal) 0)); - Assert.IsTrue(NumberUtils.IsZero((Byte?)0)); - Assert.IsFalse(NumberUtils.IsZero((Byte)2)); + Assert.IsTrue(NumberUtils.IsZero((byte?) 0)); + Assert.IsFalse(NumberUtils.IsZero((byte) 2)); - Assert.IsTrue(NumberUtils.IsZero((SByte?)0)); - Assert.IsFalse(NumberUtils.IsZero((SByte)2)); + Assert.IsTrue(NumberUtils.IsZero((sbyte?) 0)); + Assert.IsFalse(NumberUtils.IsZero((sbyte) 2)); } - [Test] - public void NegateNull() - { + [Test] + public void NegateNull() + { Assert.Throws(() => NumberUtils.Negate(null)); - } + } - [Test] - public void NegateString() - { + [Test] + public void NegateString() + { Assert.Throws(() => NumberUtils.Negate(string.Empty)); - } + } - [Test] - public void Negate() - { - Assert.AreEqual(-10, NumberUtils.Negate(10)); - } + [Test] + public void Negate() + { + Assert.AreEqual(-10, NumberUtils.Negate(10)); + } [Test] public void CoercesTypes() { - object x = (int)1; - object y = (double)2; + object x = (int) 1; + object y = (double) 2; NumberUtils.CoerceTypes(ref x, ref y); Assert.AreEqual(typeof(double), x.GetType()); } - [Test] - public void Add() - { - Assert.AreEqual(5, NumberUtils.Add(2, 3)); + [Test] + public void Add() + { + Assert.AreEqual(5, NumberUtils.Add(2, 3)); try { NumberUtils.Add(2, "3"); Assert.Fail(); } - catch(ArgumentException) - {} - } + catch (ArgumentException) + { + } + } [Test] public void BitwiseNot() { - Assert.AreEqual( ~((Byte)2), NumberUtils.BitwiseNot((Byte)2) ); - Assert.AreEqual(~((SByte)2), NumberUtils.BitwiseNot((SByte)2)); - Assert.AreEqual(~((Int16)2), NumberUtils.BitwiseNot((Int16)2)); - Assert.AreEqual(~((UInt16)2), NumberUtils.BitwiseNot((UInt16)2)); - Assert.AreEqual(~((Int32)2), NumberUtils.BitwiseNot((Int32)2)); - Assert.AreEqual(~((UInt32)2), NumberUtils.BitwiseNot((UInt32)2)); - Assert.AreEqual(~((Int64)2), NumberUtils.BitwiseNot((Int64)2)); - Assert.AreEqual(~((UInt64)2), NumberUtils.BitwiseNot((UInt64)2)); - Assert.AreEqual( false, NumberUtils.BitwiseNot(true) ); + Assert.AreEqual(~(byte) 2, NumberUtils.BitwiseNot((byte) 2)); + Assert.AreEqual(~(sbyte) 2, NumberUtils.BitwiseNot((sbyte) 2)); + Assert.AreEqual(~(short) 2, NumberUtils.BitwiseNot((short) 2)); + Assert.AreEqual(~(ushort) 2, NumberUtils.BitwiseNot((ushort) 2)); + Assert.AreEqual(~(int) 2, NumberUtils.BitwiseNot((int) 2)); + Assert.AreEqual(~(uint) 2, NumberUtils.BitwiseNot((uint) 2)); + Assert.AreEqual(~(long) 2, NumberUtils.BitwiseNot((long) 2)); + Assert.AreEqual(~(ulong) 2, NumberUtils.BitwiseNot((ulong) 2)); + Assert.AreEqual(false, NumberUtils.BitwiseNot(true)); try { - NumberUtils.BitwiseNot((double)2.0); + NumberUtils.BitwiseNot((double) 2.0); Assert.Fail(); } - catch(ArgumentException) - {} + catch (ArgumentException) + { + } } [Test] public void BitwiseAnd() { - Assert.AreEqual( ((Byte)2)&((Byte)3), NumberUtils.BitwiseAnd((Byte)2, (Byte)3)); - Assert.AreEqual(((SByte)2) & ((SByte)3), NumberUtils.BitwiseAnd((SByte)2, (SByte)3)); - Assert.AreEqual(((Int16)2) & ((Int16)3), NumberUtils.BitwiseAnd((Int16)2, (Int16)3)); - Assert.AreEqual(((UInt16)2) & ((UInt16)3), NumberUtils.BitwiseAnd((UInt16)2, (UInt16)3)); - Assert.AreEqual(((Int32)2) & ((Int32)3), NumberUtils.BitwiseAnd((Int32)2, (Int32)3)); - Assert.AreEqual(((UInt32)2) & ((UInt32)3), NumberUtils.BitwiseAnd((UInt32)2, (UInt32)3)); - Assert.AreEqual(((Int64)2) & ((Int64)3), NumberUtils.BitwiseAnd((Int64)2, (Int64)3)); - Assert.AreEqual(((UInt64)2) & ((UInt64)3), NumberUtils.BitwiseAnd((UInt64)2, (UInt64)3)); - Assert.AreEqual(((UInt64)2) & ((Byte)3), NumberUtils.BitwiseAnd((UInt64)2, (Byte)3)); + Assert.AreEqual((byte) 2 & (byte) 3, NumberUtils.BitwiseAnd((byte) 2, (byte) 3)); + Assert.AreEqual((sbyte) 2 & (sbyte) 3, NumberUtils.BitwiseAnd((sbyte) 2, (sbyte) 3)); + Assert.AreEqual((short) 2 & (short) 3, NumberUtils.BitwiseAnd((short) 2, (short) 3)); + Assert.AreEqual((ushort) 2 & (ushort) 3, NumberUtils.BitwiseAnd((ushort) 2, (ushort) 3)); + Assert.AreEqual((int) 2 & (int) 3, NumberUtils.BitwiseAnd((int) 2, (int) 3)); + Assert.AreEqual((uint) 2 & (uint) 3, NumberUtils.BitwiseAnd((uint) 2, (uint) 3)); + Assert.AreEqual((long) 2 & (long) 3, NumberUtils.BitwiseAnd((long) 2, (long) 3)); + Assert.AreEqual((ulong) 2 & (ulong) 3, NumberUtils.BitwiseAnd((ulong) 2, (ulong) 3)); + Assert.AreEqual((ulong) 2 & (byte) 3, NumberUtils.BitwiseAnd((ulong) 2, (byte) 3)); Assert.AreEqual(true, NumberUtils.BitwiseAnd(true, true)); - Assert.AreEqual( false, NumberUtils.BitwiseAnd(false, true) ); + Assert.AreEqual(false, NumberUtils.BitwiseAnd(false, true)); try { - NumberUtils.BitwiseAnd((double)2.0, 3); + NumberUtils.BitwiseAnd((double) 2.0, 3); Assert.Fail(); } - catch(ArgumentException) - {} + catch (ArgumentException) + { + } } [Test] public void BitwiseOr() { - Assert.AreEqual( ((Byte)2) | ((Byte)3), NumberUtils.BitwiseOr((Byte)2, (Byte)3)); - Assert.AreEqual(((SByte)2) | ((SByte)3), NumberUtils.BitwiseOr((SByte)2, (SByte)3)); - Assert.AreEqual(((Int16)2) | ((Int16)3), NumberUtils.BitwiseOr((Int16)2, (Int16)3)); - Assert.AreEqual(((UInt16)2) | ((UInt16)3), NumberUtils.BitwiseOr((UInt16)2, (UInt16)3)); - Assert.AreEqual(((Int32)2) | ((Int32)3), NumberUtils.BitwiseOr((Int32)2, (Int32)3)); - Assert.AreEqual(((UInt32)2) | ((UInt32)3), NumberUtils.BitwiseOr((UInt32)2, (UInt32)3)); - Assert.AreEqual(((Int64)2) | ((Int64)3), NumberUtils.BitwiseOr((Int64)2, (Int64)3)); - Assert.AreEqual(((UInt64)2) | ((UInt64)3), NumberUtils.BitwiseOr((UInt64)2, (UInt64)3)); - Assert.AreEqual(((UInt64)2) | ((Byte)3), NumberUtils.BitwiseOr((UInt64)2, (Byte)3)); + Assert.AreEqual((byte) 2 | (byte) 3, NumberUtils.BitwiseOr((byte) 2, (byte) 3)); + Assert.AreEqual((sbyte) 2 | (sbyte) 3, NumberUtils.BitwiseOr((sbyte) 2, (sbyte) 3)); + Assert.AreEqual((short) 2 | (short) 3, NumberUtils.BitwiseOr((short) 2, (short) 3)); + Assert.AreEqual((ushort) 2 | (ushort) 3, NumberUtils.BitwiseOr((ushort) 2, (ushort) 3)); + Assert.AreEqual((int) 2 | (int) 3, NumberUtils.BitwiseOr((int) 2, (int) 3)); + Assert.AreEqual((uint) 2 | (uint) 3, NumberUtils.BitwiseOr((uint) 2, (uint) 3)); + Assert.AreEqual((long) 2 | (long) 3, NumberUtils.BitwiseOr((long) 2, (long) 3)); + Assert.AreEqual((ulong) 2 | (ulong) 3, NumberUtils.BitwiseOr((ulong) 2, (ulong) 3)); + Assert.AreEqual((ulong) 2 | (byte) 3, NumberUtils.BitwiseOr((ulong) 2, (byte) 3)); Assert.AreEqual(false, NumberUtils.BitwiseOr(false, false)); Assert.AreEqual(true, NumberUtils.BitwiseOr(false, true)); try { - NumberUtils.BitwiseAnd((double)2.0, 3); + NumberUtils.BitwiseAnd((double) 2.0, 3); Assert.Fail(); } - catch(ArgumentException) - {} + catch (ArgumentException) + { + } } [Test] public void BitwiseXor() { - Assert.AreEqual( ((Byte)2) ^ ((Byte)3), NumberUtils.BitwiseXor((Byte)2, (Byte)3)); - Assert.AreEqual(((SByte)2) ^ ((SByte)3), NumberUtils.BitwiseXor((SByte)2, (SByte)3)); - Assert.AreEqual(((Int16)2) ^ ((Int16)3), NumberUtils.BitwiseXor((Int16)2, (Int16)3)); - Assert.AreEqual(((UInt16)2) ^ ((UInt16)3), NumberUtils.BitwiseXor((UInt16)2, (UInt16)3)); - Assert.AreEqual(((Int32)2) ^ ((Int32)3), NumberUtils.BitwiseXor((Int32)2, (Int32)3)); - Assert.AreEqual(((UInt32)2) ^ ((UInt32)3), NumberUtils.BitwiseXor((UInt32)2, (UInt32)3)); - Assert.AreEqual(((Int64)2) ^ ((Int64)3), NumberUtils.BitwiseXor((Int64)2, (Int64)3)); - Assert.AreEqual(((UInt64)2) ^ ((UInt64)3), NumberUtils.BitwiseXor((UInt64)2, (UInt64)3)); - Assert.AreEqual(((UInt64)2) ^ ((Byte)3), NumberUtils.BitwiseXor((UInt64)2, (Byte)3)); + Assert.AreEqual((byte) 2 ^ (byte) 3, NumberUtils.BitwiseXor((byte) 2, (byte) 3)); + Assert.AreEqual((sbyte) 2 ^ (sbyte) 3, NumberUtils.BitwiseXor((sbyte) 2, (sbyte) 3)); + Assert.AreEqual((short) 2 ^ (short) 3, NumberUtils.BitwiseXor((short) 2, (short) 3)); + Assert.AreEqual((ushort) 2 ^ (ushort) 3, NumberUtils.BitwiseXor((ushort) 2, (ushort) 3)); + Assert.AreEqual((int) 2 ^ (int) 3, NumberUtils.BitwiseXor((int) 2, (int) 3)); + Assert.AreEqual((uint) 2 ^ (uint) 3, NumberUtils.BitwiseXor((uint) 2, (uint) 3)); + Assert.AreEqual((long) 2 ^ (long) 3, NumberUtils.BitwiseXor((long) 2, (long) 3)); + Assert.AreEqual((ulong) 2 ^ (ulong) 3, NumberUtils.BitwiseXor((ulong) 2, (ulong) 3)); + Assert.AreEqual((ulong) 2 ^ (byte) 3, NumberUtils.BitwiseXor((ulong) 2, (byte) 3)); Assert.AreEqual(false, NumberUtils.BitwiseXor(false, false)); Assert.AreEqual(false, NumberUtils.BitwiseXor(true, true)); Assert.AreEqual(true, NumberUtils.BitwiseXor(false, true)); Assert.AreEqual(true, NumberUtils.BitwiseXor(true, false)); try { - NumberUtils.BitwiseAnd((double)2.0, 3); + NumberUtils.BitwiseAnd((double) 2.0, 3); Assert.Fail(); } - catch(ArgumentException) - {} + catch (ArgumentException) + { + } } - } + } } \ No newline at end of file diff --git a/test/Spring/Spring.Core.Tests/Util/ReflectionUtilsTests.cs b/test/Spring/Spring.Core.Tests/Util/ReflectionUtilsTests.cs index b0ee62ced..6d1d911af 100644 --- a/test/Spring/Spring.Core.Tests/Util/ReflectionUtilsTests.cs +++ b/test/Spring/Spring.Core.Tests/Util/ReflectionUtilsTests.cs @@ -922,7 +922,7 @@ public void GetMethodByArgumentValuesResolvesToExactMatchIfAvailable() Assert.IsNotNull(candidateMethods[1]); Assert.IsNotNull(candidateMethods[2]); Assert.AreEqual("ParamArrayMatch", foo.MethodWithSimilarArguments(1, new object())); - Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[])typedArg)); + Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, typedArg)); Assert.AreEqual("AssignableMatch", foo.MethodWithSimilarArguments(1, (ICollection)typedArg)); MethodInfo resolvedMethod = ReflectionUtils.GetMethodByArgumentValues(candidateMethods, new object[] { 1, typedArg }); @@ -950,7 +950,7 @@ public void GetMethodByArgumentValuesMatchesNullableArgs() Assert.IsNotNull(candidateMethods[2]); Assert.IsNotNull(candidateMethods[3]); Assert.AreEqual("ParamArrayMatch", foo.MethodWithSimilarArguments(1, new object())); - Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[])typedArg)); + Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, typedArg)); Assert.AreEqual("AssignableMatch", foo.MethodWithSimilarArguments(1, (ICollection)typedArg)); Assert.AreEqual("NullableArgumentMatch", foo.MethodWithNullableArgument(null)); @@ -975,7 +975,7 @@ public void GetConstructorByArgumentValuesResolvesToExactMatchIfAvailable() Assert.IsNotNull(candidateConstructors[1]); Assert.IsNotNull(candidateConstructors[2]); Assert.AreEqual("ParamArrayMatch", new GetMethodByArgumentValuesTarget(1, new object()).SelectedConstructor); - Assert.AreEqual("ExactMatch", new GetMethodByArgumentValuesTarget(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[])typedArg).SelectedConstructor); + Assert.AreEqual("ExactMatch", new GetMethodByArgumentValuesTarget(1, typedArg).SelectedConstructor); Assert.AreEqual("AssignableMatch", new GetMethodByArgumentValuesTarget(1, (ICollection)typedArg).SelectedConstructor); ConstructorInfo resolvedConstructor = ReflectionUtils.GetConstructorByArgumentValues(candidateConstructors, new object[] { 1, typedArg }); diff --git a/test/Spring/Spring.Core.Tests/Util/UniqueKeyTests.cs b/test/Spring/Spring.Core.Tests/Util/UniqueKeyTests.cs index c992fa687..892a71434 100644 --- a/test/Spring/Spring.Core.Tests/Util/UniqueKeyTests.cs +++ b/test/Spring/Spring.Core.Tests/Util/UniqueKeyTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,7 @@ private class TestObject public void MustNotCallObjectSignatureWithType() { Type myType = typeof(TestObject); - Assert.Throws(() => UniqueKey.GetInstanceScopedString( (object)myType, "PartialKey")); + Assert.Throws(() => UniqueKey.GetInstanceScopedString( myType, "PartialKey")); } [Test] @@ -60,7 +60,7 @@ public void CreateTypeScopedKey() string expectedKeyString = string.Format("{0}.{1}", typeof(TestObject).FullName, "PartialKey"); - // I know testing implementation details is not the best strategy, + // I know testing implementation details is not the best strategy, // but I want to receive an error if this fails (oakinger) Assert.AreEqual(expectedKeyString, expectedKey.ToString()); Assert.AreEqual(expectedKeyString.GetHashCode(), expectedKey.GetHashCode()); @@ -78,7 +78,7 @@ public void CreateInstanceScopedKeyString() TestObject testObject = new TestObject(); string typeScopedKey = UniqueKey.GetInstanceScopedString(testObject, "PartialKey"); string expectedKey = string.Format("{0}[{1}].{2}", typeof(TestObject).FullName, testObject.GetHashCode(), "PartialKey"); - Assert.AreEqual(expectedKey, typeScopedKey); + Assert.AreEqual(expectedKey, typeScopedKey); } [Test] @@ -90,7 +90,7 @@ public void CreateInstanceScopedKey() string expectedKeyString = string.Format("{0}[{1}].{2}", typeof(TestObject).FullName, testObject.GetHashCode(), "PartialKey"); - // I know testing implementation details is not the best strategy, + // I know testing implementation details is not the best strategy, // but I want to receive an error if this fails (oakinger) Assert.AreEqual(expectedKeyString, expectedKey.ToString()); Assert.AreEqual(expectedKeyString.GetHashCode(), expectedKey.GetHashCode()); diff --git a/test/Spring/Spring.Data.Integration.Tests/Spring.Data.Integration.Tests.2010.csproj b/test/Spring/Spring.Data.Integration.Tests/Spring.Data.Integration.Tests.2010.csproj index 74ba4ac45..ab01dee3d 100644 --- a/test/Spring/Spring.Data.Integration.Tests/Spring.Data.Integration.Tests.2010.csproj +++ b/test/Spring/Spring.Data.Integration.Tests/Spring.Data.Integration.Tests.2010.csproj @@ -10,10 +10,11 @@ + + - diff --git a/test/Spring/Spring.Data.NHibernate.Integration.Tests/Data/NHibernate/DbProviderTemplateTests.cs b/test/Spring/Spring.Data.NHibernate.Integration.Tests/Data/NHibernate/DbProviderTemplateTests.cs index 9e5c8fbec..475c481a6 100644 --- a/test/Spring/Spring.Data.NHibernate.Integration.Tests/Data/NHibernate/DbProviderTemplateTests.cs +++ b/test/Spring/Spring.Data.NHibernate.Integration.Tests/Data/NHibernate/DbProviderTemplateTests.cs @@ -72,6 +72,6 @@ public void UserCredentialsDbProvider() - + } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/HibernateTransactionManagerTests.cs b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/HibernateTransactionManagerTests.cs index 9c6d7752a..2a517e9cb 100644 --- a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/HibernateTransactionManagerTests.cs +++ b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/HibernateTransactionManagerTests.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +14,17 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Collections; using System.Data; + +using FakeItEasy; + using NHibernate; using NHibernate.Cfg; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Dao; using Spring.Data.Common; using Spring.Data.Support; @@ -34,8 +32,6 @@ using Spring.Transaction; using Spring.Transaction.Support; -#endregion - namespace Spring.Data.NHibernate { /// @@ -68,41 +64,24 @@ protected override IDbTransaction GetIDbTransaction(ITransaction hibernateTx) } } - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void TransactionCommit() { - IDbProvider provider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - IQuery query = mocks.StrictMock(); + IDbProvider provider = A.Fake(); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + IQuery query = A.Fake(); IList list = new ArrayList(); list.Add("test"); - using (mocks.Ordered()) - { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.Serializable)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - Expect.Call(session.CreateQuery("some query string")).Return(query); - Expect.Call(query.List()).Return(list); - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null); - } - - mocks.ReplayAll(); - + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.Serializable)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + A.CallTo(() => session.CreateQuery("some query string")).Returns(query); + A.CallTo(() => query.List()).Returns(list); LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory); lsfo.AfterPropertiesSet(); @@ -119,7 +98,7 @@ public void TransactionCommit() tt.TransactionIsolationLevel = IsolationLevel.Serializable; - Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy),"Hasn't thread session"); + Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session"); Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider"); Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active"); @@ -133,39 +112,26 @@ public void TransactionCommit() Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active"); - - mocks.VerifyAll(); - + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionRollback() { + IDbProvider provider = A.Fake(); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + IDbTransaction adoTransaction = A.Fake(); - IDbProvider provider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - IDbTransaction adoTransaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - - Expect.Call(adoTransaction.Connection).Return(connection); - LastCall.On(adoTransaction).Repeat.Once(); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - - Expect.Call(session.Close()).Return(null); - } - mocks.ReplayAll(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session).Once(); + A.CallTo(() => session.Connection).Returns(connection).Once(); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction).Once(); + A.CallTo(() => session.IsOpen).Returns(true).Once(); + A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -180,45 +146,32 @@ public void TransactionRollback() { tt.Execute(new TransactionRollbackTxCallback(sessionFactory)); Assert.Fail("Should have thrown exception"); - } catch (ArgumentException) + } + catch (ArgumentException) { - } Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider"); - - mocks.VerifyAll(); + + A.CallTo(() => transaction.Rollback()).MustHaveHappened(); + A.CallTo(() => session.Close()).MustHaveHappened(); } [Test] public void TransactionRollbackOnly() - { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - IDbTransaction adoTransaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - Expect.Call(session.FlushMode).Return(FlushMode.Auto); - session.Flush(); - LastCall.On(session).Repeat.Once(); - - Expect.Call(adoTransaction.Connection).Return(connection); - LastCall.On(adoTransaction).Repeat.Once(); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null); - } - mocks.ReplayAll(); - + { + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + IDbTransaction adoTransaction = A.Fake(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto); + A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -231,34 +184,24 @@ public void TransactionRollbackOnly() tt.Execute(new TransactionRollbackOnlyTxCallback(sessionFactory)); Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Shouldn't have a thread session"); - - mocks.VerifyAll(); - + + A.CallTo(() => session.Flush()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] public void ParticipatingTransactionWithCommit() { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - Expect.Call(session.FlushMode).Return(FlushMode.Auto); - session.Flush(); - LastCall.On(session).Repeat.Once(); - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null); - } - - mocks.ReplayAll(); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto); HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -270,36 +213,25 @@ public void ParticipatingTransactionWithCommit() object result = tt.Execute(new ParticipatingTransactionWithCommitTxCallback(sessionFactory, list)); Assert.IsTrue(result == list); - mocks.VerifyAll(); - + A.CallTo(() => session.Flush()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] public void ParticipatingTransactionWithRollback() { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - IDbTransaction adoTransaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - Expect.Call(session.FlushMode).Return(FlushMode.Auto); - - Expect.Call(adoTransaction.Connection).Return(connection); - LastCall.On(adoTransaction).Repeat.Once(); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null); - } - mocks.ReplayAll(); - + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + IDbTransaction adoTransaction = A.Fake(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto); + A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -313,37 +245,26 @@ public void ParticipatingTransactionWithRollback() } catch (ArgumentException) { - } - mocks.VerifyAll(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] public void ParticipatingTransactionWithRollbackOnly() { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - IDbTransaction adoTransaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - - Expect.Call(adoTransaction.Connection).Return(connection); - LastCall.On(adoTransaction).Repeat.Once(); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null); - } - mocks.ReplayAll(); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + IDbTransaction adoTransaction = A.Fake(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -354,50 +275,38 @@ public void ParticipatingTransactionWithRollbackOnly() list.Add("test"); try { - tt.Execute(new ParticipatingTransactionWithRollbackOnlyTxCallback(tt,sessionFactory,list)); + tt.Execute(new ParticipatingTransactionWithRollbackOnlyTxCallback(tt, sessionFactory, list)); Assert.Fail("Should have thrown UnexpectedRollbackException"); } catch (UnexpectedRollbackException) { - } - mocks.VerifyAll(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] public void ParticipatingTransactionWithWithRequiresNew() { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session1 = mocks.StrictMock(); - ISession session2 = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session1 = A.Fake(); + ISession session2 = A.Fake(); + ITransaction transaction = A.Fake(); - //using (mocks.Ordered()) - //{ - Expect.Call(sessionFactory.OpenSession()).Return(session1); - Expect.Call(session1.Connection).Return(connection); - Expect.Call(session1.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session1.IsOpen).Return(true); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session1).Once() + .Then.Returns(session2).Once(); - Expect.Call(sessionFactory.OpenSession()).Return(session2); - Expect.Call(session2.Connection).Return(connection); - Expect.Call(session2.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session2.IsOpen).Return(true); + A.CallTo(() => session1.Connection).Returns(connection); + A.CallTo(() => session1.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session1.IsOpen).Returns(true); - Expect.Call(session2.FlushMode).Return(FlushMode.Auto); - session2.Flush(); - LastCall.On(session2).Repeat.Once(); + A.CallTo(() => session2.Connection).Returns(connection); + A.CallTo(() => session2.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session2.IsOpen).Returns(true); - transaction.Commit(); - LastCall.On(transaction).Repeat.Twice(); - - Expect.Call(session1.Close()).Return(null); - Expect.Call(session2.Close()).Return(null); - //} - - mocks.ReplayAll(); + A.CallTo(() => session2.FlushMode).Returns(FlushMode.Auto); HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -410,36 +319,26 @@ public void ParticipatingTransactionWithWithRequiresNew() tt.Execute(new ParticipatingTransactionWithWithRequiresNewTxCallback(tt, sessionFactory)); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); - - mocks.VerifyAll(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => session2.Flush()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session1.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly(); } [Test] public void ParticipatingTransactionWithWithNotSupported() { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - - //using (mocks.Ordered()) - //{ - Expect.Call(sessionFactory.OpenSession()).Return(session).Repeat.Twice(); - Expect.Call(session.Connection).Return(connection); - - - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - Expect.Call(session.FlushMode).Return(FlushMode.Auto).Repeat.Twice(); - session.Flush(); - LastCall.On(session).Repeat.Twice(); - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null).Repeat.Once(); - //} - mocks.ReplayAll(); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session).Twice(); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto).Twice(); HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -453,28 +352,19 @@ public void ParticipatingTransactionWithWithNotSupported() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); - mocks.VerifyAll(); - - + A.CallTo(() => session.Flush()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithPropagationSupports() { - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.FlushMode).Return(FlushMode.Never); - session.FlushMode = FlushMode.Auto; - LastCall.IgnoreArguments(); - session.Flush(); - LastCall.IgnoreArguments(); - session.FlushMode = FlushMode.Never; - Expect.Call(session.FlushMode).Return(FlushMode.Never); - - mocks.ReplayAll(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.FlushMode).Returns(FlushMode.Never); LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory); lsfo.AfterPropertiesSet(); @@ -493,53 +383,38 @@ public void TransactionWithPropagationSupports() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); - mocks.VerifyAll(); - + A.CallTo(() => session.Flush()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithPropagationSupportsAndInnerTransaction() { - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session1 = mocks.StrictMock(); - ISession session2 = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - - Expect.Call(sessionFactory.OpenSession()).Return(session1); - Expect.Call(session1.Connection).Return(connection); - Expect.Call(session1.SessionFactory).Return(sessionFactory); - Expect.Call(session1.FlushMode).Return(FlushMode.Auto).Repeat.Twice(); - - session1.Flush(); - LastCall.IgnoreArguments().Repeat.Twice(); - Expect.Call(session1.Close()).Return(null); + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session1 = A.Fake(); + ISession session2 = A.Fake(); + ITransaction transaction = A.Fake(); - Expect.Call(sessionFactory.OpenSession()).Return(session2); - Expect.Call(session2.Connection).Return(connection).Repeat.Twice(); - Expect.Call(session2.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session2.FlushMode).Return(FlushMode.Auto); - session2.Flush(); - LastCall.IgnoreArguments(); - Expect.Call(session2.IsOpen).Return(true); + A.CallTo(() => sessionFactory.OpenSession()).Returns(session1).Once() + .Then.Returns(session2).Once(); + A.CallTo(() => session1.Connection).Returns(connection); + A.CallTo(() => session1.SessionFactory).Returns(sessionFactory); + A.CallTo(() => session1.FlushMode).Returns(FlushMode.Auto); - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - - - Expect.Call(session2.Close()).Return(null); - - mocks.ReplayAll(); + A.CallTo(() => session2.Connection).Returns(connection); + A.CallTo(() => session2.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session2.FlushMode).Returns(FlushMode.Auto); + A.CallTo(() => session2.IsOpen).Returns(true); LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory); lsfo.AfterPropertiesSet(); - ISessionFactory sfProxy = (ISessionFactory)lsfo.GetObject(); + ISessionFactory sfProxy = (ISessionFactory) lsfo.GetObject(); Assert.IsNotNull(sfProxy); HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; - + TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.Supports; TransactionTemplate tt2 = new TransactionTemplate(tm); @@ -554,11 +429,12 @@ public void TransactionWithPropagationSupportsAndInnerTransaction() tt.Execute(new TransactionWithPropagationSupportsAndInnerTransactionTxCallback(tt2, sessionFactory, ht, session1, session2)); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); - - mocks.ReplayAll(); - - } + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session1.Flush()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => session2.Flush()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly(); + } [Test] public void TransactionCommitWithFlushFailure() @@ -578,54 +454,38 @@ public void TransactionCommitWithFlushFailureAndFallbackTranslation() /// if set to true if the exception throw /// is of the type NHibernate.ADOException, in which case HibernateTransactionManager /// will 'fallback' to using the error codes in the underlying exception thrown by - /// the provider, ie. a SqlException, MySqlException. Otherwise, if it is - /// another subclass of HibernateException, then perform a direct maping as + /// the provider, ie. a SqlException, MySqlException. Otherwise, if it is + /// another subclass of HibernateException, then perform a direct maping as /// found in SessionFactoryUtils.ConvertHibernateAccessException. private void DoTransactionCommitWithFlushFailure(bool fallbackTranslation) { - #region Mock Setup - IDbProvider provider = new TestDbProvider(); - IDbConnection connection = mocks.StrictMock(); - ISessionFactory sessionFactory = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ITransaction transaction = mocks.StrictMock(); - IDbTransaction adoTransaction = mocks.StrictMock(); - - Exception rootCause = null; - using (mocks.Ordered()) + IDbConnection connection = A.Fake(); + ISessionFactory sessionFactory = A.Fake(); + ISession session = A.Fake(); + ITransaction transaction = A.Fake(); + IDbTransaction adoTransaction = A.Fake(); + + Exception rootCause; + A.CallTo(() => sessionFactory.OpenSession()).Returns(session); + A.CallTo(() => session.Connection).Returns(connection); + A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction); + A.CallTo(() => session.IsOpen).Returns(true); + Exception sqlException = new TestSqlException("mymsg", "2627"); + if (fallbackTranslation) { - Expect.Call(sessionFactory.OpenSession()).Return(session); - Expect.Call(session.Connection).Return(connection); - Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction); - Expect.Call(session.IsOpen).Return(true); - transaction.Commit(); - Exception sqlException = new TestSqlException("mymsg", "2627"); - if (fallbackTranslation) - { - //error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata - //used by TestDbProvider. - rootCause = sqlException; - LastCall.On(transaction).Throw(new ADOException("mymsg", sqlException)); - } - else - { - rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name"); - LastCall.On(transaction).Throw(rootCause); - } - - Expect.Call(adoTransaction.Connection).Return(connection); - LastCall.On(adoTransaction).Repeat.Once(); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - Expect.Call(session.Close()).Return(null); + //error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata + //used by TestDbProvider. + rootCause = sqlException; + A.CallTo(() => transaction.Commit()).Throws(new ADOException("mymsg", sqlException)); + } + else + { + rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name"); + A.CallTo(() => transaction.Commit()).Throws(rootCause); } - #endregion - - mocks.ReplayAll(); - + A.CallTo(() => adoTransaction.Connection).Returns(connection).Once(); TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -652,31 +512,27 @@ private void DoTransactionCommitWithFlushFailure(bool fallbackTranslation) Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - mocks.VerifyAll(); - - + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } - } - - #region Supporting classes for test TransactionCommit - public class TransactionCommitTxCallback : ITransactionCallback { private ISessionFactory sfProxy; private IDbProvider provider; + public TransactionCommitTxCallback(ISessionFactory sessionFactory, IDbProvider provider) { sfProxy = sessionFactory; this.provider = provider; } - + public object DoInTransaction(ITransactionStatus status) { - Assert.IsTrue(TransactionSynchronizationManager.HasResource(sfProxy),"Has thread session"); + Assert.IsTrue(TransactionSynchronizationManager.HasResource(sfProxy), "Has thread session"); Assert.IsTrue(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); @@ -685,9 +541,10 @@ public object DoInTransaction(ITransactionStatus status) } } - public class LocalSessionFactoryObjectStub : LocalSessionFactoryObject + public class LocalSessionFactoryObjectStub : LocalSessionFactoryObject { private ISessionFactory sf; + public LocalSessionFactoryObjectStub(ISessionFactory sf) { this.sf = sf; @@ -699,13 +556,10 @@ protected override ISessionFactory NewSessionFactory(Configuration config) } } - #endregion - - #region Supporting classes for test TransactionRollback - public class TransactionRollbackTxCallback : ITransactionCallback { private ISessionFactory sf; + public TransactionRollbackTxCallback(ISessionFactory sf) { this.sf = sf; @@ -713,7 +567,7 @@ public TransactionRollbackTxCallback(ISessionFactory sf) public object DoInTransaction(ITransactionStatus status) { - Assert.IsTrue(TransactionSynchronizationManager.HasResource(sf),"Has thread session"); + Assert.IsTrue(TransactionSynchronizationManager.HasResource(sf), "Has thread session"); HibernateTemplate ht = new HibernateTemplate(sf); return ht.ExecuteFind(new ThrowExceptionHibernateCallback()); } @@ -727,13 +581,10 @@ public object DoInHibernate(ISession session) } } - #endregion - - #region Supporting classes for test TransactionRollbackOnly - public class TransactionRollbackOnlyTxCallback : ITransactionCallback { private ISessionFactory sf; + public TransactionRollbackOnlyTxCallback(ISessionFactory sf) { this.sf = sf; @@ -755,14 +606,12 @@ private object Del(ISession session) return null; } } - #endregion - - #region Supporting classes for test ParticipatingTransactionWithCommit public class ParticipatingTransactionWithCommitTxCallback : ITransactionCallback { private ISessionFactory sf; private IList list; + public ParticipatingTransactionWithCommitTxCallback(ISessionFactory sf, IList list) { this.sf = sf; @@ -784,13 +633,10 @@ private object Del(ISession session) } } - - #endregion - - #region Supporting classes for test ParticipatingTransactionWithRollback public class ParticipatingTransactionWithRollbackTxCallback : ITransactionCallback { private ISessionFactory sf; + public ParticipatingTransactionWithRollbackTxCallback(ISessionFactory sf) { this.sf = sf; @@ -803,18 +649,14 @@ public object DoInTransaction(ITransactionStatus status) ht.TemplateFlushMode = TemplateFlushMode.Eager; return ht.ExecuteFind(new ThrowExceptionHibernateCallback()); } - } - #endregion - - #region Supporting classes for test ParticipatingTransactionWithRollbackOnly - public class ParticipatingTransactionWithRollbackOnlyTxCallback : ITransactionCallback { private TransactionTemplate tt; private ISessionFactory sf; private IList list; + public ParticipatingTransactionWithRollbackOnlyTxCallback(TransactionTemplate tt, ISessionFactory sf, IList list) { this.tt = tt; @@ -840,11 +682,7 @@ private object Del(ISession session) { return list; } - } - #endregion - - #region Supporting classes for test ParticipatingTransactionWithWithRequiresNew public class ParticipatingTransactionWithWithRequiresNewTxCallback : ITransactionCallback { @@ -860,19 +698,17 @@ public ParticipatingTransactionWithWithRequiresNewTxCallback(TransactionTemplate public object DoInTransaction(ITransactionStatus status) { SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.GetResource(sf); - Assert.IsNotNull(holder,"Has thread session"); + Assert.IsNotNull(holder, "Has thread session"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); tt.Execute(new RequiresNewTxCallback(sf, holder)); - Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false),"Same thread session as before"); + Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false), "Same thread session as before"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); return null; } - - } public class RequiresNewTxCallback : ITransactionCallback @@ -905,17 +741,13 @@ public RequiresNewTxCallbackInner(SessionHolder holder) public object DoInHibernate(ISession session) { - Assert.IsTrue(session != holder.Session,"Not enclosing session"); + Assert.IsTrue(session != holder.Session, "Not enclosing session"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); return null; } } - #endregion - - - #region Supporting classes for test ParticipatingTransactionWithWithNotSupported public class ParticipatingTransactionWithWithNotSupportedTxCallback : ITransactionCallback { @@ -930,11 +762,11 @@ public ParticipatingTransactionWithWithNotSupportedTxCallback(TransactionTemplat public object DoInTransaction(ITransactionStatus status) { - SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.GetResource(sf); + SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.GetResource(sf); Assert.IsNotNull(holder, "Has thread session"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); - tt.PropagationBehavior = TransactionPropagation.NotSupported; + tt.PropagationBehavior = TransactionPropagation.NotSupported; tt.Execute(new NotSupportedTxCallback(sf)); Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false), "Same thread session as before"); @@ -942,8 +774,6 @@ public object DoInTransaction(ITransactionStatus status) Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); return null; } - - } public class NotSupportedTxCallback : ITransactionCallback @@ -957,8 +787,6 @@ public NotSupportedTxCallback(ISessionFactory sf) public object DoInTransaction(ITransactionStatus status) { - - Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sf), "Hasn't thread session"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive); @@ -971,25 +799,19 @@ public object DoInTransaction(ITransactionStatus status) public class NotSupportedTxCallbackInner : IHibernateCallback { - public object DoInHibernate(ISession session) { return null; } } - #endregion - - #region Supporting classes for test TransactionWithPropagationSupports - public class TransactionWithPropagationSupportsTxCallback : ITransactionCallback { private ISessionFactory sf; + public TransactionWithPropagationSupportsTxCallback(ISessionFactory sf) { - this.sf = sf; - } public object DoInTransaction(ITransactionStatus status) @@ -1013,10 +835,6 @@ private object Del(ISession session) } } - #endregion - - - #region Supporting classes for test ParticipatingTransactionWithWithNotSupported public class TransactionWithPropagationSupportsAndInnerTransactionTxCallback : ITransactionCallback { @@ -1026,7 +844,7 @@ public class TransactionWithPropagationSupportsAndInnerTransactionTxCallback : I private ISession session1; private ISession session2; - public TransactionWithPropagationSupportsAndInnerTransactionTxCallback(TransactionTemplate tt, + public TransactionWithPropagationSupportsAndInnerTransactionTxCallback(TransactionTemplate tt, ISessionFactory sf, HibernateTemplate ht, ISession session1, ISession session2) { this.tt = tt; @@ -1051,7 +869,7 @@ public object DoInTransaction(ITransactionStatus status) Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive); - + return null; } @@ -1085,16 +903,8 @@ private object HibernateDelegate(ISession session) return null; } } - - } - - - #endregion - - #region Supporting classes for DoTransactionCommitWithFlushFailure - public class TransactionCommitWithFlushFailureCallback : ITransactionCallback { private ISessionFactory sessionFactory; @@ -1112,13 +922,12 @@ public object DoInTransaction(ITransactionStatus status) HibernateTemplate ht = new HibernateTemplate(sessionFactory); return ht.ExecuteFind(new TransactionCommitWithFlushFailureHibernateCallback(list)); } - - } public class TransactionCommitWithFlushFailureHibernateCallback : IHibernateCallback { private IList list; + public TransactionCommitWithFlushFailureHibernateCallback(IList list) { this.list = list; @@ -1129,7 +938,4 @@ public object DoInHibernate(ISession session) return list; } } - - #endregion - } \ No newline at end of file diff --git a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/SessionFactoryUtilsTests.cs b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/SessionFactoryUtilsTests.cs index fe1d51557..f79852a53 100644 --- a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/SessionFactoryUtilsTests.cs +++ b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/SessionFactoryUtilsTests.cs @@ -18,22 +18,18 @@ #endregion -#region Imports - using System.Data.SqlClient; +using FakeItEasy; + using NHibernate.Connection; using NHibernate.Driver; using NHibernate.Engine; using NUnit.Framework; -using Rhino.Mocks; - using Spring.Data.Common; -#endregion - namespace Spring.Data.NHibernate { /// @@ -46,23 +42,19 @@ public class SessionFactoryUtilsTests [Test] public void SessionFactoryUtilsWithGetDbProvider() { - MockRepository mockery = new MockRepository(); - ISessionFactoryImplementor sessionFactory = mockery.DynamicMock(); + ISessionFactoryImplementor sessionFactory = A.Fake(); - DriverBase driver = mockery.DynamicMock(); - Expect.Call(driver.CreateCommand()).Repeat.AtLeastOnce().Return(new SqlCommand()); + DriverBase driver = A.Fake(); + A.CallTo(() => driver.CreateCommand()).Returns(new SqlCommand()); - IConnectionProvider cp = mockery.DynamicMock(); - Expect.Call(cp.Driver).Repeat.AtLeastOnce().Return(driver); + IConnectionProvider cp = A.Fake(); + A.CallTo(() => cp.Driver).Returns(driver); - Expect.Call(sessionFactory.ConnectionProvider).Repeat.AtLeastOnce().Return(cp); + A.CallTo(() => sessionFactory.ConnectionProvider).Returns(cp); - mockery.ReplayAll(); IDbProvider provider = SessionFactoryUtils.GetDbProvider(sessionFactory); Assert.AreEqual(typeof(SqlCommand), provider.DbMetadata.CommandType); - - mockery.VerifyAll(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/ConfigSectionSessionScopeSettingsTests.cs b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/ConfigSectionSessionScopeSettingsTests.cs index 1fa33ad8e..d14f978a1 100644 --- a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/ConfigSectionSessionScopeSettingsTests.cs +++ b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/ConfigSectionSessionScopeSettingsTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,11 @@ #region Imports +using FakeItEasy; + using NHibernate; using NUnit.Framework; -using Rhino.Mocks; + using Spring.Context.Support; using Spring.Objects.Factory.Config; @@ -43,8 +45,7 @@ public void CanCreateWithDefaults() string SESSIONFACTORY_OBJECTNAME = ConfigSectionSessionScopeSettings.DEFAULT_SESSION_FACTORY_OBJECT_NAME; // setup expected values - MockRepository mocks = new MockRepository(); - ISessionFactory expectedSessionFactory = mocks.StrictMock(); + ISessionFactory expectedSessionFactory = A.Fake(); IInterceptor expectedEntityInterceptor = null; bool expectedSingleSession = SessionScopeSettings.SINGLESESSION_DEFAULT; FlushMode expectedDefaultFlushMode = SessionScopeSettings.FLUSHMODE_DEFAULT; @@ -70,9 +71,8 @@ public void CanCreateFromExplicitConfiguration() string SESSIONFACTORY_OBJECTNAME = "SessionFactory"; string ENTITYINTERCEPTOR_OBJECTNAME = "EntityInterceptor"; - MockRepository mocks = new MockRepository(); - ISessionFactory expectedSessionFactory = mocks.StrictMock(); - IInterceptor expectedEntityInterceptor = mocks.StrictMock(); + ISessionFactory expectedSessionFactory = A.Fake(); + IInterceptor expectedEntityInterceptor = A.Fake(); bool expectedSingleSession = false; FlushMode expectedDefaultFlushMode = FlushMode.Auto; @@ -93,7 +93,7 @@ public void CanCreateFromExplicitConfiguration() .Add(thisTypeName + ".DefaultFlushMode", expectedDefaultFlushMode.ToString().ToLower() ) // case insensitive! ; - + ConfigSectionSessionScopeSettings settings = new ConfigSectionSessionScopeSettings(this.GetType(), variableSource); Assert.AreEqual( expectedSessionFactory, settings.SessionFactory ); diff --git a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeSettingsTests.cs b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeSettingsTests.cs index b28c2f773..5113f64b6 100644 --- a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeSettingsTests.cs +++ b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeSettingsTests.cs @@ -18,14 +18,13 @@ #endregion -#region Imports - using System; + +using FakeItEasy; + using NHibernate; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using NUnit.Framework; namespace Spring.Data.NHibernate.Support { @@ -39,7 +38,7 @@ public class SessionScopeSettingsTests private class DerivedSessionScopeSettings : SessionScopeSettings { public DerivedSessionScopeSettings() - :base() // note, that we're calling default ctor here + : base() // note, that we're calling default ctor here { } } @@ -73,23 +72,22 @@ protected override IInterceptor ResolveEntityInterceptor() [Test] public void CheckDefaults() { - Assert.IsTrue( SessionScopeSettings.SINGLESESSION_DEFAULT ); - Assert.AreEqual( FlushMode.Never, SessionScopeSettings.FLUSHMODE_DEFAULT ); + Assert.IsTrue(SessionScopeSettings.SINGLESESSION_DEFAULT); + Assert.AreEqual(FlushMode.Never, SessionScopeSettings.FLUSHMODE_DEFAULT); } [Test] public void WorksAsExpected() { - MockRepository mocks = new MockRepository(); - ISessionFactory sessionFactory = mocks.StrictMock(); - IInterceptor entityInterceptor = mocks.StrictMock(); - Assert.AreNotEqual( FlushMode.Auto, SessionScopeSettings.FLUSHMODE_DEFAULT ); // ensure noone changed our assumptions - SessionScopeSettings sss = new SessionScopeSettings(sessionFactory, entityInterceptor, !SessionScopeSettings.SINGLESESSION_DEFAULT, FlushMode.Auto ); - - Assert.AreEqual( sessionFactory, sss.SessionFactory ); - Assert.AreEqual( entityInterceptor, sss.EntityInterceptor); - Assert.AreEqual( !SessionScopeSettings.SINGLESESSION_DEFAULT, sss.SingleSession ); - Assert.AreEqual( FlushMode.Auto, sss.DefaultFlushMode ); + ISessionFactory sessionFactory = A.Fake(); + IInterceptor entityInterceptor = A.Fake(); + Assert.AreNotEqual(FlushMode.Auto, SessionScopeSettings.FLUSHMODE_DEFAULT); // ensure noone changed our assumptions + SessionScopeSettings sss = new SessionScopeSettings(sessionFactory, entityInterceptor, !SessionScopeSettings.SINGLESESSION_DEFAULT, FlushMode.Auto); + + Assert.AreEqual(sessionFactory, sss.SessionFactory); + Assert.AreEqual(entityInterceptor, sss.EntityInterceptor); + Assert.AreEqual(!SessionScopeSettings.SINGLESESSION_DEFAULT, sss.SingleSession); + Assert.AreEqual(FlushMode.Auto, sss.DefaultFlushMode); } [Test] @@ -108,15 +106,16 @@ public void CallingDefaultConstructorLeavesReferencesMarkedUninitialized() ISessionFactory sessionFactory = sss.SessionFactory; Assert.Fail("should fail, because derived classes must override ResolveSessionFactory()"); } - catch (NotSupportedException) { } + catch (NotSupportedException) + { + } } [Test] public void CallingDefaultConstructorCausesLazyResolvingReferences() { - MockRepository mocks = new MockRepository(); - ISessionFactory expectedSessionFactory = mocks.StrictMock(); - IInterceptor expectedEntityInterceptor = mocks.StrictMock(); + ISessionFactory expectedSessionFactory = A.Fake(); + IInterceptor expectedEntityInterceptor = A.Fake(); SessionScopeSettings sss = new LazyResolvingSessionScopeSettings(expectedSessionFactory, expectedEntityInterceptor); @@ -144,8 +143,7 @@ public void MissingSessionFactoryCausesArgumentExceptionDuringLazyResolving() [Test] public void MissingEntityInterceptorIsOkDuringLazyResolving() { - MockRepository mocks = new MockRepository(); - ISessionFactory expectedSessionFactory = mocks.StrictMock(); + ISessionFactory expectedSessionFactory = A.Fake(); SessionScopeSettings sss = new LazyResolvingSessionScopeSettings(expectedSessionFactory, null); @@ -156,6 +154,5 @@ public void MissingEntityInterceptorIsOkDuringLazyResolving() Assert.AreSame(expectedSessionFactory, sss.SessionFactory); Assert.AreSame(null, sss.EntityInterceptor); } - } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeTests.cs b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeTests.cs index 3f410c7dc..8ab41430c 100644 --- a/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeTests.cs +++ b/test/Spring/Spring.Data.NHibernate.Tests/Data/NHibernate/Support/SessionScopeTests.cs @@ -21,11 +21,16 @@ #region Imports using System; + +using FakeItEasy; + using NHibernate; using NUnit.Framework; -using Rhino.Mocks; + using Spring.Transaction.Support; +using static FakeItEasy.A; + #endregion namespace Spring.Data.NHibernate.Support @@ -37,7 +42,6 @@ namespace Spring.Data.NHibernate.Support [TestFixture] public class SessionScopeTests { - private MockRepository mocks; private ISessionFactory expectedSessionFactory; private IInterceptor expectedEntityInterceptor; private bool expectedSingleSession; @@ -46,9 +50,8 @@ public class SessionScopeTests [SetUp] public void SetUp() { - mocks = new MockRepository(); - expectedSessionFactory = mocks.StrictMock(); - expectedEntityInterceptor = mocks.StrictMock(); + expectedSessionFactory = Fake(); + expectedEntityInterceptor = Fake(); expectedSingleSession = SessionScopeSettings.SINGLESESSION_DEFAULT; expectedDefaultFlushMode = SessionScopeSettings.FLUSHMODE_DEFAULT; } @@ -74,14 +77,9 @@ public void CanCreateAndClose() [Test] public void CanCreateAndCloseSimpleCtor() { - using (mocks.Ordered()) - { - ISession session = mocks.StrictMock(); - Expect.Call(expectedSessionFactory.OpenSession()).Return(session); - session.FlushMode = FlushMode.Never; - Expect.Call(session.Close()).Return(null); - } - mocks.ReplayAll(); + ISession session = Fake(); + CallTo(() => expectedSessionFactory.OpenSession()).Returns(session); + using (SessionScope scope = new SessionScope(expectedSessionFactory, true)) { // no op - just create & dispose @@ -99,7 +97,9 @@ public void CanCreateAndCloseSimpleCtor() Assert.IsNotNull(sessionHolder.Session); scope.Close(); } - mocks.VerifyAll(); + + CallToSet(() => session.FlushMode).WhenArgumentsMatch(x => x.Get(0) == FlushMode.Never).MustHaveHappenedOnceExactly(); + CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); } [Test] @@ -210,12 +210,9 @@ public void SingleSessionRegistersSessionHolderWithTSM() [Test] public void SingleSessionAppliesDefaultFlushModeOnOpenSessionAndClosesSession() { - ISession expectedSession = mocks.StrictMock(); + ISession expectedSession = Fake(); - Expect.Call(expectedSessionFactory.OpenSession()).Return(expectedSession); - expectedSession.FlushMode = FlushMode.Auto; - Expect.Call(expectedSession.Close()).Return(null); - mocks.ReplayAll(); + CallTo(() => expectedSessionFactory.OpenSession()).Returns(expectedSession); SessionScope scope = null; using (scope = new SessionScope(expectedSessionFactory, null, true, FlushMode.Auto, true)) @@ -227,7 +224,8 @@ public void SingleSessionAppliesDefaultFlushModeOnOpenSessionAndClosesSession() Assert.IsFalse(scope.IsOpen); Assert.IsFalse(TransactionSynchronizationManager.HasResource(expectedSessionFactory)); - mocks.VerifyAll(); + CallToSet(() => expectedSession.FlushMode).WhenArgumentsMatch(x => x.Get(0) == FlushMode.Auto).MustHaveHappenedOnceExactly(); + CallTo(() => expectedSession.Close()).MustHaveHappenedOnceExactly(); } [Test] @@ -287,39 +285,29 @@ public virtual IInterceptor DoResolveEntityInterceptor() [Test] public void ResolvesEntityInterceptorOnEachOpen() { - TestSessionScopeSettings sss = - (TestSessionScopeSettings)mocks.PartialMock(typeof(TestSessionScopeSettings), expectedSessionFactory); - ISession expectedSession = mocks.StrictMock(); + TestSessionScopeSettings sss = Fake(options => options + .CallsBaseMethods() + .WithArgumentsForConstructor(new[] {expectedSessionFactory}) + ); + ISession expectedSession = Fake(); sss.DefaultFlushMode = FlushMode.Never; SessionScope sc = new SessionScope(sss, false); - - using (mocks.Ordered()) - { - Expect.Call(sss.DoResolveEntityInterceptor()).Return(expectedEntityInterceptor); - Expect.Call(expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Return(expectedSession); - expectedSession.FlushMode = FlushMode.Never; - Expect.Call(expectedSession.Close()).Return(null); - - Expect.Call(sss.DoResolveEntityInterceptor()).Return(expectedEntityInterceptor); - Expect.Call(expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Return(expectedSession); - expectedSession.FlushMode = FlushMode.Never; - Expect.Call(expectedSession.Close()).Return(null); - } - mocks.ReplayAll(); + CallTo(() => sss.DoResolveEntityInterceptor()).Returns(expectedEntityInterceptor); + CallTo(() => expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Returns(expectedSession); sc.Open(); - SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory); + SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.GetResource(expectedSessionFactory); sessionHolder.ContainsSession(null); // force opening session sc.Close(); sc.Open(); - sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory); + sessionHolder = (SessionHolder) TransactionSynchronizationManager.GetResource(expectedSessionFactory); sessionHolder.ContainsSession(null); // force opening session sc.Close(); - mocks.VerifyAll(); + CallToSet(() => expectedSession.FlushMode).WhenArgumentsMatch(x => x.Get(0) == FlushMode.Never).MustHaveHappenedTwiceExactly(); + CallTo(() => expectedSession.Close()).MustHaveHappenedTwiceExactly(); } - - } + } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.NHibernate3.Tests/Spring.Data.NHibernate3.Tests.2010.csproj b/test/Spring/Spring.Data.NHibernate3.Tests/Spring.Data.NHibernate3.Tests.2010.csproj index 586d06584..7a3bdd5e1 100644 --- a/test/Spring/Spring.Data.NHibernate3.Tests/Spring.Data.NHibernate3.Tests.2010.csproj +++ b/test/Spring/Spring.Data.NHibernate3.Tests/Spring.Data.NHibernate3.Tests.2010.csproj @@ -10,10 +10,11 @@ + + - diff --git a/test/Spring/Spring.Data.NHibernate4.Tests/Spring.Data.NHibernate4.Tests.2010.csproj b/test/Spring/Spring.Data.NHibernate4.Tests/Spring.Data.NHibernate4.Tests.2010.csproj index 896283dc2..d69fad650 100644 --- a/test/Spring/Spring.Data.NHibernate4.Tests/Spring.Data.NHibernate4.Tests.2010.csproj +++ b/test/Spring/Spring.Data.NHibernate4.Tests/Spring.Data.NHibernate4.Tests.2010.csproj @@ -10,10 +10,11 @@ + + - diff --git a/test/Spring/Spring.Data.Tests/Data/AdoPlatformTransactionManagerTests.cs b/test/Spring/Spring.Data.Tests/Data/AdoPlatformTransactionManagerTests.cs index 6f0c58884..6b9d341f1 100644 --- a/test/Spring/Spring.Data.Tests/Data/AdoPlatformTransactionManagerTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/AdoPlatformTransactionManagerTests.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +14,14 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.Data; using System.Threading; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Dao; using Spring.Data.Common; using Spring.Data.Core; @@ -33,8 +30,6 @@ using Spring.Transaction; using Spring.Transaction.Support; -#endregion - namespace Spring.Data { /// @@ -44,15 +39,8 @@ namespace Spring.Data [TestFixture] public class AdoPlatformTransactionManagerTests { - private MockRepository mocks; private const IsolationLevel DefaultIsolationLevel = IsolationLevel.ReadCommitted; - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [TearDown] public void TearDown() { @@ -65,26 +53,12 @@ public void TearDown() [Test] public void TransactionCommit() { - #region Mock setup - IDbProvider dbProvider = (IDbProvider) mocks.CreateMock(typeof (IDbProvider)); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -99,34 +73,21 @@ public void TransactionCommit() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + //standard tx timeout. + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionRollback() { - #region Mock Setup - - IDbProvider dbProvider = (IDbProvider) mocks.CreateMock(typeof (IDbProvider)); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - - connection.Dispose(); - } - - #endregion + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -150,29 +111,21 @@ public void TransactionRollback() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - - mocks.VerifyAll(); + //standard tx timeout. + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void ParticipatingTransactionWithRollbackOnly() { - IDbProvider dbProvider = (IDbProvider) mocks.CreateMock(typeof (IDbProvider)); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -203,6 +156,7 @@ public void ParticipatingTransactionWithRollbackOnly() { tm.Rollback(ts); } + Assert.IsTrue(outerTransactionBoundaryReached); } @@ -212,7 +166,10 @@ public void ParticipatingTransactionWithRollbackOnly() Assert.IsFalse(synch.afterCommitCalled); Assert.IsTrue(synch.afterCompletionCalled); - mocks.VerifyAll(); + //standard tx timeout. + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] @@ -228,28 +185,12 @@ public void ParticipatingTransactionWithRollbackOnlyAndInnerSynch() [Test] public void PropagationRequiresNewWithExistingTransaction() { - #region Mock Setup - IDbProvider dbProvider = (IDbProvider) mocks.CreateMock(typeof (IDbProvider)); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - Expect.Call(dbProvider.CreateConnection()).Return(connection).Repeat.Twice(); - connection.Open(); - LastCall.On(connection).Repeat.Twice(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction).Repeat.Twice(); - //standard tx timeout. - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - - connection.Dispose(); - LastCall.On(connection).Repeat.Twice(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - #endregion - - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -265,37 +206,28 @@ public void PropagationRequiresNewWithExistingTransaction() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedTwiceExactly(); } [Test] public void PropagationRequiresNewWithExistingTransactionAndUnrelatedDataSource() { - IDbProvider dbProvider = (IDbProvider) mocks.CreateMock(typeof (IDbProvider)); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); - IDbProvider dbProvider2 = (IDbProvider) mocks.CreateMock(typeof (IDbProvider)); - IDbConnection connection2 = mocks.StrictMock(); - IDbTransaction transaction2 = mocks.StrictMock(); - Expect.Call(dbProvider2.CreateConnection()).Return(connection2); - connection2.Open(); - LastCall.On(connection2).Repeat.Once(); - Expect.Call(connection2.BeginTransaction(DefaultIsolationLevel)).Return(transaction2); - transaction2.Rollback(); - LastCall.On(transaction2).Repeat.Once(); - connection2.Dispose(); + IDbProvider dbProvider2 = A.Fake(); + IDbConnection connection2 = A.Fake(); + IDbTransaction transaction2 = A.Fake(); - mocks.ReplayAll(); + A.CallTo(() => dbProvider2.CreateConnection()).Returns(connection2); + A.CallTo(() => connection2.BeginTransaction(DefaultIsolationLevel)).Returns(transaction2); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -319,36 +251,31 @@ public void PropagationRequiresNewWithExistingTransactionAndUnrelatedDataSource( Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider2), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); + + A.CallTo(() => connection2.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction2.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection2.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void PropagationRequiresNewWithExistingTransactionAndUnrelatedFailingDataSource() { - #region Mock Setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - - IDbProvider dbProvider2 = mocks.StrictMock(); - IDbConnection connection2 = mocks.StrictMock(); - - Expect.Call(dbProvider2.CreateConnection()).Return(connection2); - connection2.Open(); - Exception failure = new Exception("can't open connection"); - LastCall.On(connection2).Throw(failure); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - #endregion + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); - mocks.ReplayAll(); + IDbProvider dbProvider2 = A.Fake(); + IDbConnection connection2 = A.Fake(); + + A.CallTo(() => dbProvider2.CreateConnection()).Returns(connection2); + Exception failure = new Exception("can't open connection"); + A.CallTo(() => connection2.Open()).Throws(failure); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -370,38 +297,29 @@ public void PropagationRequiresNewWithExistingTransactionAndUnrelatedFailingData tt.Execute( new PropagationRequiresNewWithExistingTransactionAndUnrelatedFailingDataSourceCallback(tt2)); Assert.Fail("Should have thrown CannotCreateTransactionException"); - } catch(CannotCreateTransactionException ex) + } + catch (CannotCreateTransactionException ex) { Assert.AreSame(failure, ex.InnerException); } Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider2), "Hasn't thread db provider"); - mocks.VerifyAll(); + + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void PropagationNotSupportedWithExistingTransaction() { - #region Mock Setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - #endregion - - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -413,32 +331,20 @@ public void PropagationNotSupportedWithExistingTransaction() tt.Execute(new PropagationNotSupportedWithExistingTransactionCallback(tt, dbProvider)); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void PropagationNeverWithExistingTransaction() { - #region Mock Setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - - connection.Dispose(); - } - #endregion - - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -452,42 +358,31 @@ public void PropagationNeverWithExistingTransaction() { tt.Execute(new PropagationNeverWithExistingTransactionCallback(tt)); Assert.Fail("Should have thrown IllegalTransactionStateException"); - } catch (IllegalTransactionStateException) + } + catch (IllegalTransactionStateException) { //expected. } + Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void PropagationRequiresNewWithExistingConnection() { - #region Mock Setup - - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - connection.Dispose(); - - IDbConnection connection2 = mocks.StrictMock(); - IDbTransaction transaction2 = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbConnection connection2 = A.Fake(); + IDbTransaction transaction2 = A.Fake(); - Expect.Call(dbProvider.CreateConnection()).Return(connection2); - connection2.Open(); - LastCall.On(connection2).Repeat.Once(); - Expect.Call(connection2.BeginTransaction(DefaultIsolationLevel)).Return(transaction2); - transaction2.Commit(); - LastCall.On(transaction2).Repeat.Once(); - connection2.Dispose(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection).Once() + .Then.Returns(connection2).Once(); - #endregion - - mocks.ReplayAll(); + A.CallTo(() => connection2.BeginTransaction(DefaultIsolationLevel)).Returns(transaction2); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -499,35 +394,22 @@ public void PropagationRequiresNewWithExistingConnection() tt.Execute(new PropagationRequiresNewWithExistingConnectionCallback(tt, connection, connection2, dbProvider)); - Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection2.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection2.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithIsolation() { - #region Mock setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(IsolationLevel.Serializable)).Return(transaction); - //standard tx timeout. - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(IsolationLevel.Serializable)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -541,13 +423,15 @@ public void TransactionWithIsolation() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithLongTimeout() { - DoTransactionWithTimeout(10); + DoTransactionWithTimeout(10); } [Test] @@ -558,38 +442,13 @@ public void TransactionWithShortTimeout() private void DoTransactionWithTimeout(int timeout) { - #region Mock setup - - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - IDbCommand command = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - Expect.Call(connection.CreateCommand()).Return(command); - command.CommandText = "some SQL statement"; - LastCall.On(command).Repeat.Once(); - if (timeout > 1) - { - command.CommandTimeout = (timeout - 1); - transaction.Commit(); - } else - { - transaction.Rollback(); - } - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + IDbCommand command = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); + A.CallTo(() => connection.CreateCommand()).Returns(command); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -606,12 +465,14 @@ private void DoTransactionWithTimeout(int timeout) { Assert.Fail("Should have thrown TransactionTimedOutException"); } - } catch (TransactionTimedOutException) + } + catch (TransactionTimedOutException) { - if (timeout <=1 ) + if (timeout <= 1) { //expected - } else + } + else { throw; } @@ -619,22 +480,28 @@ private void DoTransactionWithTimeout(int timeout) Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); + A.CallToSet(() => command.CommandText).WhenArgumentsMatch(x => x.Get(0) == "some SQL statement").MustHaveHappenedOnceExactly(); + + if (timeout > 1) + { + A.CallToSet(() => command.CommandTimeout).WhenArgumentsMatch(x => (int) x[0] == (timeout - 1)).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + } + else + { + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + } } [Test] public void TransactionWithExceptionOnBegin() { - #region Mock setup - IDbProvider dbProvider = mocks.StrictMock(); - - // CreateConnection is called in AdoPlatformTransactionManager.DoBegin - Expect.Call(dbProvider.CreateConnection()).Throw(new TestSqlException("Cannot begin", "314")); - + IDbProvider dbProvider = A.Fake(); - #endregion - - mocks.ReplayAll(); + // CreateConnection is called in AdoPlatformTransactionManager.DoBegin + A.CallTo(() => dbProvider.CreateConnection()).Throws(new TestSqlException("Cannot begin", "314")); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -642,16 +509,14 @@ public void TransactionWithExceptionOnBegin() TransactionTemplate tt = new TransactionTemplate(tm); try { - tt.Execute(new TransactionDelegate(TransactionWithExceptionNoOp)); - } catch (CannotCreateTransactionException) + tt.Execute(TransactionWithExceptionNoOp); + } + catch (CannotCreateTransactionException) { // expected } - Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - - mocks.VerifyAll(); } private object TransactionWithExceptionNoOp(ITransactionStatus status) @@ -662,70 +527,44 @@ private object TransactionWithExceptionNoOp(ITransactionStatus status) [Test] public void TransactionWithExceptionOnCommit() { - #region Mock setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Commit(); - LastCall.On(transaction).Throw(new TestSqlException("Cannot commit", "314")); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); + A.CallTo(() => transaction.Commit()).Throws(new TestSqlException("Cannot commit", "314")); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); - + try { - tt.Execute(new TransactionDelegate(TransactionWithExceptionNoOp)); - } catch (TransactionSystemException) + tt.Execute(TransactionWithExceptionNoOp); + } + catch (TransactionSystemException) { //expected } + Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); - + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithExceptionOnCommitAndRollbackOnCommitFailure() { - #region Mock Setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - transaction.Commit(); - LastCall.On(transaction).Throw(new TestSqlException("Cannot commit", "314")); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - - connection.Dispose(); - } - #endregion - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); + A.CallTo(() => transaction.Commit()).Throws(new TestSqlException("Cannot commit", "314")); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -735,7 +574,7 @@ public void TransactionWithExceptionOnCommitAndRollbackOnCommitFailure() try { - tt.Execute(new TransactionDelegate(TransactionWithExceptionNoOp)); + tt.Execute(TransactionWithExceptionNoOp); } catch (TransactionSystemException) { @@ -744,34 +583,20 @@ public void TransactionWithExceptionOnCommitAndRollbackOnCommitFailure() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithExceptionOnRollback() { - #region Mock Setup - - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Rollback(); - LastCall.On(transaction).Throw(new TestSqlException("Cannot commit", "314")); - - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); + A.CallTo(() => transaction.Rollback()).Throws(new TestSqlException("Cannot commit", "314")); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -780,7 +605,7 @@ public void TransactionWithExceptionOnRollback() try { - tt.Execute(new TransactionDelegate(TransactionWithExceptionOnRollbackMethod)); + tt.Execute(TransactionWithExceptionOnRollbackMethod); } catch (TransactionSystemException) { @@ -789,8 +614,9 @@ public void TransactionWithExceptionOnRollback() Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); - + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } private object TransactionWithExceptionOnRollbackMethod(ITransactionStatus status) @@ -802,9 +628,7 @@ private object TransactionWithExceptionOnRollbackMethod(ITransactionStatus statu [Test] public void TransactionWithPropagationSupports() { - IDbProvider dbProvider = mocks.StrictMock(); - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -817,15 +641,12 @@ public void TransactionWithPropagationSupports() tt.Execute(new TransactionWithPropagationSupportsCallback(dbProvider)); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); } [Test] public void TransactionWithPropagationNotSupported() { - IDbProvider dbProvider = mocks.StrictMock(); - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -838,15 +659,12 @@ public void TransactionWithPropagationNotSupported() tt.Execute(new TransactionWithPropagationNotSupportedCallback(dbProvider)); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); } [Test] public void TransactionWithPropagationNever() { - IDbProvider dbProvider = mocks.StrictMock(); - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -859,39 +677,23 @@ public void TransactionWithPropagationNever() tt.Execute(new TransactionWithPropagationNotSupportedCallback(dbProvider)); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); } [Test] public void ExistingTransactionWithPropagationNestedNotSupported() { - #region Mock setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.Nested; - + Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); @@ -899,38 +701,26 @@ public void ExistingTransactionWithPropagationNestedNotSupported() { tt.Execute(new ExistingTransactionWithPropagationNestedCallback(dbProvider, tt)); Assert.Fail("Should have thrown NestedTransactionNotSupportedException"); - } catch (NestedTransactionNotSupportedException) + } + catch (NestedTransactionNotSupportedException) { - // expected + // expected } Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void TransactionWithPropagationNested() { - #region Mock setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - //standard tx timeout. - transaction.Commit(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -942,12 +732,13 @@ public void TransactionWithPropagationNested() Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - tt.Execute(new TransactionDelegate(TransactionWithPropagationNestedMethod)); + tt.Execute(TransactionWithPropagationNestedMethod); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); - + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } private object TransactionWithPropagationNestedMethod(ITransactionStatus status) @@ -959,25 +750,11 @@ private object TransactionWithPropagationNestedMethod(ITransactionStatus status) [Test] public void TransactionWithPropagationNestedAndRollback() { - #region Mock setup - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - IDbTransaction transaction = mocks.StrictMock(); - - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - connection.Open(); - LastCall.On(connection).Repeat.Once(); - Expect.Call(connection.BeginTransaction(DefaultIsolationLevel)).Return(transaction); - transaction.Rollback(); - LastCall.On(transaction).Repeat.Once(); - connection.Dispose(); - } - - #endregion - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + IDbTransaction transaction = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => connection.BeginTransaction(DefaultIsolationLevel)).Returns(transaction); AdoPlatformTransactionManager tm = new AdoPlatformTransactionManager(dbProvider); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -989,12 +766,13 @@ public void TransactionWithPropagationNestedAndRollback() Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - tt.Execute(new TransactionDelegate(TransactionWithPropagationNestedAndRollbackMethod)); + tt.Execute(TransactionWithPropagationNestedAndRollbackMethod); Assert.IsTrue(!TransactionSynchronizationManager.HasResource(dbProvider), "Hasn't thread db provider"); - mocks.VerifyAll(); - + A.CallTo(() => connection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Dispose()).MustHaveHappenedOnceExactly(); } private object TransactionWithPropagationNestedAndRollbackMethod(ITransactionStatus status) @@ -1020,7 +798,7 @@ public object DoInTransaction(ITransactionStatus status) { Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); //TODO: Note no support for savepoints at this time (1.1), so can't check that a savepoint isn't present. - + tt.Execute(new ExistingTransactionWithPropagationNestedCallback2(dbProvider)); Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); @@ -1048,7 +826,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #region Supporting class for TransactionWithPropagationNotSupported internal class TransactionWithPropagationNotSupportedCallback : ITransactionCallback { private IDbProvider provider; @@ -1065,9 +842,7 @@ public object DoInTransaction(ITransactionStatus status) return null; } } - #endregion - #region Supporting class for TransactionWithPropagationSupports internal class TransactionWithPropagationSupportsCallback : ITransactionCallback { private IDbProvider provider; @@ -1080,20 +855,18 @@ public TransactionWithPropagationSupportsCallback(IDbProvider provider) public object DoInTransaction(ITransactionStatus status) { Assert.IsTrue(!TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider"); - Assert.IsTrue(!status.IsNewTransaction,"Is not new transaction"); + Assert.IsTrue(!status.IsNewTransaction, "Is not new transaction"); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive); return null; } } - #endregion - - #region Supporting class for TransactionWithTimeout internal class TransactionWithTimeoutCallback : ITransactionCallback { private IDbProvider provider; + public TransactionWithTimeoutCallback(IDbProvider provider) { this.provider = provider; @@ -1104,31 +877,31 @@ public object DoInTransaction(ITransactionStatus status) try { Thread.Sleep(1500); - } catch (Exception) + } + catch (Exception) { - } + try { IDbConnection con = ConnectionUtils.GetConnection(provider); IDbCommand cmd = con.CreateCommand(); cmd.CommandText = "some SQL statement"; ConnectionUtils.ApplyTransactionTimeout(cmd, provider); - - } catch (Exception e) + } + catch (Exception e) { if (e.GetType() != typeof(TransactionTimedOutException)) { throw new DataAccessResourceFailureException("", e); } + throw; } + return null; } } - #endregion - - #region Supporting class for PropagationRequiresNewWithExistingConnection internal class PropagationRequiresNewWithExistingConnectionCallback : ITransactionCallback { @@ -1182,10 +955,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting classes for PropagationNeverWithExistingTransaction - internal class PropagationNeverWithExistingTransactionCallback : ITransactionCallback { private TransactionTemplate innerTxTemplate; @@ -1203,12 +972,11 @@ public object DoInTransaction(ITransactionStatus status) innerTxTemplate.Execute(new PropagationNeverWithExistingTransactionCallback2()); Assert.Fail("Should have thrown IllegalTransactionStateException"); return null; - } + } } internal class PropagationNeverWithExistingTransactionCallback2 : ITransactionCallback { - public object DoInTransaction(ITransactionStatus status) { Assert.Fail("Should have thrown IllegalTransactionStateException"); @@ -1216,10 +984,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting classes for PropagationNotSupportedWithExistingTransaction - internal class PropagationNotSupportedWithExistingTransactionCallback : ITransactionCallback { private TransactionTemplate innerTxTemplate; @@ -1266,10 +1030,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting class for PropagationRequiresNewWithExistingTransactionAndUnrelatedFailingDataSource - internal class PropagationRequiresNewWithExistingTransactionAndUnrelatedFailingDataSourceCallback : ITransactionCallback { private TransactionTemplate innerTxTemplate; @@ -1300,17 +1060,13 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting class for PropagationRequiresNewWithExistingTransaction - internal class PropagationRequiresNewWithExistingTransactionCallback : ITransactionCallback { private TransactionTemplate innerTxTemplate; private IDbProvider dbProvider; public PropagationRequiresNewWithExistingTransactionCallback(TransactionTemplate transactionTemplate, - IDbProvider provider) + IDbProvider provider) { innerTxTemplate = transactionTemplate; dbProvider = provider; @@ -1352,10 +1108,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting class for TransactionCommit test - internal class TransactionCommitTxCallback : ITransactionCallback { private IDbProvider provider; @@ -1376,10 +1128,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting class for TransactionRollback test - internal class TransactionRollbackTxCallback : ITransactionCallback { private IDbProvider provider; @@ -1400,10 +1148,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting class for ParticipatingTxWithRollbackOnly test - internal class ParticipatingTxWithRollbackOnlyTxCallback : ITransactionCallback { private TransactionTemplate innerTxTemplate; @@ -1446,11 +1190,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - - - #region Helper class internal class TestTransactionSynchronization : ITransactionSynchronization { @@ -1463,7 +1202,7 @@ internal class TestTransactionSynchronization : ITransactionSynchronization public bool afterCompletionCalled; public TestTransactionSynchronization(IDbProvider provider, - TransactionSynchronizationStatus synchronizationStatus) + TransactionSynchronizationStatus synchronizationStatus) { this.provider = provider; status = synchronizationStatus; @@ -1484,6 +1223,7 @@ public void BeforeCommit(bool readOnly) { Assert.Fail("Should never be called"); } + Assert.IsFalse(beforeCommitCalled); beforeCommitCalled = true; } @@ -1494,6 +1234,7 @@ public void AfterCommit() { Assert.Fail("Should never be called"); } + Assert.IsFalse(afterCommitCalled); afterCommitCalled = true; } @@ -1512,6 +1253,4 @@ public void AfterCompletion(TransactionSynchronizationStatus syncStatus) Assert.IsTrue(TransactionSynchronizationManager.HasResource(provider)); } } - - #endregion } \ No newline at end of file diff --git a/test/Spring/Spring.Data.Tests/Data/Common/MultiDelegatingDbProviderTests.cs b/test/Spring/Spring.Data.Tests/Data/Common/MultiDelegatingDbProviderTests.cs index e3d84ab38..7f918805d 100644 --- a/test/Spring/Spring.Data.Tests/Data/Common/MultiDelegatingDbProviderTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Common/MultiDelegatingDbProviderTests.cs @@ -22,8 +22,11 @@ using System.Collections; using System.Data; using System.Data.Common; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Dao; using Spring.Threading; @@ -36,14 +39,6 @@ namespace Spring.Data.Common [TestFixture] public class MultiDelegatingDbProviderTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void CreationWhenNoRequiredPropertiesSet() { @@ -197,33 +192,33 @@ public void FallbackToDefault() [Test] public void CreateOperations() { - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection mockConnection = mocks.StrictMock(); - Expect.Call(dbProvider.CreateConnection()).Return(mockConnection).Repeat.Once(); + IDbProvider dbProvider = A.Fake(); + IDbConnection mockConnection = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(mockConnection).Once(); - IDbCommand mockCommand = (IDbCommand)mocks.CreateMock(typeof(IDbCommand)); - Expect.Call(dbProvider.CreateCommand()).Return(mockCommand).Repeat.Once(); + IDbCommand mockCommand = A.Fake(); + A.CallTo(() => dbProvider.CreateCommand()).Returns(mockCommand).Once(); - IDbDataParameter mockParameter = (IDbDataParameter) mocks.CreateMock(typeof (IDbDataParameter)); - Expect.Call(dbProvider.CreateParameter()).Return(mockParameter).Repeat.Once(); + IDbDataParameter mockParameter = A.Fake(); + A.CallTo(() => dbProvider.CreateParameter()).Returns(mockParameter).Once(); - IDbDataAdapter mockDataAdapter = (IDbDataAdapter) mocks.CreateMock(typeof (IDbDataAdapter)); - Expect.Call(dbProvider.CreateDataAdapter()).Return(mockDataAdapter).Repeat.Once(); + IDbDataAdapter mockDataAdapter = A.Fake(); + A.CallTo(() => dbProvider.CreateDataAdapter()).Returns(mockDataAdapter).Once(); - DbCommandBuilder mockDbCommandBuilder = (DbCommandBuilder) mocks.CreateMock(typeof (DbCommandBuilder)); - Expect.Call(dbProvider.CreateCommandBuilder()).Return(mockDbCommandBuilder).Repeat.Once(); + DbCommandBuilder mockDbCommandBuilder = A.Fake(); + A.CallTo(() => dbProvider.CreateCommandBuilder()).Returns(mockDbCommandBuilder).Once(); - Expect.Call(dbProvider.CreateParameterName("p1")).Return("@p1").Repeat.Once(); - Expect.Call(dbProvider.CreateParameterNameForCollection("c1")).Return("cc1"); + A.CallTo(() => dbProvider.CreateParameterName("p1")).Returns("@p1").Once(); + A.CallTo(() => dbProvider.CreateParameterNameForCollection("c1")).Returns("cc1"); - IDbMetadata mockDbMetaData = (IDbMetadata) mocks.CreateMock(typeof (IDbMetadata)); - Expect.Call(dbProvider.DbMetadata).Return(mockDbMetaData); + IDbMetadata mockDbMetaData = A.Fake(); + A.CallTo(() => dbProvider.DbMetadata).Returns(mockDbMetaData); Exception e = new Exception("foo"); - Expect.Call(dbProvider.ExtractError(e)).Return("badsql").Repeat.Once(); - DbException dbException = (DbException) mocks.CreateMock(typeof (DbException)); + A.CallTo(() => dbProvider.ExtractError(e)).Returns("badsql").Once(); + DbException dbException = A.Fake(); + - MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider(); IDictionary targetDbProviders = new Hashtable(); targetDbProviders.Add("db1", dbProvider); @@ -231,9 +226,6 @@ public void CreateOperations() multiDbProvider.TargetDbProviders = targetDbProviders; multiDbProvider.AfterPropertiesSet(); - - mocks.ReplayAll(); - Assert.IsNotNull(multiDbProvider.CreateConnection()); Assert.IsNotNull(multiDbProvider.CreateCommand()); Assert.IsNotNull(multiDbProvider.CreateParameter()); @@ -245,7 +237,6 @@ public void CreateOperations() Assert.AreEqual("badsql", multiDbProvider.ExtractError(e)); Assert.IsTrue(multiDbProvider.IsDataAccessException(dbException)); Assert.IsFalse(multiDbProvider.IsDataAccessException(e)); - mocks.VerifyAll(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.Tests/Data/Common/UserCredentialsDbProviderTests.cs b/test/Spring/Spring.Data.Tests/Data/Common/UserCredentialsDbProviderTests.cs index 1e8c40339..6d4eb7345 100644 --- a/test/Spring/Spring.Data.Tests/Data/Common/UserCredentialsDbProviderTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Common/UserCredentialsDbProviderTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,13 +18,11 @@ #endregion -#region Imports - using System.Data; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Data.Common { @@ -35,28 +33,13 @@ namespace Spring.Data.Common [TestFixture] public class UserCredentialsDbProviderTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void StaticCredentials() { - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - Expect.Call(dbProvider.ConnectionString).Return( - @"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False"); - Expect.Call(connection.ConnectionString = @"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa"); - } - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => dbProvider.ConnectionString).Returns(@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False"); UserCredentialsDbProvider provider = new UserCredentialsDbProvider(); provider.TargetDbProvider = dbProvider; @@ -64,50 +47,39 @@ public void StaticCredentials() provider.Password = "Password=springqa"; Assert.AreEqual(connection, provider.CreateConnection()); - mocks.VerifyAll(); + A.CallToSet(() => connection.ConnectionString) + .WhenArgumentsMatch(x => (string) x[0] == "Data Source=MARKT60\\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa") + .MustHaveHappenedOnceExactly(); } [Test] public void NoCredentials() { - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - } + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); - mocks.ReplayAll(); - UserCredentialsDbProvider provider = new UserCredentialsDbProvider(); provider.TargetDbProvider = dbProvider; Assert.AreEqual(connection, provider.CreateConnection()); - - mocks.VerifyAll(); } [Test] public void ThreadBoundCredentials() { - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection connection = mocks.StrictMock(); - using (mocks.Ordered()) - { - Expect.Call(dbProvider.CreateConnection()).Return(connection); - Expect.Call(dbProvider.ConnectionString).Return( - @"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False"); - Expect.Call(connection.ConnectionString = @"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa"); - } - - mocks.ReplayAll(); + IDbProvider dbProvider = A.Fake(); + IDbConnection connection = A.Fake(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(connection); + A.CallTo(() => dbProvider.ConnectionString).Returns(@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False"); UserCredentialsDbProvider provider = new UserCredentialsDbProvider(); provider.TargetDbProvider = dbProvider; provider.SetCredentialsForCurrentThread("User ID=springqa", "Password=springqa"); Assert.AreEqual(connection, provider.CreateConnection()); - mocks.VerifyAll(); - + A.CallToSet(() => connection.ConnectionString) + .WhenArgumentsMatch(x => (string) x[0] == "Data Source=MARKT60\\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa") + .MustHaveHappenedOnceExactly(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.Tests/Data/Core/ServiceDomainTransactionManagerTests.cs b/test/Spring/Spring.Data.Tests/Data/Core/ServiceDomainTransactionManagerTests.cs index 6b436ecf1..874948894 100644 --- a/test/Spring/Spring.Data.Tests/Data/Core/ServiceDomainTransactionManagerTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Core/ServiceDomainTransactionManagerTests.cs @@ -1,7 +1,5 @@ -#region License - /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +14,17 @@ * limitations under the License. */ -#endregion - -#region Imports - using System; using System.EnterpriseServices; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Data.Support; using Spring.Transaction; using Spring.Transaction.Support; -#endregion - namespace Spring.Data.Core { /// @@ -39,53 +34,33 @@ namespace Spring.Data.Core [TestFixture] public class ServiceDomainTransactionManagerTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void TransactionCommit() { - #region Mock Setup - IServiceDomainAdapter txAdapter = (IServiceDomainAdapter) mocks.CreateMock(typeof (IServiceDomainAdapter)); - using (mocks.Ordered()) - { - Expect.Call(txAdapter.IsInTransaction).Return(false); - SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); - ConfigureServiceConfig(serviceConfig, true); - txAdapter.Enter(serviceConfig); - - //ProcessCommit - status.GlobalRollbackOnly check - Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); - //DoCommit - status.GlobalRollbackOnly check - Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); - - Expect.Call(txAdapter.IsInTransaction).Return(true); - //DoCommit - check to call SetComplete or SetAbort - Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); - txAdapter.SetComplete(); - Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited); + IServiceDomainAdapter txAdapter = A.Fake(); - } - #endregion + A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true).Once(); - mocks.ReplayAll(); + //ProcessCommit - status.GlobalRollbackOnly check + //DoCommit - status.GlobalRollbackOnly check + //DoCommit - check to call SetComplete or SetAbort + A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3); + + A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited).Once(); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); TransactionTemplate tt = new TransactionTemplate(tm); tm.TransactionSynchronization = TransactionSynchronizationState.Always; - tt.Execute(new TransactionDelegate(TransactionCommitMethod)); + tt.Execute(TransactionCommitMethod); Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - mocks.VerifyAll(); - + SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); + ConfigureServiceConfig(serviceConfig, true); + A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappenedOnceExactly(); + A.CallTo(() => txAdapter.SetComplete()).MustHaveHappenedOnceExactly(); } private object TransactionCommitMethod(ITransactionStatus status) @@ -98,23 +73,13 @@ private object TransactionCommitMethod(ITransactionStatus status) [Test] public void TransactionRollback() { - #region Mock Setup - IServiceDomainAdapter txAdapter = (IServiceDomainAdapter)mocks.CreateMock(typeof(IServiceDomainAdapter)); - using (mocks.Ordered()) - { - - Expect.Call(txAdapter.IsInTransaction).Return(false); - SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); - ConfigureServiceConfig(serviceConfig, true); - txAdapter.Enter(serviceConfig); - Expect.Call(txAdapter.IsInTransaction).Return(true); - txAdapter.SetAbort(); - Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited); - } - #endregion + SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); + ConfigureServiceConfig(serviceConfig, standardIsolationAndProp: true); - mocks.ReplayAll(); + IServiceDomainAdapter txAdapter = A.Fake(); + A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true); + A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -136,53 +101,25 @@ public void TransactionRollback() Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - - mocks.VerifyAll(); + A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly(); + A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappenedOnceExactly(); } [Test] public void PropagationRequiresNewWithExistingTransaction() { - #region Mock Setup - IServiceDomainAdapter txAdapter = (IServiceDomainAdapter)mocks.CreateMock(typeof(IServiceDomainAdapter)); - using (mocks.Ordered()) - { + IServiceDomainAdapter txAdapter = A.Fake(); - Expect.Call(txAdapter.IsInTransaction).Return(false); - SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); - ConfigureServiceConfig(serviceConfig, true); - txAdapter.Enter(serviceConfig); + A.CallTo(() => txAdapter.IsInTransaction) + .Returns(false).Once() + .Then.Returns(true).NumberOfTimes(3); + A.CallTo(() => txAdapter.Leave()) + .Returns(TransactionStatus.Aborted).Once() + .Then.Returns(TransactionStatus.Commited).Once(); - Expect.Call(txAdapter.IsInTransaction).Return(true); - // inner tx - ConfigureServiceConfig(serviceConfig, false); - serviceConfig.TransactionOption = TransactionOption.RequiresNew; - serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; - txAdapter.Enter(serviceConfig); - Expect.Call(txAdapter.IsInTransaction).Return(true); - txAdapter.SetAbort(); - Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Aborted); - // innter tx aborted - - - //ProcessCommit - status.GlobalRollbackOnly check - Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); - //DoCommit - status.GlobalRollbackOnly check - Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); - - Expect.Call(txAdapter.IsInTransaction).Return(true); - //DoCommit - check to call SetComplete or SetAbort - Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); - txAdapter.SetComplete(); - - Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited); - - } - #endregion - - mocks.ReplayAll(); + A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -190,10 +127,22 @@ public void PropagationRequiresNewWithExistingTransaction() TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.RequiresNew; tt.Execute(new PropagationRequiresNewWithExistingTransactionCallbackSD(tt)); - mocks.VerifyAll(); + + SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); + ConfigureServiceConfig(serviceConfig, false); + serviceConfig.TransactionOption = TransactionOption.RequiresNew; + serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; + A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappened(); + + ConfigureServiceConfig(serviceConfig, false); + serviceConfig.TransactionOption = TransactionOption.RequiresNew; + serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; + A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappened(); + + A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly(); + A.CallTo(() => txAdapter.SetComplete()).MustHaveHappenedOnceExactly(); } - #region Helper Methods private SimpleServiceConfig ConfigureServiceConfig(SimpleServiceConfig serviceConfig, bool standardIsolationAndProp) { serviceConfig.TransactionDescription = null; @@ -206,14 +155,11 @@ private SimpleServiceConfig ConfigureServiceConfig(SimpleServiceConfig serviceCo serviceConfig.TransactionOption = TransactionOption.Required; serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; } - return serviceConfig; + return serviceConfig; } - #endregion - #region Supporting class for TransactionRollback test - internal class TransactionRollbackTxCallback : ITransactionCallback { private Exception exception; @@ -232,9 +178,6 @@ public object DoInTransaction(ITransactionStatus status) } } - #endregion - - #region Supporting class for PropagationRequiresNewWithExistingTransactionCallback test internal class PropagationRequiresNewWithExistingTransactionCallbackSD : ITransactionCallback { private TransactionTemplate tt; @@ -264,12 +207,8 @@ private object TransactionMethod(ITransactionStatus status) Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); status.SetRollbackOnly(); - return null; + return null; } } - - #endregion } - - -} +} \ No newline at end of file diff --git a/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerIntegrationTests.cs b/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerIntegrationTests.cs index a5f50dc8d..3435a9db8 100644 --- a/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerIntegrationTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerIntegrationTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,15 +18,13 @@ #endregion -#region Imports +using FakeItEasy; using NUnit.Framework; -using Rhino.Mocks; + using Spring.Transaction; using Spring.Transaction.Support; -#endregion - namespace Spring.Data.Core { /// @@ -37,13 +35,6 @@ namespace Spring.Data.Core [TestFixture] public class TxScopeTransactionManagerIntegrationTests { - private MockRepository mocks; - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [TearDown] public void TearDown() { @@ -53,7 +44,6 @@ public void TearDown() Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.AreEqual(System.Data.IsolationLevel.Unspecified, TransactionSynchronizationManager.CurrentTransactionIsolationLevel); Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive); - } [Test] @@ -80,7 +70,7 @@ public object CommitTxDelegate(ITransactionStatus status) { Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - + return null; } @@ -97,12 +87,11 @@ public void TransactionInformation() public object TransactionInformationTxDelegate(ITransactionStatus status) { - Assert.AreEqual(System.Transactions.IsolationLevel.ReadUncommitted, - System.Transactions.Transaction.Current.IsolationLevel); + System.Transactions.Transaction.Current.IsolationLevel); Assert.AreEqual(System.Data.IsolationLevel.ReadUncommitted, - TransactionSynchronizationManager.CurrentTransactionIsolationLevel); + TransactionSynchronizationManager.CurrentTransactionIsolationLevel); return null; } @@ -110,14 +99,7 @@ public object TransactionInformationTxDelegate(ITransactionStatus status) [Test] public void Rollback() { - ITransactionSynchronization sync = - (ITransactionSynchronization) mocks.DynamicMock(typeof (ITransactionSynchronization)); - sync.BeforeCompletion(); - LastCall.On(sync).Repeat.Once(); - sync.AfterCompletion(TransactionSynchronizationStatus.Rolledback); - LastCall.On(sync).Repeat.Once(); - mocks.ReplayAll(); - + ITransactionSynchronization sync = A.Fake(); TxScopeTransactionManager tm = new TxScopeTransactionManager(); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -130,20 +112,18 @@ public void Rollback() Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); tt.Execute(status => - { - Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); - TransactionSynchronizationManager.RegisterSynchronization(sync); - Assert.AreEqual("txName", TransactionSynchronizationManager.CurrentTransactionName); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - status.SetRollbackOnly(); - return null; - } + { + Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); + TransactionSynchronizationManager.RegisterSynchronization(sync); + Assert.AreEqual("txName", TransactionSynchronizationManager.CurrentTransactionName); + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + status.SetRollbackOnly(); + return null; + } ); - mocks.VerifyAll(); - + A.CallTo(() => sync.BeforeCompletion()).MustHaveHappenedOnceExactly(); + A.CallTo(() => sync.AfterCompletion(TransactionSynchronizationStatus.Rolledback)).MustHaveHappenedOnceExactly(); } - - } -} +} \ No newline at end of file diff --git a/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerTests.cs b/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerTests.cs index c1151c9df..949e70ec2 100644 --- a/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Core/TxScopeTransactionManagerTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,91 +18,68 @@ #endregion -#region Imports - using System; using System.Transactions; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Data.Support; using Spring.Transaction; using Spring.Transaction.Support; -#endregion - namespace Spring.Data.Core { /// - /// This calss contains tests for + /// This calss contains tests for /// /// Mark Pollack [TestFixture] public class TxScopeTransactionManagerTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } [Test] - public void TransactionCommit() { - ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter) mocks.CreateMock(typeof(ITransactionScopeAdapter)); + ITransactionScopeAdapter txAdapter = A.Fake(); + A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false); - using (mocks.Ordered()) - { - Expect.Call(txAdapter.IsExistingTransaction).Return(false); - TransactionOptions txOptions = new TransactionOptions(); - txOptions.IsolationLevel = IsolationLevel.ReadCommitted; - txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None); - - Expect.Call(txAdapter.RollbackOnly).Return(false); - txAdapter.Complete(); - txAdapter.Dispose(); - } - mocks.ReplayAll(); + A.CallTo(() => txAdapter.RollbackOnly).Returns(false); TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); tt.Execute(status => - { - Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - return null; - }); + { + Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + return null; + }); Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - - mocks.VerifyAll(); - + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + TransactionOptions txOptions = new TransactionOptions(); + txOptions.IsolationLevel = IsolationLevel.ReadCommitted; + txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None); + txAdapter.Complete(); + txAdapter.Dispose(); } [Test] public void TransactionRollback() { - ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter)mocks.CreateMock(typeof(ITransactionScopeAdapter)); + ITransactionScopeAdapter txAdapter = A.Fake(); - using (mocks.Ordered()) - { - Expect.Call(txAdapter.IsExistingTransaction).Return(false); - TransactionOptions txOptions = new TransactionOptions(); - txOptions.IsolationLevel = IsolationLevel.ReadCommitted; - txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None); - txAdapter.Dispose(); - } - mocks.ReplayAll(); + A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false); + TransactionOptions txOptions = new TransactionOptions(); + txOptions.IsolationLevel = IsolationLevel.ReadCommitted; TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; - + TransactionTemplate tt = new TransactionTemplate(tm); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); @@ -111,13 +88,13 @@ public void TransactionRollback() try { tt.Execute(status => - { - Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); - if (ex != null) throw ex; - return null; - }); + { + Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); + if (ex != null) throw ex; + return null; + }); Assert.Fail("Should have thrown exception"); } catch (ArgumentException e) @@ -126,36 +103,24 @@ public void TransactionRollback() } Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); - - - mocks.VerifyAll(); + A.CallTo(() => txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None)).MustHaveHappenedOnceExactly(); + A.CallTo(() => txAdapter.Dispose()).MustHaveHappenedOnceExactly(); } [Test] public void PropagationRequiresNewWithExistingTransaction() { + ITransactionScopeAdapter txAdapter = A.Fake(); + A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false).Once(); - ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter)mocks.CreateMock(typeof(ITransactionScopeAdapter)); + TransactionOptions txOptions = new TransactionOptions(); + txOptions.IsolationLevel = IsolationLevel.ReadCommitted; - using (mocks.Ordered()) - { - Expect.Call(txAdapter.IsExistingTransaction).Return(false); - TransactionOptions txOptions = new TransactionOptions(); - txOptions.IsolationLevel = IsolationLevel.ReadCommitted; - txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None); - - //inner tx actions - Expect.Call(txAdapter.IsExistingTransaction).Return(true); - txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None); - txAdapter.Dispose(); - //end inner tx actions - - Expect.Call(txAdapter.RollbackOnly).Return(false); - txAdapter.Complete(); - txAdapter.Dispose(); - - } - mocks.ReplayAll(); + //inner tx actions + A.CallTo(() => txAdapter.IsExistingTransaction).Returns(true).Once(); + //end inner tx actions + + A.CallTo(() => txAdapter.RollbackOnly).Returns(false); TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; @@ -163,30 +128,32 @@ public void PropagationRequiresNewWithExistingTransaction() TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.RequiresNew; tt.Execute(status => - { - Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); - Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active"); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); - - tt.Execute(status2 => - { - Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active"); - Assert.IsTrue(status2.IsNewTransaction, "Is new transaction"); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); - status2.SetRollbackOnly(); - return null; - }); - - - Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); - Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); - Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); - return null; - }); - - mocks.VerifyAll(); + { + Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); + Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active"); + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); + + tt.Execute(status2 => + { + Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active"); + Assert.IsTrue(status2.IsNewTransaction, "Is new transaction"); + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); + status2.SetRollbackOnly(); + return null; + }); + + + Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); + Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); + Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); + return null; + }); + + A.CallTo(() => txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None)).MustHaveHappenedTwiceExactly(); + A.CallTo(() => txAdapter.Dispose()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => txAdapter.Complete()).MustHaveHappenedOnceExactly(); } } } diff --git a/test/Spring/Spring.Data.Tests/Data/Objects/AbstractAdoQueryTests.cs b/test/Spring/Spring.Data.Tests/Data/Objects/AbstractAdoQueryTests.cs index 6592ceded..3ac2445ad 100644 --- a/test/Spring/Spring.Data.Tests/Data/Objects/AbstractAdoQueryTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Objects/AbstractAdoQueryTests.cs @@ -19,7 +19,9 @@ #endregion using System.Data; -using Rhino.Mocks; + +using FakeItEasy; + using Spring.Data.Common; namespace Spring.Data.Objects @@ -34,26 +36,26 @@ public abstract class AbstractAdoQueryTests public void SetUpMocks() { - provider = MockRepository.GenerateMock(); - IDbConnection connection = MockRepository.GenerateMock(); + provider = A.Fake(); + IDbConnection connection = A.Fake(); - provider.Stub(x => x.CreateConnection()).Return(connection).Repeat.Once(); + A.CallTo(() => provider.CreateConnection()).Returns(connection).Once(); // Creating a query (setting DbProvider property) // will call new DbParameters(IDbProvider), which is a real pain to mock. // to store the declared parameters. - command = MockRepository.GenerateMock(); + command = A.Fake(); //This IDbCommand is used as a container for the underlying parameter collection. - provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once(); + A.CallTo(() => provider.CreateCommand()).Returns(command).Once(); //Create a real instance of IDbParameters to stored the declared parameters IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); IDbParameters dbParameters = new DbParameters(realDbProvider); //Pass real instance into mock instance. - command.Stub(x => x.Parameters).Return(dbParameters.DataParameterCollection).Repeat.Once(); - provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once(); + A.CallTo(() => command.Parameters).Returns(dbParameters.DataParameterCollection).Once(); + A.CallTo(() => provider.CreateCommand()).Returns(command).Once(); // done with init of DbParameters mock/stubbing } diff --git a/test/Spring/Spring.Data.Tests/Data/Objects/AdoQueryTests.cs b/test/Spring/Spring.Data.Tests/Data/Objects/AdoQueryTests.cs index da5c76f91..6abb0c753 100644 --- a/test/Spring/Spring.Data.Tests/Data/Objects/AdoQueryTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Objects/AdoQueryTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,14 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. - * + * Copyright © 2002-2011 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -44,9 +44,9 @@ using System.Data; using System.Data.SqlClient; -using NUnit.Framework; +using FakeItEasy; -using Rhino.Mocks; +using NUnit.Framework; using Spring.Dao; using Spring.Data.Common; @@ -75,12 +75,11 @@ public void Setup() [Test] public void MappingAdoQueryWithContextWithoutParams() { - IDataReader reader = MockRepository.GenerateMock(); - reader.Stub(x => x.Read()).Return(true).Repeat.Once(); - reader.Stub(x => x.GetInt32(0)).Return(1).Repeat.Once(); - reader.Stub(x => x.Read()).Return(false).Repeat.Once(); + IDataReader reader = A.Fake(); + A.CallTo(() => reader.Read()).Returns(true).Once().Then.Returns(false); + A.CallTo(() => reader.GetInt32(0)).Returns(1).Once(); - command.Stub(x => x.ExecuteReader()).Return(reader); + A.CallTo(() => command.ExecuteReader()).Returns(reader); IntMappingQueryWithContext queryWithNoContext = new IntMappingQueryWithContext(provider); queryWithNoContext.Compile(); @@ -95,13 +94,10 @@ public void MappingAdoQueryWithContextWithoutParams() [Test] public void QueryWithoutEnoughParams() { - SqlParameter sqlParameter1 = new SqlParameter(); - command.Stub(x => x.CreateParameter()).Return(sqlParameter1).Repeat.Once(); - provider.Stub(x => x.CreateParameterNameForCollection(COLUMN_NAMES[0])).Return("@" + COLUMN_NAMES[0]).Repeat.Once(); + A.CallTo(() => command.CreateParameter()).ReturnsLazily(() => new SqlParameter()); - SqlParameter sqlParameter2 = new SqlParameter(); - command.Stub(x => x.CreateParameter()).Return(sqlParameter2); - provider.Stub(x => x.CreateParameterNameForCollection(COLUMN_NAMES[1])).Return("@" + COLUMN_NAMES[1]); + A.CallTo(() => provider.CreateParameterNameForCollection(COLUMN_NAMES[0])).Returns("@" + COLUMN_NAMES[0]).Once(); + A.CallTo(() => provider.CreateParameterNameForCollection(COLUMN_NAMES[1])).Returns("@" + COLUMN_NAMES[1]); IntMappingAdoQuery query = new IntMappingAdoQuery(); query.DbProvider = provider; diff --git a/test/Spring/Spring.Data.Tests/Data/Objects/StoredProcedureTests.cs b/test/Spring/Spring.Data.Tests/Data/Objects/StoredProcedureTests.cs index 4571d2334..e340d0091 100644 --- a/test/Spring/Spring.Data.Tests/Data/Objects/StoredProcedureTests.cs +++ b/test/Spring/Spring.Data.Tests/Data/Objects/StoredProcedureTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,14 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. - * + * Copyright © 2002-2011 the original author or authors. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,19 +38,15 @@ #endregion -#region Imports - using System.Data; using System.Data.SqlClient; -using NUnit.Framework; +using FakeItEasy; -using Rhino.Mocks; +using NUnit.Framework; using Spring.Data.Common; -#endregion - namespace Spring.Data.Objects { /// @@ -70,15 +66,14 @@ public void Setup() public void NullArg() { SqlParameter sqlParameter1 = new SqlParameter(); - command.Stub(x => x.CreateParameter()).Return(sqlParameter1); - provider.Stub(x => x.CreateParameterNameForCollection("ptest")).Return("@ptest"); + A.CallTo(() => command.CreateParameter()).Returns(sqlParameter1); + A.CallTo(() => provider.CreateParameterNameForCollection("ptest")).Returns("@ptest"); //Create a real instance of IDbParameters to store the executable parameters //IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); //IDbParameters dbParameters = new DbParameters(realDbProvider); - IDataParameterCollection dbParamCollection = new SqlCommand().Parameters; //provide the same instance to another call to extract output params - command.Stub(x => x.Parameters).Return(dbParamCollection).Repeat.Twice(); + A.CallTo(() => command.Parameters).ReturnsLazily(() => new SqlCommand().Parameters).Twice(); NullArg na = new NullArg(provider); na.Execute(null); diff --git a/test/Spring/Spring.Data.Tests/Spring.Data.Tests.2010.csproj b/test/Spring/Spring.Data.Tests/Spring.Data.Tests.2010.csproj index 788762bdb..e0e5030d8 100644 --- a/test/Spring/Spring.Data.Tests/Spring.Data.Tests.2010.csproj +++ b/test/Spring/Spring.Data.Tests/Spring.Data.Tests.2010.csproj @@ -10,10 +10,11 @@ + + - diff --git a/test/Spring/Spring.Data.Tests/Transaction/Interceptor/AbstractTransactionAspectTests.cs b/test/Spring/Spring.Data.Tests/Transaction/Interceptor/AbstractTransactionAspectTests.cs index 728ca38e6..21a73e8a2 100644 --- a/test/Spring/Spring.Data.Tests/Transaction/Interceptor/AbstractTransactionAspectTests.cs +++ b/test/Spring/Spring.Data.Tests/Transaction/Interceptor/AbstractTransactionAspectTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,17 +18,16 @@ #endregion -#region Imports - using System; using System.Reflection; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Data; using Spring.Objects; -#endregion - namespace Spring.Transaction.Interceptor { /// @@ -38,44 +37,31 @@ namespace Spring.Transaction.Interceptor [TestFixture] public abstract class AbstractTransactionAspectTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void CopyAttributes() { - - IPlatformTransactionManager ptm = PlatformTxManagerForNewTransaction(); + IPlatformTransactionManager ptm = A.Fake(); AttributesTransactionAttributeSource tas = new AttributesTransactionAttributeSource(); TestObjectMgr to = new TestObjectMgr(); - ITestObjectMgr ito = (ITestObjectMgr)Advised(to, ptm, tas); + ITestObjectMgr ito = (ITestObjectMgr) Advised(to, ptm, tas); ito.DeleteTwoTestObjects("foo", "bar"); - } [Test] public void CannotCommitTransaction() { ITransactionAttribute txatt = new DefaultTransactionAttribute(); - MethodInfo m = typeof (ITestObject).GetMethod("GetDescription"); + MethodInfo m = typeof(ITestObject).GetMethod("GetDescription"); MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource(); tas.AddTransactionalMethod(m, txatt); + IPlatformTransactionManager ptm = A.Fake(); + ITransactionStatus status = A.Fake(); - IPlatformTransactionManager ptm = PlatformTxManagerForNewTransaction(); - - ITransactionStatus status = TransactionStatusForNewTransaction(); - Expect.On(ptm).Call(ptm.GetTransaction(txatt)).Return(status); + A.CallTo(() => ptm.GetTransaction(txatt)).Returns(status); UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null); - ptm.Commit(status); - LastCall.On(ptm).Throw(ex); - mocks.ReplayAll(); + A.CallTo(() => ptm.Commit(status)).Throws(ex); TestObject to = new TestObject(); ITestObject ito = (ITestObject) Advised(to, ptm, tas); @@ -84,20 +70,11 @@ public void CannotCommitTransaction() { ito.GetDescription(); Assert.Fail("Shouldn't have succeeded"); - } catch (UnexpectedRollbackException thrown) + } + catch (UnexpectedRollbackException thrown) { Assert.IsTrue(thrown == ex); } - - mocks.VerifyAll(); - - - - } - - private IPlatformTransactionManager PlatformTxManagerForNewTransaction() - { - return (IPlatformTransactionManager) mocks.DynamicMock(typeof(IPlatformTransactionManager)); } @@ -110,25 +87,19 @@ public void ProgrammaticRollback() MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource(); tas.AddTransactionalMethod(m, txatt); - ITransactionStatus status = TransactionStatusForNewTransaction(); + ITransactionStatus status = A.Fake(); - IPlatformTransactionManager ptm = PlatformTxManagerForNewTransaction(); + IPlatformTransactionManager ptm = A.Fake(); - Expect.Call(ptm.GetTransaction(txatt)).Return(status).Repeat.Once(); - ptm.Commit(status); - LastCall.On(ptm).Repeat.Once(); + A.CallTo(() => ptm.GetTransaction(txatt)).Returns(status).Once(); - mocks.ReplayAll(); - RollbackTestObject to = new RollbackTestObject(); ITestObject ito = (ITestObject) Advised(to, ptm, tas); Assert.AreEqual("test description", ito.GetDescription()); - mocks.VerifyAll(); - - + A.CallTo(() => ptm.Commit(status)).MustHaveHappenedOnceExactly(); } [Test] @@ -160,37 +131,21 @@ private void DoTestRollbackOnException(Exception exception, bool shouldRollback, ITransactionAttribute txatt = new ConfigurableTransactionAttribute(shouldRollback); - MethodInfo mi = typeof (ITestObject).GetMethod("Exceptional"); + MethodInfo mi = typeof(ITestObject).GetMethod("Exceptional"); MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource(); tas.AddTransactionalMethod(mi, txatt); - ITransactionStatus status = TransactionStatusForNewTransaction(); + ITransactionStatus status = A.Fake(); - IPlatformTransactionManager ptm = - (IPlatformTransactionManager) mocks.DynamicMock(typeof (IPlatformTransactionManager)); + IPlatformTransactionManager ptm = A.Fake(); + A.CallTo(() => ptm.GetTransaction(txatt)).Returns(status); - - Expect.On(ptm).Call(ptm.GetTransaction(txatt)).Return(status); - - if (shouldRollback) - { - ptm.Rollback(status); - } - else - { - ptm.Commit(status); - } TransactionSystemException tex = new TransactionSystemException("system exception"); if (rollbackException) { - LastCall.On(ptm).Throw(tex).Repeat.Once(); + A.CallTo(() => ptm.Rollback(A._)).Throws(tex); } - else - { - LastCall.On(ptm).Repeat.Once(); - } - mocks.ReplayAll(); TestObject to = new TestObject(); ITestObject ito = (ITestObject) Advised(to, ptm, tas); @@ -199,9 +154,10 @@ private void DoTestRollbackOnException(Exception exception, bool shouldRollback, { ito.Exceptional(exception); Assert.Fail("Should have thrown exception"); - } catch (Exception e) + } + catch (Exception e) { - if (rollbackException) + if (rollbackException && shouldRollback) { Assert.AreEqual(tex, e); } @@ -211,17 +167,18 @@ private void DoTestRollbackOnException(Exception exception, bool shouldRollback, } } - mocks.VerifyAll(); - - } - - private ITransactionStatus TransactionStatusForNewTransaction() - { - return (ITransactionStatus) mocks.DynamicMock(typeof (ITransactionStatus)); + if (shouldRollback) + { + A.CallTo(() => ptm.Rollback(status)).MustHaveHappenedOnceExactly(); + } + else + { + A.CallTo(() => ptm.Commit(status)).MustHaveHappenedOnceExactly(); + } } protected abstract object Advised(object target, IPlatformTransactionManager ptm, - ITransactionAttributeSource tas); + ITransactionAttributeSource tas); } internal class RollbackTestObject : TestObject @@ -232,12 +189,12 @@ public override string GetDescription() txStatus.SetRollbackOnly(); return "test description"; } - } internal class ConfigurableTransactionAttribute : DefaultTransactionAttribute { private bool shouldRollback; + public ConfigurableTransactionAttribute(bool shouldRollback) { this.shouldRollback = shouldRollback; diff --git a/test/Spring/Spring.Data.Tests/Transaction/Support/AbstractPlatformTransactionManagerTests.cs b/test/Spring/Spring.Data.Tests/Transaction/Support/AbstractPlatformTransactionManagerTests.cs index f6bfd0db5..3ebe68ac2 100644 --- a/test/Spring/Spring.Data.Tests/Transaction/Support/AbstractPlatformTransactionManagerTests.cs +++ b/test/Spring/Spring.Data.Tests/Transaction/Support/AbstractPlatformTransactionManagerTests.cs @@ -1,5 +1,6 @@ +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; namespace Spring.Transaction.Support { @@ -144,7 +145,7 @@ public void NestedTransactionWithSavepoint() MockTxnDefinition def = new MockTxnDefinition(); def.PropagationBehavior = TransactionPropagation.Nested; def.ReadOnly = false; - ISavepointManager saveMgr = MockRepository.GenerateMock(); + ISavepointManager saveMgr = A.Fake(); _mockTxnMgr.SetTransaction(saveMgr); _mockTxnMgr.Savepoints = true; _mockTxnMgr.NestedTransactionsAllowed = true; diff --git a/test/Spring/Spring.Data.Tests/Transaction/Support/DefaultTransactionStatusTests.cs b/test/Spring/Spring.Data.Tests/Transaction/Support/DefaultTransactionStatusTests.cs index b8be93a69..cb38f62d9 100644 --- a/test/Spring/Spring.Data.Tests/Transaction/Support/DefaultTransactionStatusTests.cs +++ b/test/Spring/Spring.Data.Tests/Transaction/Support/DefaultTransactionStatusTests.cs @@ -1,5 +1,6 @@ +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; namespace Spring.Transaction.Support { @@ -9,7 +10,7 @@ public class DefaultTransactionStatusTests [Test] public void DefaultConstructorTests() { - ISmartTransactionObject txn = MockRepository.GenerateMock(); + ISmartTransactionObject txn = A.Fake(); DefaultTransactionStatus stat = new DefaultTransactionStatus(txn, true, false, false, true, new object()); Assert.IsNotNull(stat.Transaction); @@ -20,14 +21,12 @@ public void DefaultConstructorTests() Assert.IsTrue(! stat.RollbackOnly); stat.SetRollbackOnly(); Assert.IsTrue(stat.RollbackOnly); - - txn.AssertWasCalled(x => x.RollbackOnly, constraints => constraints.Repeat.Once()); } [Test] public void CreateSavepointException() { - ISmartTransactionObject transaction = MockRepository.GenerateMock(); + ISmartTransactionObject transaction = A.Fake(); DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object()); Assert.Throws(() => stat.CreateSavepoint("mySavePoint")); } @@ -35,7 +34,7 @@ public void CreateSavepointException() [Test] public void RollbackSavepointException() { - ISmartTransactionObject transaction = MockRepository.GenerateMock(); + ISmartTransactionObject transaction = A.Fake(); DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object()); Assert.Throws(() => stat.RollbackToSavepoint(null)); } @@ -43,7 +42,7 @@ public void RollbackSavepointException() [Test] public void ReleaseSavepointException() { - ISmartTransactionObject transaction = MockRepository.GenerateMock(); + ISmartTransactionObject transaction = A.Fake(); DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object()); Assert.Throws(() => stat.ReleaseSavepoint(null)); } @@ -51,7 +50,7 @@ public void ReleaseSavepointException() [Test] public void CreateSaveAndHoldValidSavepoint() { - ISavepointManager saveMgr = MockRepository.GenerateMock(); + ISavepointManager saveMgr = A.Fake(); DefaultTransactionStatus status = new DefaultTransactionStatus(saveMgr, true, false, false, true, new object()); status.CreateAndHoldSavepoint("savepoint"); Assert.IsTrue(status.HasSavepoint); @@ -61,7 +60,7 @@ public void CreateSaveAndHoldValidSavepoint() [Test] public void RollbackHeldSavepointException() { - ISmartTransactionObject transaction = MockRepository.GenerateMock(); + ISmartTransactionObject transaction = A.Fake(); DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object()); Assert.Throws(() => stat.RollbackToHeldSavepoint()); } @@ -69,7 +68,7 @@ public void RollbackHeldSavepointException() [Test] public void RollbackHeldSavepointSuccess() { - ISavepointManager saveMgr = MockRepository.GenerateMock(); + ISavepointManager saveMgr = A.Fake(); string savepoint = "savepoint"; DefaultTransactionStatus status = new DefaultTransactionStatus(saveMgr, true, false, false, true, new object()); status.CreateAndHoldSavepoint(savepoint); @@ -77,13 +76,13 @@ public void RollbackHeldSavepointSuccess() Assert.AreEqual(savepoint, status.Savepoint); status.RollbackToHeldSavepoint(); - saveMgr.AssertWasCalled(x => x.RollbackToSavepoint(savepoint)); + A.CallTo(() => saveMgr.RollbackToSavepoint(savepoint)).MustHaveHappened(); } [Test] public void ReleaseHeldSavepointException() { - ISmartTransactionObject transaction = MockRepository.GenerateMock(); + ISmartTransactionObject transaction = A.Fake(); DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object()); Assert.Throws(() => stat.ReleaseHeldSavepoint()); } @@ -91,7 +90,7 @@ public void ReleaseHeldSavepointException() [Test] public void ReleaseHeldSavepointSuccess() { - ISavepointManager saveMgr = MockRepository.GenerateMock(); + ISavepointManager saveMgr = A.Fake(); string savepoint = "savepoint"; DefaultTransactionStatus status = new DefaultTransactionStatus(saveMgr, true, false, false, true, new object()); status.CreateAndHoldSavepoint(savepoint); @@ -99,8 +98,8 @@ public void ReleaseHeldSavepointSuccess() Assert.AreEqual(savepoint, status.Savepoint); status.ReleaseHeldSavepoint(); - saveMgr.AssertWasCalled(x => x.CreateSavepoint(savepoint)); - saveMgr.AssertWasCalled(x => x.ReleaseSavepoint(savepoint)); + A.CallTo(() => saveMgr.CreateSavepoint(savepoint)).MustHaveHappened(); + A.CallTo(() => saveMgr.ReleaseSavepoint(savepoint)).MustHaveHappened(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionSynchronizationManagerTests.cs b/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionSynchronizationManagerTests.cs index 2a5b0aa96..72d2be3e5 100644 --- a/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionSynchronizationManagerTests.cs +++ b/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionSynchronizationManagerTests.cs @@ -1,9 +1,9 @@ using System; using System.Collections; -using NUnit.Framework; +using FakeItEasy; -using Rhino.Mocks; +using NUnit.Framework; using Spring.Core; using Spring.Util; @@ -54,7 +54,7 @@ public void SynchronizationsClearInvalid() [Test] public void RegisterSyncsInvalid() { - Assert.Throws(() => TransactionSynchronizationManager.RegisterSynchronization(MockRepository.GenerateMock())); + Assert.Throws(() => TransactionSynchronizationManager.RegisterSynchronization(A.Fake())); } [Test] @@ -63,7 +63,7 @@ public void SynchronizationsLifeCycle() TransactionSynchronizationManager.InitSynchronization(); IList syncs = TransactionSynchronizationManager.Synchronizations; Assert.AreEqual(0, syncs.Count); - TransactionSynchronizationManager.RegisterSynchronization(MockRepository.GenerateMock()); + TransactionSynchronizationManager.RegisterSynchronization(A.Fake()); syncs = TransactionSynchronizationManager.Synchronizations; Assert.AreEqual(1, syncs.Count); TransactionSynchronizationManager.ClearSynchronization(); diff --git a/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionTemplateTests.cs b/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionTemplateTests.cs index c7d525aaf..b720980c9 100644 --- a/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionTemplateTests.cs +++ b/test/Spring/Spring.Data.Tests/Transaction/Support/TransactionTemplateTests.cs @@ -1,6 +1,8 @@ using System; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; namespace Spring.Transaction.Support { @@ -18,59 +20,60 @@ public void NoTxnMgr() public void TxnMgr() { TransactionTemplate temp = new TransactionTemplate(); - temp.PlatformTransactionManager = MockRepository.GenerateMock(); + temp.PlatformTransactionManager = A.Fake(); temp.AfterPropertiesSet(); } [Test] public void ExecuteException() { - IPlatformTransactionManager mock = MockRepository.GenerateMock(); + IPlatformTransactionManager mock = A.Fake(); TransactionTemplate temp = new TransactionTemplate(mock); try { - temp.Execute(new TransactionDelegate(DummyExceptionMethod)); + temp.Execute(DummyExceptionMethod); } catch { } - mock.AssertWasCalled(x => x.GetTransaction(Arg.Is.Anything), constraints => constraints.Repeat.Once()); - mock.AssertWasCalled(x => x.Rollback(Arg.Is.Anything), constraints => constraints.Repeat.Once()); + A.CallTo(() => mock.GetTransaction(A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => mock.Rollback(A._)).MustHaveHappenedOnceExactly(); } [Test] public void ExecuteExceptionRollbackException() { - IPlatformTransactionManager mock = MockRepository.GenerateMock(); - mock.Stub(x => x.Rollback(Arg.Is.Anything)).Throw(new Exception("Rollback")); + IPlatformTransactionManager mock = A.Fake(); + A.CallTo(() => mock.Rollback(A._)).Throws(new Exception("Rollback")); TransactionTemplate temp = new TransactionTemplate(mock); try { - temp.Execute(new TransactionDelegate(DummyExceptionMethod)); + temp.Execute(DummyExceptionMethod); } catch { } - mock.AssertWasCalled(x => x.GetTransaction(Arg.Is.Anything), constraints => constraints.Repeat.Once()); - mock.AssertWasCalled(x => x.Rollback(Arg.Is.Anything), constraints => constraints.Repeat.Once()); + A.CallTo(() => mock.GetTransaction(A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => mock.Rollback(A._)).MustHaveHappenedOnceExactly(); } [Test] public void NullResult() { - IPlatformTransactionManager mock = MockRepository.GenerateMock(); + IPlatformTransactionManager mock = A.Fake(); + A.CallTo(() => mock.GetTransaction(A._)).Returns(null); TransactionTemplate temp = new TransactionTemplate(mock); temp.AfterPropertiesSet(); Assert.AreEqual(mock, temp.PlatformTransactionManager); - Assert.IsNull(temp.Execute(new TransactionDelegate(DummyTransactionMethod))); + Assert.IsNull(temp.Execute(DummyTransactionMethod)); - mock.AssertWasCalled(x => x.GetTransaction(Arg.Is.Anything), constraints => constraints.Repeat.Once()); - mock.AssertWasCalled(x => x.Commit(Arg.Is.Anything), constraints => constraints.Repeat.Once()); + A.CallTo(() => mock.GetTransaction(A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => mock.Commit(A._)).MustHaveHappenedOnceExactly(); } public object DummyTransactionMethod(ITransactionStatus status) diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Config/NmsNamespaceHandlerTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Config/NmsNamespaceHandlerTests.cs index 3d37783c4..11e0b78ff 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Config/NmsNamespaceHandlerTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Config/NmsNamespaceHandlerTests.cs @@ -22,8 +22,10 @@ using System.Collections.Generic; using Apache.NMS; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Context; using Spring.Context.Support; using Spring.Messaging.Nms.Core; @@ -45,23 +47,16 @@ namespace Spring.Messaging.Nms.Config [TestFixture] public class NmsNamespaceHandlerTests { - private static string DEFAULT_CONNECTION_FACTORY = "ConnectionFactory"; - private static string EXPLICIT_CONNECTION_FACTORY = "testConnectionFactory"; - - private IApplicationContext ctx; - private MockRepository mocks; - [SetUp] public void Setup() { // WELLKNOWN //NamespaceParserRegistry.RegisterParser(typeof(NmsNamespaceParser)); ctx = new XmlApplicationContext(ReadOnlyXmlTestResource.GetFilePath("NmsNamespaceHandlerTests.xml", GetType())); - mocks = new MockRepository(); } [Test] @@ -117,37 +112,29 @@ public void Listeners() Assert.IsNull(testObject3.Message); - ITextMessage message1 = mocks.StrictMock(); - Expect.Call(message1.Text).Return("Test1"); - mocks.Replay(message1); + ITextMessage message1 = A.Fake(); + A.CallTo(() => message1.Text).Returns("Test1"); IMessageListener listener1 = GetListener("listener1"); listener1.OnMessage(message1); Assert.AreEqual("Test1", testObject1.Name); - mocks.Verify(message1); - ITextMessage message2 = mocks.StrictMock(); - Expect.Call(message2.Text).Return("Test1"); - mocks.Replay(message2); + ITextMessage message2 = A.Fake(); + A.CallTo(() => message2.Text).Returns("Test1"); IMessageListener listener2 = GetListener("listener2"); listener2.OnMessage(message2); - mocks.Verify(message2); + A.CallTo(() => message2.Text).MustHaveHappened(); + ITextMessage message3 = A.Fake(); - ITextMessage message3 = mocks.StrictMock(); - mocks.Replay(message3); - //Default naming strategy is to use full type name + # + number string className = typeof(SimpleMessageListenerContainer).FullName; string targetName = className + ObjectDefinitionReaderUtils.GENERATED_OBJECT_NAME_SEPARATOR + "0"; IMessageListener listener3 = GetListener(targetName); listener3.OnMessage(message3); Assert.AreSame(message3, testObject3.Message); - mocks.Verify(message3); - - } private IMessageListener GetListener(string containerObjectName) diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachingConnectionFactoryTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachingConnectionFactoryTests.cs index b54f69e4c..c6fe23272 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachingConnectionFactoryTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/CachingConnectionFactoryTests.cs @@ -22,8 +22,10 @@ using Apache.NMS; using Apache.NMS.ActiveMQ.Commands; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; #endregion @@ -36,21 +38,11 @@ namespace Spring.Messaging.Nms.Connections [TestFixture] public class CachingConnectionFactoryTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void CachedSession() { IConnectionFactory connectionFactory = CreateConnectionFactory(); - mocks.ReplayAll(); - CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(); cachingConnectionFactory.TargetConnectionFactory = connectionFactory; @@ -75,8 +67,6 @@ public void CachedSession() Assert.AreEqual(1, testSession.CreatedCount); Assert.AreEqual(0, testSession.CloseCount); - - mocks.VerifyAll(); //don't explicitly call close on } @@ -95,8 +85,6 @@ public void CachedSessionTwoRequests() { IConnectionFactory connectionFactory = CreateConnectionFactory(); - mocks.ReplayAll(); - CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(); cachingConnectionFactory.TargetConnectionFactory = connectionFactory; IConnection con1 = cachingConnectionFactory.CreateConnection(); @@ -125,10 +113,6 @@ public void CachedSessionTwoRequests() Assert.AreSame(session1, session3); Assert.AreEqual(1, testSession1.CreatedCount); Assert.AreEqual(0, testSession1.CloseCount); - - mocks.VerifyAll(); - - } /// @@ -141,9 +125,6 @@ public void CachedMessageProducer() { IConnectionFactory connectionFactory = CreateConnectionFactory(); - mocks.ReplayAll(); - - CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(); cachingConnectionFactory.TargetConnectionFactory = connectionFactory; IConnection con1 = cachingConnectionFactory.CreateConnection(); @@ -159,8 +140,6 @@ public void CachedMessageProducer() TestMessageProducer tmpB = GetTestMessageProducer(producerB); Assert.AreSame(tmpA, tmpB); - - mocks.VerifyAll(); } [Test] @@ -168,9 +147,6 @@ public void CachedMessageProducerTwoRequests() { IConnectionFactory connectionFactory = CreateConnectionFactory(); - mocks.ReplayAll(); - - CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(); cachingConnectionFactory.TargetConnectionFactory = connectionFactory; IConnection con1 = cachingConnectionFactory.CreateConnection(); @@ -193,11 +169,8 @@ public void CachedMessageProducerTwoRequests() TestMessageProducer tmpC = GetTestMessageProducer(producerC); Assert.AreSame(tmpA, tmpC); - - mocks.VerifyAll(); } - /// /// Tests that the same underlying instance of the message consumer is returned after /// creating a session, creating the consumer (A), closing the session, and creating another @@ -208,9 +181,6 @@ public void CachedMessageConsumer() { IConnectionFactory connectionFactory = CreateConnectionFactory(); - mocks.ReplayAll(); - - CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(); cachingConnectionFactory.TargetConnectionFactory = connectionFactory; IConnection con1 = cachingConnectionFactory.CreateConnection(); @@ -227,15 +197,14 @@ public void CachedMessageConsumer() TestMessageConsumer tmpB = GetTestMessageConsumer(consumerB); Assert.AreSame(tmpA, tmpB); - mocks.VerifyAll(); } private IConnectionFactory CreateConnectionFactory() { - IConnectionFactory connectionFactory = mocks.StrictMock(); + IConnectionFactory connectionFactory = A.Fake(); IConnection connection = new TestConnection(); - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Once(); return connectionFactory; } diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/MessageTransactionManagerTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/MessageTransactionManagerTests.cs index bda194d3e..f77fb5a7f 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/MessageTransactionManagerTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/MessageTransactionManagerTests.cs @@ -21,8 +21,10 @@ #region Imports using Apache.NMS; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Messaging.Nms.Core; using Spring.Transaction; using Spring.Transaction.Support; @@ -39,27 +41,14 @@ namespace Spring.Messaging.Nms.Connections [TestFixture] public class NmsTransactionManagerTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void TransactionCommit() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - - using (mocks.Ordered()) - { - SetupCommitExpectations(connection, connectionFactory, session); - } + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession session = A.Fake(); - mocks.ReplayAll(); + SetupCreateSession(connection, connectionFactory, session); NmsTransactionManager tm = new NmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); @@ -67,20 +56,17 @@ public void TransactionCommit() nt.Execute(new AssertSessionCallback(session)); tm.Commit(ts); - mocks.VerifyAll(); - + AssertCommitExpectations(connection, connectionFactory, session); } [Test] public void TransactionRollback() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - - SetupRollbackExpectations(connection, connectionFactory, session); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession session = A.Fake(); - mocks.ReplayAll(); + SetupCreateSession(connection, connectionFactory, session); NmsTransactionManager tm = new NmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); @@ -88,23 +74,17 @@ public void TransactionRollback() nt.Execute(new AssertSessionCallback(session)); tm.Rollback(ts); - mocks.VerifyAll(); + AssertRollbackExpectations(connection, connectionFactory, session); } [Test] public void ParticipatingTransactionWithCommit() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - - using (mocks.Ordered()) - { - SetupCommitExpectations(connection, connectionFactory, session); - } - - mocks.ReplayAll(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession session = A.Fake(); + SetupCreateSession(connection, connectionFactory, session); NmsTransactionManager tm = new NmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); @@ -120,23 +100,17 @@ public void ParticipatingTransactionWithCommit() tm.Commit(ts); - mocks.VerifyAll(); - + AssertCommitExpectations(connection, connectionFactory, session); } [Test] public void ParticipatingTransactionWithRollback() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession session = mocks.StrictMock(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession session = A.Fake(); - using (mocks.Ordered()) - { - SetupRollbackExpectations(connection, connectionFactory, session); - } - - mocks.ReplayAll(); + SetupCreateSession(connection, connectionFactory, session); NmsTransactionManager tm = new NmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); @@ -159,34 +133,21 @@ public void ParticipatingTransactionWithRollback() } - mocks.VerifyAll(); + AssertRollbackExpectations(connection, connectionFactory, session); } [Test] public void SuspendedTransaction() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ISession session2 = mocks.StrictMock(); - - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Twice(); - Expect.Call(connection.CreateSession(AcknowledgementMode.Transactional)).Return(session).Repeat.Once(); - Expect.Call(connection.CreateSession(AcknowledgementMode.AutoAcknowledge)).Return(session2).Repeat.Once(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession session = A.Fake(); + ISession session2 = A.Fake(); + + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Twice(); + A.CallTo(() => connection.CreateSession(AcknowledgementMode.Transactional)).Returns(session).Once(); + A.CallTo(() => connection.CreateSession(AcknowledgementMode.AutoAcknowledge)).Returns(session2).Once(); - session.Commit(); - LastCall.On(session).Repeat.Once(); - session.Close(); - LastCall.On(session).Repeat.Once(); - - session2.Close(); - LastCall.On(session2).Repeat.Once(); - - connection.Close(); - LastCall.On(connection).Repeat.Twice(); - - mocks.ReplayAll(); - NmsTransactionManager tm = new NmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); NmsTemplate nt = new NmsTemplate(connectionFactory); @@ -204,43 +165,29 @@ public void SuspendedTransaction() tm.Commit(ts); - mocks.VerifyAll(); - + A.CallTo(() => session.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedTwiceExactly(); } [Test] public void TransactionSuspension() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession session = mocks.StrictMock(); - ISession session2 = mocks.StrictMock(); - - - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Twice(); - Expect.Call(connection.CreateSession(AcknowledgementMode.Transactional)).Return(session).Repeat.Once(); - Expect.Call(connection.CreateSession(AcknowledgementMode.Transactional)).Return(session2).Repeat.Once(); - - session.Commit(); - LastCall.On(session).Repeat.Once(); - session2.Commit(); - LastCall.On(session2).Repeat.Once(); - - session.Close(); - LastCall.On(session).Repeat.Once(); - session2.Close(); - LastCall.On(session2).Repeat.Once(); - - connection.Close(); - LastCall.On(connection).Repeat.Twice(); - - mocks.ReplayAll(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession session = A.Fake(); + ISession session2 = A.Fake(); + + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Twice(); + A.CallTo(() => connection.CreateSession(AcknowledgementMode.Transactional)) + .Returns(session).Once() + .Then.Returns(session2).Once(); NmsTransactionManager tm = new NmsTransactionManager(connectionFactory); ITransactionStatus ts = tm.GetTransaction(new DefaultTransactionDefinition()); NmsTemplate nt = new NmsTemplate(connectionFactory); - TransactionTemplate tt = new TransactionTemplate(tm); tt.PropagationBehavior = TransactionPropagation.RequiresNew; tt.Execute(status => @@ -253,32 +200,38 @@ public void TransactionSuspension() tm.Commit(ts); - mocks.VerifyAll(); + A.CallTo(() => session.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session2.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedTwiceExactly(); + } + private static void AssertRollbackExpectations(IConnection connection, IConnectionFactory connectionFactory, ISession session) + { + A.CallTo(() => session.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } - private static void SetupRollbackExpectations(IConnection connection, IConnectionFactory connectionFactory, ISession session) + private static void SetupCreateSession( + IConnection connection, + IConnectionFactory connectionFactory, + ISession session) { - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); - Expect.Call(connection.CreateSession(AcknowledgementMode.Transactional)).Return(session).Repeat.Once(); - session.Rollback(); - LastCall.On(session).Repeat.Once(); - session.Close(); - LastCall.On(session).Repeat.Once(); - connection.Close(); - LastCall.On(connection).Repeat.Once(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Once(); + A.CallTo(() => connection.CreateSession(AcknowledgementMode.Transactional)).Returns(session).Once(); } - private static void SetupCommitExpectations(IConnection connection, IConnectionFactory connectionFactory, ISession session) + + private static void AssertCommitExpectations( + IConnection connection, + IConnectionFactory connectionFactory, + ISession session) { - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); - Expect.Call(connection.CreateSession(AcknowledgementMode.Transactional)).Return(session).Repeat.Once(); - session.Commit(); - LastCall.On(session).Repeat.Once(); - session.Close(); - LastCall.On(session).Repeat.Once(); - connection.Close(); - LastCall.On(connection).Repeat.Once(); + A.CallTo(() => session.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } [TearDown] @@ -288,8 +241,6 @@ public void TearDown() Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); } - - } internal class AssertSessionCallback : ISessionCallback diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/SingleConnectionFactoryTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/SingleConnectionFactoryTests.cs index aa5933218..c71b426dd 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/SingleConnectionFactoryTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Connections/SingleConnectionFactoryTests.cs @@ -21,8 +21,10 @@ #region Imports using Apache.NMS; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Messaging.Nms.Core; @@ -37,31 +39,11 @@ namespace Spring.Messaging.Nms.Connections [TestFixture] public class SingleConnectionFactoryTests { - private MockRepository mocks; - - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - - [Test] public void UsingConnection() { - IConnection connection = mocks.StrictMock(); - - connection.Start(); - LastCall.On(connection).Repeat.Twice(); - connection.PurgeTempDestinations(); - LastCall.On( connection ).Repeat.Twice(); - connection.Stop(); - LastCall.On(connection).Repeat.Once(); - connection.Close(); - LastCall.On(connection).Repeat.Once(); - - mocks.ReplayAll(); - + IConnection connection = A.Fake(); + SingleConnectionFactory scf = new SingleConnectionFactory(connection); IConnection con1 = scf.CreateConnection(); con1.Start(); @@ -75,25 +57,19 @@ public void UsingConnection() con2.Close(); // should be ignored. scf.Dispose(); - mocks.VerifyAll(); + A.CallTo(() => connection.Start()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => connection.PurgeTempDestinations()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => connection.Stop()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } [Test] public void UsingConnectionFactory() { - IConnectionFactory connectionFactory = (IConnectionFactory)mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); - connection.Start(); - LastCall.On(connection).Repeat.Twice(); - connection.Stop(); - LastCall.On(connection).Repeat.Once(); - connection.Close(); - LastCall.On(connection).Repeat.Once(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); - - mocks.ReplayAll(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Once(); SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); IConnection con1 = scf.CreateConnection(); @@ -101,30 +77,21 @@ public void UsingConnectionFactory() con1.Close(); // should be ignored IConnection con2 = scf.CreateConnection(); con2.Start(); - con2.Close(); //should be ignored - scf.Dispose(); //should trigger actual close - - mocks.VerifyAll(); + con2.Close(); //should be ignored + scf.Dispose(); //should trigger actual close + A.CallTo(() => connection.Start()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => connection.Stop()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } [Test] public void UsingConnectionFactoryAndClientId() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); - connection.ClientId = "MyId"; - LastCall.On(connection).Repeat.Once(); - connection.Start(); - LastCall.On(connection).Repeat.Twice(); - connection.Stop(); - LastCall.On(connection).Repeat.Once(); - connection.Close(); - LastCall.On(connection).Repeat.Once(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); - mocks.ReplayAll(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Once(); SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); scf.ClientId = "MyId"; @@ -133,36 +100,26 @@ public void UsingConnectionFactoryAndClientId() con1.Close(); // should be ignored IConnection con2 = scf.CreateConnection(); con2.Start(); - con2.Close(); // should be ignored - scf.Dispose(); // should trigger actual close - - mocks.VerifyAll(); - + con2.Close(); // should be ignored + scf.Dispose(); // should trigger actual close + A.CallToSet(() => connection.ClientId).WhenArgumentsMatch(x => x.Get(0) == "MyId").MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Start()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => connection.Stop()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } [Test] public void UsingConnectionFactoryAndExceptionListener() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); IExceptionListener listener = new ChainedExceptionListener(); - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); - connection.ExceptionListener += listener.OnException; - LastCall.On(connection).IgnoreArguments(); - - connection.Start(); - LastCall.On(connection).Repeat.Twice(); - connection.Stop(); - LastCall.On(connection).Repeat.Once(); - connection.Close(); - LastCall.On(connection).Repeat.Once(); - - mocks.ReplayAll(); - + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Once(); + SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); scf.ExceptionListener = listener; IConnection con1 = scf.CreateConnection(); @@ -177,19 +134,24 @@ public void UsingConnectionFactoryAndExceptionListener() con2.Stop(); con2.Close(); scf.Dispose(); - - mocks.VerifyAll(); + + // TODO + //connection.ExceptionListener += listener.OnException; + // LastCall.On(connection).IgnoreArguments(); + + + A.CallTo(() => connection.Start()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => connection.Stop()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } [Test] public void UsingConnectionFactoryAndReconnectOnException() { - IConnectionFactory connectionFactory = mocks.StrictMock(); + IConnectionFactory connectionFactory = A.Fake(); TestConnection con = new TestConnection(); - Expect.Call(connectionFactory.CreateConnection()).Return(con).Repeat.Twice(); - - mocks.ReplayAll(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(con).Twice(); SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); scf.ReconnectOnException = true; @@ -201,8 +163,6 @@ public void UsingConnectionFactoryAndReconnectOnException() con2.Start(); scf.Dispose(); - mocks.VerifyAll(); - Assert.AreEqual(2, con.StartCount); Assert.AreEqual(2, con.CloseCount); } @@ -210,14 +170,12 @@ public void UsingConnectionFactoryAndReconnectOnException() [Test] public void UsingConnectionFactoryAndExceptionListenerAndReconnectOnException() { - IConnectionFactory connectionFactory = mocks.StrictMock(); + IConnectionFactory connectionFactory = A.Fake(); TestConnection con = new TestConnection(); TestExceptionListener listener = new TestExceptionListener(); - Expect.Call(connectionFactory.CreateConnection()).Return(con).Repeat.Twice(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(con).Twice(); - mocks.ReplayAll(); - SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); scf.ExceptionListener = listener; scf.ReconnectOnException = true; @@ -229,8 +187,6 @@ public void UsingConnectionFactoryAndExceptionListenerAndReconnectOnException() con2.Start(); scf.Dispose(); - mocks.VerifyAll(); - Assert.AreEqual(2, con.StartCount); Assert.AreEqual(2, con.CloseCount); Assert.AreEqual(1, listener.Count); @@ -239,32 +195,16 @@ public void UsingConnectionFactoryAndExceptionListenerAndReconnectOnException() [Test] public void CachingConnectionFactory() { - IConnectionFactory connectionFactory = mocks.StrictMock(); - IConnection connection = mocks.StrictMock(); - ISession txSession = mocks.StrictMock(); - ISession nonTxSession = mocks.StrictMock(); - Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once(); - - Expect.Call(connection.CreateSession(AcknowledgementMode.Transactional)).Return(txSession).Repeat.Once(); - Expect.Call(txSession.Transacted).Return(true).Repeat.Twice(); - txSession.Rollback(); - LastCall.Repeat.Once(); - txSession.Commit(); - LastCall.Repeat.Once(); - txSession.Close(); - LastCall.Repeat.Once(); - - Expect.Call(connection.CreateSession(AcknowledgementMode.ClientAcknowledge)).Return(nonTxSession).Repeat.Once(); - nonTxSession.Close(); - LastCall.Repeat.Once(); - connection.Start(); - LastCall.Repeat.Twice(); - connection.Stop(); - LastCall.Repeat.Once(); - connection.Close(); - LastCall.Repeat.Once(); - - mocks.ReplayAll(); + IConnectionFactory connectionFactory = A.Fake(); + IConnection connection = A.Fake(); + ISession txSession = A.Fake(); + ISession nonTxSession = A.Fake(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection).Once(); + + A.CallTo(() => connection.CreateSession(AcknowledgementMode.Transactional)).Returns(txSession).Once(); + A.CallTo(() => txSession.Transacted).Returns(true).Twice(); + + A.CallTo(() => connection.CreateSession(AcknowledgementMode.ClientAcknowledge)).Returns(nonTxSession).Once(); CachingConnectionFactory scf = new CachingConnectionFactory(connectionFactory); scf.ReconnectOnException = false; @@ -272,9 +212,9 @@ public void CachingConnectionFactory() IConnection con1 = scf.CreateConnection(); ISession session1 = con1.CreateSession(AcknowledgementMode.Transactional); bool b = session1.Transacted; - session1.Close(); // should be ignored + session1.Close(); // should be ignored session1 = con1.CreateSession(AcknowledgementMode.ClientAcknowledge); - session1.Close(); // should be ignored + session1.Close(); // should be ignored con1.Start(); con1.Close(); // should be ignored IConnection con2 = scf.CreateConnection(); @@ -287,12 +227,14 @@ public void CachingConnectionFactory() con2.Close(); scf.Dispose(); - mocks.Verify(connectionFactory); - mocks.Verify(connection); - mocks.Verify(txSession); - mocks.Verify(nonTxSession); - + A.CallTo(() => txSession.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => txSession.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => txSession.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => nonTxSession.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Start()).MustHaveHappenedTwiceExactly(); + A.CallTo(() => connection.Stop()).MustHaveHappenedOnceExactly(); + A.CallTo(() => connection.Close()).MustHaveHappenedOnceExactly(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/MessageTemplateTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/MessageTemplateTests.cs index a94ea163c..8927e53b7 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/MessageTemplateTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/MessageTemplateTests.cs @@ -22,8 +22,10 @@ using System.Collections; using Apache.NMS; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Messaging.Nms.Connections; using Spring.Messaging.Nms.Support.Destinations; using Spring.Transaction.Support; @@ -39,7 +41,6 @@ namespace Spring.Messaging.Nms.Core [TestFixture] public class MessageTemplateTests { - private MockRepository mocks; private IDestinationResolver mockDestinationResolver; private IConnectionFactory mockConnectionFactory; private IConnection mockConnection; @@ -49,7 +50,6 @@ public class MessageTemplateTests [SetUp] public void Setup() { - mocks = new MockRepository(); CreateMocks(); } @@ -74,30 +74,26 @@ protected virtual bool UseTransactedTemplate private void CreateMocks() { - mockConnectionFactory = mocks.StrictMock(); - mockConnection = mocks.StrictMock(); - mockSession = mocks.StrictMock(); + mockConnectionFactory = A.Fake(); + mockConnection = A.Fake(); + mockSession = A.Fake(); - IQueue queue = mocks.StrictMock(); + IQueue queue = A.Fake(); - Expect.Call(mockConnectionFactory.CreateConnection()).Return(mockConnection).Repeat.Once(); + A.CallTo(() => mockConnectionFactory.CreateConnection()).Returns(mockConnection).Once(); if (UseTransactedTemplate) { - Expect.Call(mockConnection.CreateSession(AcknowledgementMode.Transactional)).Return(mockSession).Repeat. - Once(); + A.CallTo(() => mockConnection.CreateSession(AcknowledgementMode.Transactional)).Returns(mockSession).Once(); } else { - Expect.Call(mockConnection.CreateSession(AcknowledgementMode.AutoAcknowledge)).Return(mockSession). - Repeat. - Once(); + A.CallTo(() => mockConnection.CreateSession(AcknowledgementMode.AutoAcknowledge)).Returns(mockSession).Once(); } - Expect.Call(mockSession.Transacted).Return(true); - mockDestinationResolver = - mocks.StrictMock(); - mockDestinationResolver.ResolveDestinationName(mockSession, "testDestination", false); - LastCall.Return(queue).Repeat.Any(); + A.CallTo(() => mockSession.Transacted).Returns(true); + + mockDestinationResolver = A.Fake(); + A.CallTo(() => mockDestinationResolver.ResolveDestinationName(mockSession, "testDestination", false)).Returns(queue); } [Test] @@ -106,13 +102,9 @@ public void ProducerCallback() NmsTemplate template = CreateTemplate(); template.ConnectionFactory = mockConnectionFactory; - IMessageProducer mockProducer = mocks.StrictMock(); - Expect.Call(mockSession.CreateProducer(null)).Return(mockProducer); - - Expect.Call(mockProducer.Priority).Return(MsgPriority.Normal); - CloseProducerSessionConnection(mockProducer); - - mocks.ReplayAll(); + IMessageProducer mockProducer = A.Fake(); + A.CallTo(() => mockSession.CreateProducer(null)).Returns(mockProducer); + A.CallTo(() => mockProducer.Priority).Returns(MsgPriority.Normal); MsgPriority priority = MsgPriority.Highest; template.Execute((session, producer) => @@ -122,11 +114,10 @@ public void ProducerCallback() return null; }); - - Assert.AreEqual(priority, MsgPriority.Normal); - mocks.VerifyAll(); - } + Assert.AreEqual(priority, MsgPriority.Normal); + AssertCloseProducerSessionConnection(mockProducer); + } [Test] public void ProducerCallbackWithIdAndTimestampDisabled() @@ -136,39 +127,28 @@ public void ProducerCallbackWithIdAndTimestampDisabled() template.MessageIdEnabled = false; template.MessageTimestampEnabled = false; - IMessageProducer mockProducer = mocks.StrictMock(); - Expect.Call(mockSession.CreateProducer(null)).Return(mockProducer); - - mockProducer.DisableMessageID = true; - LastCall.On(mockProducer).Repeat.Once(); - mockProducer.DisableMessageTimestamp = true; - LastCall.On(mockProducer).Repeat.Once(); + IMessageProducer mockProducer = A.Fake(); + A.CallTo(() => mockSession.CreateProducer(null)).Returns(mockProducer); - Expect.Call(mockProducer.Priority).Return(MsgPriority.Normal); - CloseProducerSessionConnection(mockProducer); - - mocks.ReplayAll(); + A.CallTo(() => mockProducer.Priority).Returns(MsgPriority.Normal); template.Execute((session, producer) => - { - bool b = session.Transacted; - MsgPriority priority = producer.Priority; - return null; - - }); - - mocks.VerifyAll(); + { + bool b = session.Transacted; + MsgPriority priority = producer.Priority; + return null; + }); + AssertCloseProducerSessionConnection(mockProducer); + A.CallToSet(() => mockProducer.DisableMessageID).WhenArgumentsMatch(x => x.Get(0) == true).MustHaveHappenedOnceExactly(); + A.CallToSet(() => mockProducer.DisableMessageTimestamp).WhenArgumentsMatch(x => x.Get(0) == true).MustHaveHappenedOnceExactly(); } - private void CloseProducerSessionConnection(IMessageProducer mockProducer) + private void AssertCloseProducerSessionConnection(IMessageProducer mockProducer) { - mockProducer.Close(); - LastCall.On(mockProducer).Repeat.Once(); - mockSession.Close(); - LastCall.On(mockSession).Repeat.Once(); - mockConnection.Close(); - LastCall.On(mockConnection).Repeat.Once(); + A.CallTo(() => mockProducer.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => mockSession.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => mockConnection.Close()).MustHaveHappenedOnceExactly(); } [Test] @@ -176,19 +156,15 @@ public void SessionCallback() { NmsTemplate template = CreateTemplate(); template.ConnectionFactory = mockConnectionFactory; - mockSession.Close(); - LastCall.On(mockSession).Repeat.Once(); - mockConnection.Close(); - LastCall.On(mockConnection).Repeat.Once(); - - mocks.ReplayAll(); template.Execute(session => { bool b = session.Transacted; return null; }); - mocks.VerifyAll(); + + A.CallTo(() => mockSession.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => mockConnection.Close()).MustHaveHappenedOnceExactly(); } [Test] @@ -198,26 +174,8 @@ public void SessionCallbackWithinSynchronizedTransaction() NmsTemplate template = CreateTemplate(); template.ConnectionFactory = scf; - mockConnection.Start(); - LastCall.On(mockConnection).Repeat.Times(2); // We're gonna call getTransacted 3 times, i.e. 2 more times. - Expect.Call(mockSession.Transacted).Return(UseTransactedSession).Repeat.Twice(); - - if (UseTransactedTemplate) - { - mockSession.Commit(); - LastCall.On(mockSession).Repeat.Once(); - } - - mockSession.Close(); - LastCall.On(mockSession).Repeat.Once(); - mockConnection.Stop(); - LastCall.On(mockConnection).Repeat.Once(); - mockConnection.Close(); - LastCall.On(mockConnection).Repeat.Once(); - - mocks.ReplayAll(); - + A.CallTo(() => mockSession.Transacted).Returns(UseTransactedSession); TransactionSynchronizationManager.InitSynchronization(); @@ -263,9 +221,17 @@ public void SessionCallbackWithinSynchronizedTransaction() scf.Dispose(); } Assert.IsTrue(TransactionSynchronizationManager.ResourceDictionary.Count == 0); - mocks.VerifyAll(); - } - + A.CallTo(() => mockConnection.Start()).MustHaveHappenedTwiceExactly(); + + if (UseTransactedTemplate) + { + A.CallTo(() => mockSession.Commit()).MustHaveHappenedOnceExactly(); + } + + A.CallTo(() => mockSession.Close()).MustHaveHappenedOnceExactly(); + A.CallTo(() => mockConnection.Stop()).MustHaveHappenedOnceExactly(); + A.CallTo(() => mockConnection.Close()).MustHaveHappenedOnceExactly(); + } } } \ No newline at end of file diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageConverterTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageConverterTests.cs index c01cd6bea..f81c7d3b3 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageConverterTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageConverterTests.cs @@ -27,9 +27,9 @@ using Apache.NMS; using Apache.NMS.Util; -using NUnit.Framework; +using FakeItEasy; -using Rhino.Mocks; +using NUnit.Framework; using Spring.Messaging.Nms.Support.Converter; @@ -44,102 +44,73 @@ namespace Spring.Messaging.Nms.Core [TestFixture] public class SimpleMessageConverterTests { - private MockRepository mocks; private SimpleMessageConverter converter; private ISession session; - [SetUp] public void Setup() { - mocks = new MockRepository(); - session = mocks.StrictMock(); + session = A.Fake(); converter = new SimpleMessageConverter(); } [Test] public void StringConversion() { - ITextMessage message = mocks.StrictMock(); + ITextMessage message = A.Fake(); string content = "test"; - Expect.Call(session.CreateTextMessage(content)).Return(message).Repeat.Once(); - string txt = message.Text; - LastCall.On(message).Return(content).Repeat.Once(); - - mocks.ReplayAll(); - + A.CallTo(() => session.CreateTextMessage(content)).Returns(message).Once(); + A.CallTo(() => message.Text).Returns(content).Once(); IMessage msg = converter.ToMessage(content, session); Assert.AreEqual(content, converter.FromMessage(msg)); - - mocks.VerifyAll(); - - } [Test] public void ByteArrayConversion() { - IBytesMessage message = mocks.StrictMock(); + IBytesMessage message = A.Fake(); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] content = encoding.GetBytes("test"); - Expect.Call(session.CreateBytesMessage()).Return(message); - Expect.Call(message.Content = content).Repeat.Once(); - - - Expect.Call(message.Content).Return(content).Repeat.Once(); + A.CallTo(() => session.CreateBytesMessage()).Returns(message); + A.CallTo(() => message.Content).Returns(content).Once(); - mocks.ReplayAll(); - IMessage msg = converter.ToMessage(content, session); Assert.AreEqual(content.Length, ((byte[])converter.FromMessage(msg)).Length); - - mocks.VerifyAll(); + A.CallTo(() => message.Content).WithAnyArguments().MustHaveHappened(); } [Test] public void MapConversion() { - IMapMessage message = mocks.StrictMock(); + IMapMessage message = A.Fake(); IPrimitiveMap primitiveMap = new PrimitiveMap(); IDictionary content = new Hashtable(); content["key1"] = "value1"; content["key2"] = "value2"; - Expect.Call(session.CreateMapMessage()).Return(message).Repeat.Once(); - Expect.Call(message.Body).Return(primitiveMap).Repeat.Any(); + A.CallTo(() => session.CreateMapMessage()).Returns(message).Once(); + A.CallTo(() => message.Body).Returns(primitiveMap); //can't seem to mock indexer... - mocks.ReplayAll(); - IMessage msg = converter.ToMessage(content, session); Assert.AreEqual(content, converter.FromMessage(msg)); - - mocks.VerifyAll(); - - } [Test] public void Serializable() { - IObjectMessage message = mocks.StrictMock(); + IObjectMessage message = A.Fake(); SerializableWithAttribute content = new SerializableWithAttribute(); - Expect.Call(session.CreateObjectMessage(content)).Return(message).Repeat.Once(); - - Expect.Call(message.Body).Return(content).Repeat.Once(); - - mocks.ReplayAll(); - + A.CallTo(() => session.CreateObjectMessage(content)).Returns(message).Once(); + A.CallTo(() => message.Body).Returns(content).Once(); IMessage msg = converter.ToMessage(content, session); Assert.AreEqual(content, converter.FromMessage(message)); - - mocks.VerifyAll(); } [Test] @@ -157,53 +128,31 @@ public void ToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() [Test] public void ToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() { - IObjectMessage message = mocks.StrictMock(); - - mocks.ReplayAll(); - + IObjectMessage message = A.Fake(); IMessage msg = converter.ToMessage(message, session); Assert.AreSame(message, msg); - - mocks.VerifyAll(); } [Test] public void FromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() { - IMessage message = mocks.StrictMock(); - - mocks.ReplayAll(); - + IMessage message = A.Fake(); Object msg = converter.FromMessage(message); Assert.AreSame(message, msg); - - mocks.VerifyAll(); } [Test] public void DictionaryConversionWhereMapHasNonStringTypesForKeys() { - IMapMessage message = mocks.StrictMock(); - + IMapMessage message = A.Fake(); - Expect.Call(session.CreateMapMessage()).Return(message); - mocks.ReplayAll(); + A.CallTo(() => session.CreateMapMessage()).Returns(message); - IDictionary content = new Hashtable(); + var content = new Hashtable(); content.Add(new Cafe(), "value1"); - - try - { - converter.ToMessage(content, session); - Assert.Fail("Should have thrown MessageConversionException"); - } catch (MessageConversionException) - { - - } - - mocks.VerifyAll(); + + Assert.Throws(() => converter.ToMessage(content, session)); } - [Serializable] public class SerializableWithAttribute diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageListenerContainerTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageListenerContainerTests.cs index 8f4a52be0..e0108d0e9 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageListenerContainerTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Core/SimpleMessageListenerContainerTests.cs @@ -21,9 +21,13 @@ #region Imports using System; + using Apache.NMS; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Messaging.Nms.Listener; using Spring.Util; @@ -39,53 +43,41 @@ namespace Spring.Messaging.Nms.Core public class SimpleMessageListenerContainerTests { private static string DESTINATION_NAME = "foo"; - private static StubQueue QUEUE_DESTINATION = new StubQueue(); - private static string EXCEPTION_MESSAGE = "This.Is.It"; - private SimpleMessageListenerContainer container; - private MockRepository mocks; - - [SetUp] public void Setup() { - mocks = new MockRepository(); - container = new SimpleMessageListenerContainer(); + container = new SimpleMessageListenerContainer(); } - - [Test] public void RegisteredExceptionListenerIsInvokedOnException() { SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - ISession session = mocks.StrictMock(); - Expect.Call(session.GetQueue(DESTINATION_NAME)).Return(QUEUE_DESTINATION); - Expect.Call(session.CreateConsumer(QUEUE_DESTINATION, null)).Return(messageConsumer); + ISession session = A.Fake(); + A.CallTo(() => session.GetQueue(DESTINATION_NAME)).Returns(QUEUE_DESTINATION); + A.CallTo(() => session.CreateConsumer(QUEUE_DESTINATION, null)).Returns(messageConsumer); // an exception is thrown, so the rollback logic is being applied here... - Expect.Call(session.Transacted).Return(false); + A.CallTo(() => session.Transacted).Returns(false); - IConnection connection = mocks.StrictMock(); + IConnection connection = A.Fake(); connection.ExceptionListener += container.OnException; - Expect.Call(connection.CreateSession(container.SessionAcknowledgeMode)).Return(session); + A.CallTo(() => connection.CreateSession(container.SessionAcknowledgeMode)).Returns(session); connection.Start(); - - IConnectionFactory connectionFactory = mocks.StrictMock(); - Expect.Call(connectionFactory.CreateConnection()).Return(connection); + + IConnectionFactory connectionFactory = A.Fake(); + A.CallTo(() => connectionFactory.CreateConnection()).Returns(connection); NMSException theException = new NMSException(EXCEPTION_MESSAGE); - IExceptionListener exceptionListener = mocks.StrictMock(); + IExceptionListener exceptionListener = A.Fake(); exceptionListener.OnException(theException); - IMessage message = mocks.StrictMock(); - - mocks.ReplayAll(); - + IMessage message = A.Fake(); container.ConnectionFactory = connectionFactory; container.DestinationName = DESTINATION_NAME; @@ -95,7 +87,6 @@ public void RegisteredExceptionListenerIsInvokedOnException() // manually trigger an Exception with the above bad MessageListener... messageConsumer.SendMessage(message); - mocks.VerifyAll(); } [Test] @@ -103,29 +94,26 @@ public void RegisteredErrorHandlerIsInvokedOnException() { SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - ISession session = mocks.StrictMock(); - Expect.Call(session.GetQueue(DESTINATION_NAME)).Return(QUEUE_DESTINATION); - Expect.Call(session.CreateConsumer(QUEUE_DESTINATION, null)).Return(messageConsumer); + ISession session = A.Fake(); + A.CallTo((() => session.GetQueue(DESTINATION_NAME))).Returns(QUEUE_DESTINATION); + A.CallTo((() => session.CreateConsumer(QUEUE_DESTINATION, null))).Returns(messageConsumer); // an exception is thrown, so the rollback logic is being applied here... - Expect.Call(session.Transacted).Return(false); + A.CallTo((() => session.Transacted)).Returns(false); - IConnection connection = mocks.StrictMock(); + IConnection connection = A.Fake(); connection.ExceptionListener += container.OnException; - Expect.Call(connection.CreateSession(container.SessionAcknowledgeMode)).Return(session); + A.CallTo((() => connection.CreateSession(container.SessionAcknowledgeMode))).Returns(session); connection.Start(); - IConnectionFactory connectionFactory = mocks.StrictMock(); - Expect.Call(connectionFactory.CreateConnection()).Return(connection); + IConnectionFactory connectionFactory = A.Fake(); + A.CallTo((() => connectionFactory.CreateConnection())).Returns(connection); IllegalStateException theException = new IllegalStateException(EXCEPTION_MESSAGE); - IErrorHandler errorHandler = mocks.StrictMock(); + IErrorHandler errorHandler = A.Fake(); errorHandler.HandleError(theException); - IMessage message = mocks.StrictMock(); - - mocks.ReplayAll(); - + IMessage message = A.Fake(); container.ConnectionFactory = connectionFactory; container.DestinationName = DESTINATION_NAME; @@ -135,64 +123,62 @@ public void RegisteredErrorHandlerIsInvokedOnException() // manually trigger an Exception with the above bad MessageListener... messageConsumer.SendMessage(message); - - mocks.VerifyAll(); } - } - internal class BadSessionAwareMessageListener : ISessionAwareMessageListener - { - private NMSException exception; - public BadSessionAwareMessageListener(NMSException exception) + internal class BadSessionAwareMessageListener : ISessionAwareMessageListener { - this.exception = exception; - } + private NMSException exception; - public void OnMessage(IMessage message, ISession session) - { - throw exception; - } - } - - internal class SimpleMessageConsumer : IMessageConsumer - { - public event MessageListener Listener; - - public void SendMessage(IMessage message) - { - Listener(message); - } - public IMessage Receive() - { - throw new NotImplementedException(); - } - - public IMessage Receive(TimeSpan timeout) - { - throw new NotImplementedException(); - } - - public IMessage ReceiveNoWait() - { - throw new NotImplementedException(); - } - - public void Close() - { - throw new NotImplementedException(); - } + public BadSessionAwareMessageListener(NMSException exception) + { + this.exception = exception; + } - public ConsumerTransformerDelegate ConsumerTransformer - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } + public void OnMessage(IMessage message, ISession session) + { + throw exception; + } } - public void Dispose() + internal class SimpleMessageConsumer : IMessageConsumer { - throw new NotImplementedException(); + public event MessageListener Listener; + + public void SendMessage(IMessage message) + { + Listener(message); + } + + public IMessage Receive() + { + throw new NotImplementedException(); + } + + public IMessage Receive(TimeSpan timeout) + { + throw new NotImplementedException(); + } + + public IMessage ReceiveNoWait() + { + throw new NotImplementedException(); + } + + public void Close() + { + throw new NotImplementedException(); + } + + public ConsumerTransformerDelegate ConsumerTransformer + { + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } + } + + public void Dispose() + { + throw new NotImplementedException(); + } } - - } } \ No newline at end of file diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Listener/Adapter/MessageListenerAdapterTests.cs b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Listener/Adapter/MessageListenerAdapterTests.cs index a900297b0..37fb4ce32 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Listener/Adapter/MessageListenerAdapterTests.cs +++ b/test/Spring/Spring.Messaging.Nms.Tests/Messaging/Nms/Listener/Adapter/MessageListenerAdapterTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,13 @@ #region Imports -using System; using System.Text; + using Apache.NMS; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; #endregion @@ -38,87 +40,67 @@ namespace Spring.Messaging.Nms.Listener.Adapter [TestFixture] public class MessageListenerAdapterTests { - private MockRepository mocks; - private static string TEXT = "I fancy a good cuppa right now"; - [SetUp] - public void Setup() - { - mocks = new MockRepository(); - } - [Test] public void MessageContentsHandlerForTextMessage() { int numIterations = 10; - ITextMessage message = mocks.StrictMock(); - Expect.Call(message.Text).Return(TEXT).Repeat.Times(numIterations); + ITextMessage message = A.Fake(); + A.CallTo(() => message.Text).Returns(TEXT).NumberOfTimes(numIterations); MessageContentsHandler handler = new MessageContentsHandler(); - mocks.ReplayAll(); MessageListenerAdapter adapter = new MessageListenerAdapter(handler); for (int i = 0; i < numIterations; i++) { adapter.OnMessage(message); } - Assert.AreEqual(numIterations, handler.HandledStringCount); - mocks.VerifyAll(); + Assert.AreEqual(numIterations, handler.HandledStringCount); } [Test] public void MessageContentsHandlerForBytesMessage() { int numIterations = 10; - IBytesMessage message = mocks.StrictMock(); + IBytesMessage message = A.Fake(); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] content = encoding.GetBytes("test"); - Expect.Call(message.Content).Return(content).Repeat.Times(numIterations); - MessageContentsHandler handler = new MessageContentsHandler(); - mocks.ReplayAll(); + A.CallTo(() => message.Content).Returns(content).NumberOfTimes(numIterations); + MessageContentsHandler handler = new MessageContentsHandler(); MessageListenerAdapter adapter = new MessageListenerAdapter(handler); for (int i = 0; i < numIterations; i++) { adapter.OnMessage(message); } - Assert.AreEqual(numIterations, handler.HandledByteArrayCount); - mocks.VerifyAll(); + Assert.AreEqual(numIterations, handler.HandledByteArrayCount); } [Test] public void MessageContentsHandlerOverloadCalls() { int numIterations = 10; - IBytesMessage bytesMessage = mocks.StrictMock(); + IBytesMessage bytesMessage = A.Fake(); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] content = encoding.GetBytes("test"); - Expect.Call(bytesMessage.Content).Return(content).Repeat.Times(numIterations / 2); + A.CallTo(() => bytesMessage.Content).Returns(content).NumberOfTimes(numIterations / 2); - ITextMessage textMessage = mocks.StrictMock(); - Expect.Call(textMessage.Text).Return(TEXT).Repeat.Times(numIterations/2); + ITextMessage textMessage = A.Fake(); + A.CallTo(() => textMessage.Text).Returns(TEXT).NumberOfTimes(numIterations / 2); MessageContentsHandler handler = new MessageContentsHandler(); - mocks.ReplayAll(); MessageListenerAdapter adapter = new MessageListenerAdapter(handler); - for (int i = 0; i < numIterations/2; i++) + for (int i = 0; i < numIterations / 2; i++) { adapter.OnMessage(textMessage); adapter.OnMessage(bytesMessage); } + Assert.AreEqual(numIterations / 2, handler.HandledByteArrayCount); Assert.AreEqual(numIterations / 2, handler.HandledStringCount); - - mocks.VerifyAll(); } } - - [Serializable] - public class SerializableObject - { - - } } \ No newline at end of file diff --git a/test/Spring/Spring.Messaging.Nms.Tests/Spring.Messaging.Nms.Tests.2010.csproj b/test/Spring/Spring.Messaging.Nms.Tests/Spring.Messaging.Nms.Tests.2010.csproj index 1dc099c28..26fd86552 100644 --- a/test/Spring/Spring.Messaging.Nms.Tests/Spring.Messaging.Nms.Tests.2010.csproj +++ b/test/Spring/Spring.Messaging.Nms.Tests/Spring.Messaging.Nms.Tests.2010.csproj @@ -10,12 +10,13 @@ + + - diff --git a/test/Spring/Spring.Messaging.Tests/Spring.Messaging.Tests.2010.csproj b/test/Spring/Spring.Messaging.Tests/Spring.Messaging.Tests.2010.csproj index d508e18a6..bdff90004 100644 --- a/test/Spring/Spring.Messaging.Tests/Spring.Messaging.Tests.2010.csproj +++ b/test/Spring/Spring.Messaging.Tests/Spring.Messaging.Tests.2010.csproj @@ -10,10 +10,11 @@ + + - diff --git a/test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/Spring.Scheduling.Quartz2.Integration.Tests.2010.csproj b/test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/Spring.Scheduling.Quartz2.Integration.Tests.2010.csproj index 543fe6da1..5bf73ef3d 100644 --- a/test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/Spring.Scheduling.Quartz2.Integration.Tests.2010.csproj +++ b/test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/Spring.Scheduling.Quartz2.Integration.Tests.2010.csproj @@ -8,10 +8,11 @@ + + - diff --git a/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/MethodInvokingJobTest.cs b/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/MethodInvokingJobTest.cs index 3de2232e7..da4676a35 100644 --- a/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/MethodInvokingJobTest.cs +++ b/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/MethodInvokingJobTest.cs @@ -17,6 +17,8 @@ using System; using System.Threading; +using FakeItEasy; + using NUnit.Framework; using Quartz; @@ -25,8 +27,6 @@ using Quartz.Job; using Quartz.Spi; -using Rhino.Mocks; - using Spring.Objects.Support; namespace Spring.Scheduling.Quartz @@ -142,8 +142,7 @@ public void TestMethodInvoker_PrivateMethod() private static IJobExecutionContext CreateMinimalJobExecutionContext() { - MockRepository repo = new MockRepository(); - IScheduler sched = (IScheduler)repo.DynamicMock(typeof(IScheduler)); + IScheduler sched = A.Fake(); IJobExecutionContext ctx = new JobExecutionContextImpl(sched, ConstructMinimalTriggerFiredBundle(), null); return ctx; } diff --git a/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/QuartzSupportTests.cs b/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/QuartzSupportTests.cs index 0e454143a..57b7df0a4 100644 --- a/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/QuartzSupportTests.cs +++ b/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/QuartzSupportTests.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,6 +18,8 @@ using System.Collections; using System.Threading; +using FakeItEasy; + using NUnit.Framework; using Quartz; @@ -25,8 +27,6 @@ using Quartz.Impl.Triggers; using Quartz.Spi; -using Rhino.Mocks; - using Spring.Context.Support; using Spring.Objects; using Spring.Objects.Factory.Support; @@ -75,58 +75,60 @@ private void DoTestSchedulerFactoryObject(bool explicitJobDetail, bool prototype TestObject tb = new TestObject("tb", 99); JobDetailObject jobDetail0 = new JobDetailObject(); jobDetail0.JobType = typeof (IJob); - jobDetail0.ObjectName = ("myJob0"); + jobDetail0.ObjectName = "myJob0"; IDictionary jobData = new Hashtable(); jobData.Add("testObject", tb); - jobDetail0.JobDataAsMap = (jobData); + jobDetail0.JobDataAsMap = jobData; jobDetail0.AfterPropertiesSet(); Assert.AreEqual(tb, jobDetail0.JobDataMap.Get("testObject")); CronTriggerObject trigger0 = new CronTriggerObject(); - trigger0.ObjectName = ("myTrigger0"); - trigger0.JobDetail = (jobDetail0); - trigger0.CronExpressionString = ("0/1 * * * * ?"); + trigger0.ObjectName = "myTrigger0"; + trigger0.JobDetail = jobDetail0; + trigger0.CronExpressionString = "0/1 * * * * ?"; trigger0.AfterPropertiesSet(); TestMethodInvokingTask task1 = new TestMethodInvokingTask(); MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject(); - mijdfb.ObjectName = ("myJob1"); + mijdfb.ObjectName = "myJob1"; if (prototypeJob) { StaticListableObjectFactory objectFactory = new StaticListableObjectFactory(); objectFactory.AddObject("task", task1); - mijdfb.TargetObjectName = ("task"); + mijdfb.TargetObjectName = "task"; mijdfb.ObjectFactory = objectFactory; } else { - mijdfb.TargetObject = (task1); + mijdfb.TargetObject = task1; } - mijdfb.TargetMethod = ("doSomething"); + mijdfb.TargetMethod = "doSomething"; mijdfb.AfterPropertiesSet(); IJobDetail jobDetail1 = (IJobDetail) mijdfb.GetObject(); SimpleTriggerObject trigger1 = new SimpleTriggerObject(); - trigger1.ObjectName = ("myTrigger1"); - trigger1.JobDetail = (jobDetail1); + trigger1.ObjectName = "myTrigger1"; + trigger1.JobDetail = jobDetail1; trigger1.StartDelay = TimeSpan.FromMilliseconds(0); trigger1.RepeatInterval = TimeSpan.FromMilliseconds(20); trigger1.AfterPropertiesSet(); - IScheduler scheduler = MockRepository.GenerateMock(); + IScheduler scheduler = A.Fake(); + + A.CallTo(() => scheduler.Context).Returns(new SchedulerContext()); + A.CallTo(() => scheduler.GetTrigger(A._)).Returns(null); + A.CallTo(() => scheduler.GetJobDetail(A._)).Returns(null); - scheduler.Stub(x => x.Context).Return(new SchedulerContext()); - SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler); - schedulerFactoryObject.JobFactory = (null); + schedulerFactoryObject.JobFactory = null; IDictionary schedulerContext = new Hashtable(); schedulerContext.Add("otherTestObject", tb); - schedulerFactoryObject.SchedulerContextAsMap = (schedulerContext); + schedulerFactoryObject.SchedulerContextAsMap = schedulerContext; if (explicitJobDetail) { - schedulerFactoryObject.JobDetails = (new IJobDetail[] {jobDetail0}); + schedulerFactoryObject.JobDetails = new IJobDetail[] {jobDetail0}; } - schedulerFactoryObject.Triggers = (new ITrigger[] {trigger0, trigger1}); + schedulerFactoryObject.Triggers = new ITrigger[] {trigger0, trigger1}; try { schedulerFactoryObject.AfterPropertiesSet(); @@ -137,14 +139,14 @@ private void DoTestSchedulerFactoryObject(bool explicitJobDetail, bool prototype schedulerFactoryObject.Dispose(); } - scheduler.AssertWasCalled(x => x.ScheduleJob(trigger0)); - scheduler.AssertWasCalled(x => x.ScheduleJob(trigger1)); - - scheduler.AssertWasCalled(x => x.AddJob(jobDetail0, true, true)); - scheduler.AssertWasCalled(x => x.AddJob(jobDetail0, true, true)); - - scheduler.AssertWasCalled(x => x.Start()); - scheduler.AssertWasCalled(x => x.Shutdown(false)); + A.CallTo(() => scheduler.ScheduleJob(trigger0)).MustHaveHappened(); + A.CallTo(() => scheduler.ScheduleJob(trigger1)).MustHaveHappened(); + + A.CallTo(() => scheduler.AddJob(jobDetail0, true, true)).MustHaveHappened(); + A.CallTo(() => scheduler.AddJob(jobDetail0, true, true)).MustHaveHappened(); + + A.CallTo(() => scheduler.Start()).MustHaveHappened(); + A.CallTo(() => scheduler.Shutdown(false)).MustHaveHappened(); } /// @@ -170,52 +172,54 @@ private void DoTestSchedulerFactoryObjectWithExistingJobs(bool overwrite) TestObject tb = new TestObject("tb", 99); JobDetailObject jobDetail0 = new JobDetailObject(); jobDetail0.JobType = typeof (IJob); - jobDetail0.ObjectName = ("myJob0"); + jobDetail0.ObjectName = "myJob0"; IDictionary jobData = new Hashtable(); jobData.Add("testObject", tb); - jobDetail0.JobDataAsMap = (jobData); + jobDetail0.JobDataAsMap = jobData; jobDetail0.AfterPropertiesSet(); Assert.AreEqual(tb, jobDetail0.JobDataMap.Get("testObject")); CronTriggerObject trigger0 = new CronTriggerObject(); - trigger0.ObjectName = ("myTrigger0"); - trigger0.JobDetail = (jobDetail0); - trigger0.CronExpressionString = ("0/1 * * * * ?"); + trigger0.ObjectName = "myTrigger0"; + trigger0.JobDetail = jobDetail0; + trigger0.CronExpressionString = "0/1 * * * * ?"; trigger0.AfterPropertiesSet(); TestMethodInvokingTask task1 = new TestMethodInvokingTask(); MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject(); - mijdfb.ObjectName = ("myJob1"); - mijdfb.TargetObject = (task1); - mijdfb.TargetMethod = ("doSomething"); + mijdfb.ObjectName = "myJob1"; + mijdfb.TargetObject = task1; + mijdfb.TargetMethod = "doSomething"; mijdfb.AfterPropertiesSet(); IJobDetail jobDetail1 = (IJobDetail) mijdfb.GetObject(); SimpleTriggerObject trigger1 = new SimpleTriggerObject(); - trigger1.ObjectName = ("myTrigger1"); - trigger1.JobDetail = (jobDetail1); + trigger1.ObjectName = "myTrigger1"; + trigger1.JobDetail = jobDetail1; trigger1.StartDelay = TimeSpan.FromMilliseconds(0); trigger1.RepeatInterval = TimeSpan.FromMilliseconds(20); trigger1.AfterPropertiesSet(); - IScheduler scheduler = MockRepository.GenerateMock(); - scheduler.Stub(x => x.Context).Return(new SchedulerContext()); - scheduler.Stub(x => x.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup))).Return(new SimpleTriggerImpl()); + IScheduler scheduler = A.Fake(); + A.CallTo(() => scheduler.Context).Returns(new SchedulerContext()); + A.CallTo(() => scheduler.GetJobDetail(A._)).Returns(null); + A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup))).Returns(null); + A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup))).Returns(new SimpleTriggerImpl()); if (overwrite) { - scheduler.Stub(x => x.RescheduleJob(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup), trigger1)).Return(DateTime.UtcNow); + A.CallTo(() => scheduler.RescheduleJob(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup), trigger1)).Returns(DateTime.UtcNow); } SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler); - schedulerFactoryObject.JobFactory = (null); + schedulerFactoryObject.JobFactory = null; IDictionary schedulerContext = new Hashtable(); schedulerContext.Add("otherTestObject", tb); - schedulerFactoryObject.SchedulerContextAsMap = (schedulerContext); - schedulerFactoryObject.Triggers = (new ITrigger[] {trigger0, trigger1}); + schedulerFactoryObject.SchedulerContextAsMap = schedulerContext; + schedulerFactoryObject.Triggers = new ITrigger[] {trigger0, trigger1}; if (overwrite) { - schedulerFactoryObject.OverwriteExistingJobs = (true); + schedulerFactoryObject.OverwriteExistingJobs = true; } try { @@ -227,10 +231,10 @@ private void DoTestSchedulerFactoryObjectWithExistingJobs(bool overwrite) schedulerFactoryObject.Dispose(); } - scheduler.AssertWasCalled(x => x.AddJob(jobDetail0, true, true)); - scheduler.AssertWasCalled(x => x.ScheduleJob(trigger0)); - scheduler.AssertWasCalled(x => x.Start()); - scheduler.AssertWasCalled(x => x.Shutdown(false)); + A.CallTo(() => scheduler.AddJob(jobDetail0, true, true)).MustHaveHappened(); + A.CallTo(() => scheduler.ScheduleJob(trigger0)).MustHaveHappened(); + A.CallTo(() => scheduler.Start()).MustHaveHappened(); + A.CallTo(() => scheduler.Shutdown(false)).MustHaveHappened(); } /// @@ -241,7 +245,7 @@ public void TestSchedulerFactoryObjectWithExistingJobsAndRaceCondition() { DoTestSchedulerFactoryObjectWithExistingJobsAndRaceCondition(false); } - + /// /// Executes parametrized test. /// @@ -256,48 +260,50 @@ private void DoTestSchedulerFactoryObjectWithExistingJobsAndRaceCondition(bool o TestObject tb = new TestObject("tb", 99); JobDetailObject jobDetail0 = new JobDetailObject(); jobDetail0.JobType = typeof (IJob); - jobDetail0.ObjectName = ("myJob0"); + jobDetail0.ObjectName = "myJob0"; IDictionary jobData = new Hashtable(); jobData.Add("testObject", tb); - jobDetail0.JobDataAsMap = (jobData); + jobDetail0.JobDataAsMap = jobData; jobDetail0.AfterPropertiesSet(); Assert.AreEqual(tb, jobDetail0.JobDataMap.Get("testObject")); CronTriggerObject trigger0 = new CronTriggerObject(); - trigger0.ObjectName = ("myTrigger0"); - trigger0.JobDetail = (jobDetail0); - trigger0.CronExpressionString = ("0/1 * * * * ?"); + trigger0.ObjectName = "myTrigger0"; + trigger0.JobDetail = jobDetail0; + trigger0.CronExpressionString = "0/1 * * * * ?"; trigger0.AfterPropertiesSet(); TestMethodInvokingTask task1 = new TestMethodInvokingTask(); MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject(); - mijdfb.ObjectName = ("myJob1"); - mijdfb.TargetObject = (task1); - mijdfb.TargetMethod = ("doSomething"); + mijdfb.ObjectName = "myJob1"; + mijdfb.TargetObject = task1; + mijdfb.TargetMethod = "doSomething"; mijdfb.AfterPropertiesSet(); IJobDetail jobDetail1 = (IJobDetail) mijdfb.GetObject(); SimpleTriggerObject trigger1 = new SimpleTriggerObject(); - trigger1.ObjectName = ("myTrigger1"); - trigger1.JobDetail = (jobDetail1); + trigger1.ObjectName = "myTrigger1"; + trigger1.JobDetail = jobDetail1; trigger1.StartDelay = TimeSpan.FromMilliseconds(0); trigger1.RepeatInterval = TimeSpan.FromMilliseconds(20); trigger1.AfterPropertiesSet(); - IScheduler scheduler = MockRepository.GenerateMock(); - scheduler.Stub(x => x.Context).Return(new SchedulerContext()); - scheduler.Stub(x => x.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup))).Return(new SimpleTriggerImpl()); + IScheduler scheduler = A.Fake(); + A.CallTo(() => scheduler.Context).Returns(new SchedulerContext()); + A.CallTo(() => scheduler.GetJobDetail(A._)).Returns(null); + A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup))).Returns(null); + A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup))).Returns(new SimpleTriggerImpl()); if (overwrite) { scheduler.AddJob(jobDetail1, true); - scheduler.Stub(x => x.RescheduleJob(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup), trigger1)).Return(DateTime.UtcNow); + A.CallTo(() => scheduler.RescheduleJob(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup), trigger1)).Returns(DateTime.UtcNow); } - - scheduler.Stub(x => x.ScheduleJob(trigger0)).Throw(new ObjectAlreadyExistsException("")); + + A.CallTo(() => scheduler.ScheduleJob(trigger0)).Throws(new ObjectAlreadyExistsException("")); if (overwrite) { - scheduler.Stub(x => x.RescheduleJob(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup), trigger0)).Return(DateTime.UtcNow); + A.CallTo(() => scheduler.RescheduleJob(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup), trigger0)).Returns(DateTime.UtcNow); } scheduler.Start(); @@ -305,14 +311,14 @@ private void DoTestSchedulerFactoryObjectWithExistingJobsAndRaceCondition(bool o SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler); - schedulerFactoryObject.JobFactory = (null); + schedulerFactoryObject.JobFactory = null; IDictionary schedulerContext = new Hashtable(); schedulerContext.Add("otherTestObject", tb); - schedulerFactoryObject.SchedulerContextAsMap = (schedulerContext); - schedulerFactoryObject.Triggers = (new ITrigger[] {trigger0, trigger1}); + schedulerFactoryObject.SchedulerContextAsMap = schedulerContext; + schedulerFactoryObject.Triggers = new ITrigger[] {trigger0, trigger1}; if (overwrite) { - schedulerFactoryObject.OverwriteExistingJobs = (true); + schedulerFactoryObject.OverwriteExistingJobs = true; } try { @@ -324,7 +330,7 @@ private void DoTestSchedulerFactoryObjectWithExistingJobsAndRaceCondition(bool o schedulerFactoryObject.Dispose(); } - scheduler.AssertWasCalled(x => x.AddJob(jobDetail0, true, true)); + A.CallTo(() => scheduler.AddJob(jobDetail0, true, true)).MustHaveHappened(); } @@ -338,32 +344,32 @@ private void MethodInvokingConcurrency(bool concurrent) TestMethodInvokingTask task1 = new TestMethodInvokingTask(); MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject(); // set the concurrency flag! - mijdfb.Concurrent = (concurrent); - mijdfb.ObjectName = ("myJob1"); - mijdfb.TargetObject = (task1); - mijdfb.TargetMethod = ("doWait"); + mijdfb.Concurrent = concurrent; + mijdfb.ObjectName = "myJob1"; + mijdfb.TargetObject = task1; + mijdfb.TargetMethod = "doWait"; mijdfb.AfterPropertiesSet(); IJobDetail jobDetail1 = (IJobDetail) mijdfb.GetObject(); SimpleTriggerObject trigger0 = new SimpleTriggerObject(); - trigger0.ObjectName = ("myTrigger1"); - trigger0.JobDetail = (jobDetail1); + trigger0.ObjectName = "myTrigger1"; + trigger0.JobDetail = jobDetail1; trigger0.StartDelay = TimeSpan.FromMilliseconds(0); trigger0.RepeatInterval = TimeSpan.FromMilliseconds(1); - trigger0.RepeatCount = (1); + trigger0.RepeatCount = 1; trigger0.AfterPropertiesSet(); SimpleTriggerObject trigger1 = new SimpleTriggerObject(); - trigger1.ObjectName = ("myTrigger1"); - trigger1.JobDetail = (jobDetail1); + trigger1.ObjectName = "myTrigger1"; + trigger1.JobDetail = jobDetail1; trigger1.StartDelay = TimeSpan.FromMilliseconds(1000L); trigger1.RepeatInterval = TimeSpan.FromMilliseconds(1); - trigger1.RepeatCount = (1); + trigger1.RepeatCount = 1; trigger1.AfterPropertiesSet(); SchedulerFactoryObject schedulerFactoryObject = new SchedulerFactoryObject(); - schedulerFactoryObject.JobDetails = (new IJobDetail[] {jobDetail1}); - schedulerFactoryObject.Triggers = (new ITrigger[] {trigger1, trigger0}); + schedulerFactoryObject.JobDetails = new IJobDetail[] {jobDetail1}; + schedulerFactoryObject.Triggers = new ITrigger[] {trigger1, trigger0}; schedulerFactoryObject.AfterPropertiesSet(); // ok scheduler is set up... let's wait for like 4 seconds @@ -418,25 +424,25 @@ public void TestSchedulerFactoryObjectWithPlainQuartzObjects() TestObject tb = new TestObject("tb", 99); JobDetailImpl jobDetail0 = new JobDetailImpl(); jobDetail0.JobType = typeof (IJob); - jobDetail0.Name = ("myJob0"); - jobDetail0.Group = (SchedulerConstants.DefaultGroup); + jobDetail0.Name = "myJob0"; + jobDetail0.Group = SchedulerConstants.DefaultGroup; jobDetail0.JobDataMap.Add("testObject", tb); Assert.AreEqual(tb, jobDetail0.JobDataMap.Get("testObject")); CronTriggerImpl trigger0 = new CronTriggerImpl(); - trigger0.Name = ("myTrigger0"); + trigger0.Name = "myTrigger0"; trigger0.Group = SchedulerConstants.DefaultGroup; trigger0.JobName = "myJob0"; trigger0.JobGroup = SchedulerConstants.DefaultGroup; - trigger0.StartTimeUtc = (DateTime.UtcNow); - trigger0.CronExpressionString = ("0/1 * * * * ?"); + trigger0.StartTimeUtc = DateTime.UtcNow; + trigger0.CronExpressionString = "0/1 * * * * ?"; TestMethodInvokingTask task1 = new TestMethodInvokingTask(); MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject(); - mijdfb.Name = ("myJob1"); - mijdfb.Group = (SchedulerConstants.DefaultGroup); - mijdfb.TargetObject = (task1); - mijdfb.TargetMethod = ("doSomething"); + mijdfb.Name = "myJob1"; + mijdfb.Group = SchedulerConstants.DefaultGroup; + mijdfb.TargetObject = task1; + mijdfb.TargetMethod = "doSomething"; mijdfb.AfterPropertiesSet(); IJobDetail jobDetail1 = (IJobDetail) mijdfb.GetObject(); @@ -445,17 +451,19 @@ public void TestSchedulerFactoryObjectWithPlainQuartzObjects() trigger1.Group = SchedulerConstants.DefaultGroup; trigger1.JobName = "myJob1"; trigger1.JobGroup = SchedulerConstants.DefaultGroup; - trigger1.StartTimeUtc = (DateTime.UtcNow); - trigger1.RepeatCount = (SimpleTriggerImpl.RepeatIndefinitely); + trigger1.StartTimeUtc = DateTime.UtcNow; + trigger1.RepeatCount = SimpleTriggerImpl.RepeatIndefinitely; trigger1.RepeatInterval = TimeSpan.FromMilliseconds(20); - IScheduler scheduler = MockRepository.GenerateMock(); - + IScheduler scheduler = A.Fake(); + A.CallTo(() => scheduler.GetTrigger(A._)).Returns(null); + A.CallTo(() => scheduler.GetJobDetail(A._)).Returns(null); + SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler); - schedulerFactoryObject.JobFactory = (jobFactory); - schedulerFactoryObject.JobDetails = (new IJobDetail[] {jobDetail0, jobDetail1}); - schedulerFactoryObject.Triggers = (new ITrigger[] {trigger0, trigger1}); + schedulerFactoryObject.JobFactory = jobFactory; + schedulerFactoryObject.JobDetails = new IJobDetail[] {jobDetail0, jobDetail1}; + schedulerFactoryObject.Triggers = new ITrigger[] {trigger0, trigger1}; try { schedulerFactoryObject.AfterPropertiesSet(); @@ -466,13 +474,17 @@ public void TestSchedulerFactoryObjectWithPlainQuartzObjects() schedulerFactoryObject.Dispose(); } - scheduler.AssertWasCalled(x => x.JobFactory = jobFactory); - scheduler.AssertWasCalled(x => x.AddJob(jobDetail0, true, true)); - scheduler.AssertWasCalled(x => x.AddJob(jobDetail1, true, true)); - scheduler.AssertWasCalled(x => x.GetJobDetail(new JobKey("myJob0", SchedulerConstants.DefaultGroup))); - scheduler.AssertWasCalled(x => x.GetJobDetail(new JobKey("myJob1", SchedulerConstants.DefaultGroup))); - scheduler.AssertWasCalled(x => x.GetTrigger(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup))); - scheduler.AssertWasCalled(x => x.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup))); + A.CallTo(scheduler) + .Where(x => x.Method.Name.Equals("set_JobFactory")) + .WhenArgumentsMatch(x => x.Get(0) == jobFactory) + .MustHaveHappened(); + + A.CallTo(() => scheduler.AddJob(jobDetail0, true, true)).MustHaveHappened(); + A.CallTo(() => scheduler.AddJob(jobDetail1, true, true)).MustHaveHappened(); + A.CallTo(() => scheduler.GetJobDetail(new JobKey("myJob0", SchedulerConstants.DefaultGroup))).MustHaveHappened(); + A.CallTo(() => scheduler.GetJobDetail(new JobKey("myJob1", SchedulerConstants.DefaultGroup))).MustHaveHappened(); + A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup))).MustHaveHappened(); + A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup))).MustHaveHappened(); } /// @@ -483,17 +495,17 @@ public void TestSchedulerFactoryObjectWithApplicationContext() TestObject tb = new TestObject("tb", 99); StaticApplicationContext ac = new StaticApplicationContext(); - IScheduler scheduler = MockRepository.GenerateMock(); + IScheduler scheduler = A.Fake(); SchedulerContext schedulerContext = new SchedulerContext(); - scheduler.Stub(x => x.Context).Return(schedulerContext).Repeat.Times(4); + A.CallTo(() => scheduler.Context).Returns(schedulerContext).NumberOfTimes(4); SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler); - schedulerFactoryObject.JobFactory = (null); + schedulerFactoryObject.JobFactory = null; IDictionary schedulerContextMap = new Hashtable(); schedulerContextMap.Add("testObject", tb); - schedulerFactoryObject.SchedulerContextAsMap = (schedulerContextMap); - schedulerFactoryObject.ApplicationContext = (ac); - schedulerFactoryObject.ApplicationContextSchedulerContextKey = ("appCtx"); + schedulerFactoryObject.SchedulerContextAsMap = schedulerContextMap; + schedulerFactoryObject.ApplicationContext = ac; + schedulerFactoryObject.ApplicationContextSchedulerContextKey = "appCtx"; try { schedulerFactoryObject.AfterPropertiesSet(); @@ -518,12 +530,12 @@ public void TestJobDetailObjectWithApplicationContext() JobDetailObject jobDetail = new JobDetailObject(); jobDetail.JobType = typeof (IJob); - jobDetail.ObjectName = ("myJob0"); + jobDetail.ObjectName = "myJob0"; IDictionary jobData = new Hashtable(); jobData.Add("testObject", tb); - jobDetail.JobDataAsMap = (jobData); - jobDetail.ApplicationContext = (ac); - jobDetail.ApplicationContextJobDataKey = ("appCtx"); + jobDetail.JobDataAsMap = jobData; + jobDetail.ApplicationContext = ac; + jobDetail.ApplicationContextJobDataKey = "appCtx"; jobDetail.AfterPropertiesSet(); Assert.AreEqual(tb, jobDetail.JobDataMap.Get("testObject")); @@ -540,20 +552,20 @@ public void TestSchedulerWithTaskExecutor() JobDetailImpl jobDetail = new JobDetailImpl(); jobDetail.JobType = typeof (DummyJob); - jobDetail.Name = ("myJob"); + jobDetail.Name = "myJob"; SimpleTriggerObject trigger = new SimpleTriggerObject(); - trigger.Name = ("myTrigger"); - trigger.JobDetail = (jobDetail); + trigger.Name = "myTrigger"; + trigger.JobDetail = jobDetail; trigger.StartDelay = TimeSpan.FromMilliseconds(1); trigger.RepeatInterval = TimeSpan.FromMilliseconds(500); - trigger.RepeatCount = (1); + trigger.RepeatCount = 1; trigger.AfterPropertiesSet(); SchedulerFactoryObject factoryObject = new SchedulerFactoryObject(); - factoryObject.TaskExecutor = (taskExecutor); - factoryObject.Triggers = (new ITrigger[] {trigger}); - factoryObject.JobDetails = (new IJobDetail[] {jobDetail}); + factoryObject.TaskExecutor = taskExecutor; + factoryObject.Triggers = new ITrigger[] {trigger}; + factoryObject.JobDetails = new IJobDetail[] {jobDetail}; factoryObject.AfterPropertiesSet(); factoryObject.Start(); @@ -604,21 +616,21 @@ public void TestSchedulerWithQuartzJobObject() DummyJob.count = 0; JobDetailImpl jobDetail = new JobDetailImpl(); - jobDetail.JobType = (typeof (DummyJobObject)); - jobDetail.Name = ("myJob"); + jobDetail.JobType = typeof (DummyJobObject); + jobDetail.Name = "myJob"; jobDetail.JobDataMap.Put("param", "10"); SimpleTriggerObject trigger = new SimpleTriggerObject(); - trigger.Name = ("myTrigger"); - trigger.JobDetail = (jobDetail); + trigger.Name = "myTrigger"; + trigger.JobDetail = jobDetail; trigger.StartDelay = TimeSpan.FromMilliseconds(1); trigger.RepeatInterval = TimeSpan.FromMilliseconds(500); - trigger.RepeatCount = (1); + trigger.RepeatCount = 1; trigger.AfterPropertiesSet(); SchedulerFactoryObject factoryObject = new SchedulerFactoryObject(); - factoryObject.Triggers = (new ITrigger[] {trigger}); - factoryObject.JobDetails = (new IJobDetail[] {jobDetail}); + factoryObject.Triggers = new ITrigger[] {trigger}; + factoryObject.JobDetails = new IJobDetail[] {jobDetail}; factoryObject.AfterPropertiesSet(); factoryObject.Start(); @@ -639,22 +651,22 @@ public void TestSchedulerWithSpringObjectJobFactory() JobDetailImpl jobDetail = new JobDetailImpl(); jobDetail.JobType = typeof(DummyJob); - jobDetail.Name = ("myJob"); + jobDetail.Name = "myJob"; jobDetail.JobDataMap.Add("param", "10"); jobDetail.JobDataMap.Add("ignoredParam", "10"); SimpleTriggerObject trigger = new SimpleTriggerObject(); - trigger.Name = ("myTrigger"); - trigger.JobDetail = (jobDetail); + trigger.Name = "myTrigger"; + trigger.JobDetail = jobDetail; trigger.StartDelay = TimeSpan.FromMilliseconds(1); trigger.RepeatInterval = TimeSpan.FromMilliseconds(500); - trigger.RepeatCount = (1); + trigger.RepeatCount = 1; trigger.AfterPropertiesSet(); SchedulerFactoryObject factoryObject = new SchedulerFactoryObject(); - factoryObject.JobFactory = (new SpringObjectJobFactory()); - factoryObject.Triggers = (new ITrigger[] {trigger}); - factoryObject.JobDetails = (new IJobDetail[] {jobDetail}); + factoryObject.JobFactory = new SpringObjectJobFactory(); + factoryObject.Triggers = new ITrigger[] {trigger}; + factoryObject.JobDetails = new IJobDetail[] {jobDetail}; factoryObject.AfterPropertiesSet(); factoryObject.Start(); @@ -675,24 +687,24 @@ public void TestSchedulerWithSpringObjectJobFactoryAndParamMismatchNotIgnored() JobDetailImpl jobDetail = new JobDetailImpl(); jobDetail.JobType = typeof(DummyJob); - jobDetail.Name = ("myJob"); + jobDetail.Name = "myJob"; jobDetail.JobDataMap.Add("para", "10"); jobDetail.JobDataMap.Add("ignoredParam", "10"); SimpleTriggerObject trigger = new SimpleTriggerObject(); - trigger.Name = ("myTrigger"); - trigger.JobDetail = (jobDetail); + trigger.Name = "myTrigger"; + trigger.JobDetail = jobDetail; trigger.StartDelay = TimeSpan.FromMilliseconds(1); trigger.RepeatInterval = TimeSpan.FromMilliseconds(500); - trigger.RepeatCount = (1); + trigger.RepeatCount = 1; trigger.AfterPropertiesSet(); SchedulerFactoryObject bean = new SchedulerFactoryObject(); SpringObjectJobFactory jobFactory = new SpringObjectJobFactory(); - jobFactory.IgnoredUnknownProperties = (new String[] {"ignoredParam"}); - bean.JobFactory = (jobFactory); - bean.Triggers = (new ITrigger[] {trigger}); - bean.JobDetails = (new IJobDetail[] {jobDetail}); + jobFactory.IgnoredUnknownProperties = new String[] {"ignoredParam"}; + bean.JobFactory = jobFactory; + bean.Triggers = new ITrigger[] {trigger}; + bean.JobDetails = new IJobDetail[] {jobDetail}; bean.AfterPropertiesSet(); Thread.Sleep(500); @@ -712,21 +724,21 @@ public void TestSchedulerWithSpringObjectJobFactoryAndRunnable() JobDetailObject jobDetail = new JobDetailObject(); jobDetail.JobType = typeof (DummyRunnable); - jobDetail.Name = ("myJob"); + jobDetail.Name = "myJob"; jobDetail.JobDataMap.Add("param", "10"); SimpleTriggerObject trigger = new SimpleTriggerObject(); - trigger.Name = ("myTrigger"); - trigger.JobDetail = (jobDetail); + trigger.Name = "myTrigger"; + trigger.JobDetail = jobDetail; trigger.StartDelay = TimeSpan.FromMilliseconds(1); trigger.RepeatInterval = TimeSpan.FromMilliseconds(500); - trigger.RepeatCount = (1); + trigger.RepeatCount = 1; trigger.AfterPropertiesSet(); SchedulerFactoryObject factoryObject = new SchedulerFactoryObject(); - factoryObject.JobFactory = (new SpringObjectJobFactory()); - factoryObject.Triggers = (new ITrigger[] {trigger}); - factoryObject.JobDetails = (new IJobDetail[] {jobDetail}); + factoryObject.JobFactory = new SpringObjectJobFactory(); + factoryObject.Triggers = new ITrigger[] {trigger}; + factoryObject.JobDetails = new IJobDetail[] {jobDetail}; factoryObject.AfterPropertiesSet(); factoryObject.Start(); @@ -747,21 +759,21 @@ public void TestSchedulerWithSpringObjectJobFactoryAndQuartzJobObject() JobDetailImpl jobDetail = new JobDetailImpl(); jobDetail.JobType = typeof (DummyJobObject); - jobDetail.Name = ("myJob"); + jobDetail.Name = "myJob"; jobDetail.JobDataMap.Add("param", "10"); SimpleTriggerObject trigger = new SimpleTriggerObject(); - trigger.Name = ("myTrigger"); - trigger.JobDetail = (jobDetail); + trigger.Name = "myTrigger"; + trigger.JobDetail = jobDetail; trigger.StartDelay = TimeSpan.FromMilliseconds(1); trigger.RepeatInterval = TimeSpan.FromMilliseconds(500); - trigger.RepeatCount = (1); + trigger.RepeatCount = 1; trigger.AfterPropertiesSet(); SchedulerFactoryObject factoryObject = new SchedulerFactoryObject(); - factoryObject.JobFactory = (new SpringObjectJobFactory()); - factoryObject.Triggers = (new ITrigger[] {trigger}); - factoryObject.JobDetails = (new IJobDetail[] {jobDetail}); + factoryObject.JobFactory = new SpringObjectJobFactory(); + factoryObject.Triggers = new ITrigger[] {trigger}; + factoryObject.JobDetails = new IJobDetail[] {jobDetail}; factoryObject.AfterPropertiesSet(); factoryObject.Start(); @@ -773,7 +785,7 @@ public void TestSchedulerWithSpringObjectJobFactoryAndQuartzJobObject() } /// - /// + /// /// [Test] public void TestSchedulerWithSpringObjectJobFactoryAndJobSchedulingData() @@ -902,7 +914,7 @@ public void TestSchedulerAutoStartupFalse() context.RegisterObjectDefinition("scheduler", beanDefinition.ObjectDefinition); IScheduler scheduler = (IScheduler) context.GetObject("scheduler", typeof(IScheduler)); - + Assert.IsFalse(scheduler.IsStarted); context.Refresh(); Assert.IsFalse(scheduler.IsStarted); @@ -987,7 +999,7 @@ public void SchedulerStarted() public void SchedulerStarting() { - + } public void SchedulerShutdown() @@ -1090,7 +1102,7 @@ public void SetParam(int value) param = value; } - /// + /// /// Execute the actual job. The job data map will already have been /// applied as object property values by execute. The contract is /// exactly the same as for the standard Quartz execute method. diff --git a/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/SchedulerFactoryObjectTest.cs b/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/SchedulerFactoryObjectTest.cs index 6500725ad..e8fe16076 100644 --- a/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/SchedulerFactoryObjectTest.cs +++ b/test/Spring/Spring.Scheduling.Quartz2.Tests/Scheduling/Quartz/SchedulerFactoryObjectTest.cs @@ -1,12 +1,12 @@ /* * Copyright 2002-2010 the original author or authors. -* +* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -* +* * http://www.apache.org/licenses/LICENSE-2.0 -* +* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,13 +21,15 @@ using System.IO; using System.Reflection; using System.Text; + +using FakeItEasy; + using NUnit.Framework; using Quartz; using Quartz.Impl; using Quartz.Impl.Triggers; using Quartz.Spi; -using Rhino.Mocks; using Spring.Core.IO; @@ -53,7 +55,7 @@ public void SetUp() factory = new SchedulerFactoryObject(); TestSchedulerFactory.Initialize(); - TestSchedulerFactory.MockScheduler.Stub(x => x.SchedulerName).Return("scheduler").Repeat.Any(); + A.CallTo(() => TestSchedulerFactory.MockScheduler.SchedulerName).Returns("scheduler"); } /// @@ -71,7 +73,7 @@ public void TestAfterPropertiesSet_Defaults() [Test] public void TestAfterPropertiesSet_NullJobFactory() { - factory.JobFactory = null; + factory.JobFactory = null; factory.AfterPropertiesSet(); } @@ -81,14 +83,11 @@ public void TestAfterPropertiesSet_NullJobFactory() [Test] public void TestAfterPropertiesSet_NoAutoStartup() { - // set expectations - TestSchedulerFactory.MockScheduler.JobFactory = null; - factory.SchedulerFactoryType = typeof(TestSchedulerFactory); factory.AutoStartup = false; factory.AfterPropertiesSet(); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.JobFactory = null); + A.CallTo(() => TestSchedulerFactory.MockScheduler.Start()).MustNotHaveHappened(); } /// @@ -100,14 +99,14 @@ public void TestAfterPropertiesSet_Calendars() InitForAfterPropertiesSetTest(); const string calendarName = "calendar"; - ICalendar cal = MockRepository.GenerateMock(); + ICalendar cal = A.Fake(); Hashtable calTable = new Hashtable(); calTable[calendarName] = cal; factory.Calendars = calTable; factory.AfterPropertiesSet(); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.AddCalendar(calendarName, cal, true, true)); + A.CallTo(() => TestSchedulerFactory.MockScheduler.AddCalendar(calendarName, cal, true, true)).MustHaveHappened(); } /// @@ -123,7 +122,7 @@ public void TestAfterPropertiesSet_Trigger_TriggerExists() SimpleTriggerImpl trigger = new SimpleTriggerImpl(TRIGGER_NAME, TRIGGER_GROUP); factory.Triggers = new ITrigger[] { trigger }; - TestSchedulerFactory.MockScheduler.Stub(x => x.GetTrigger(new TriggerKey(TRIGGER_NAME, TRIGGER_GROUP))).Return(trigger); + A.CallTo(() => TestSchedulerFactory.MockScheduler.GetTrigger(new TriggerKey(TRIGGER_NAME, TRIGGER_GROUP))).Returns(trigger); factory.AfterPropertiesSet(); } @@ -135,6 +134,7 @@ public void TestAfterPropertiesSet_Trigger_TriggerExists() public void TestAfterPropertiesSet_Trigger_TriggerDoesntExist() { InitForAfterPropertiesSetTest(); + A.CallTo(() => TestSchedulerFactory.MockScheduler.GetTrigger(A._)).Returns(null); const string TRIGGER_NAME = "trigName"; const string TRIGGER_GROUP = "trigGroup"; @@ -143,7 +143,7 @@ public void TestAfterPropertiesSet_Trigger_TriggerDoesntExist() factory.AfterPropertiesSet(); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.ScheduleJob(trigger)); + A.CallTo(() => TestSchedulerFactory.MockScheduler.ScheduleJob(trigger)).MustHaveHappened(); } @@ -166,8 +166,12 @@ public void TestStart() factory.AfterPropertiesSet(); factory.Start(); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.JobFactory = Arg.Is.NotNull); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.Start()); + A.CallTo(TestSchedulerFactory.MockScheduler) + .Where(x => x.Method.Name.Equals("set_JobFactory")) + .WhenArgumentsMatch(x => x.Get(0) != null) + .MustHaveHappened(); + + A.CallTo(() => TestSchedulerFactory.MockScheduler.Start()).MustHaveHappened(); } /// @@ -181,8 +185,12 @@ public void TestStop() factory.AfterPropertiesSet(); factory.Stop(); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.JobFactory = Arg.Is.NotNull); - TestSchedulerFactory.MockScheduler.AssertWasCalled(x => x.Standby()); + A.CallTo(TestSchedulerFactory.MockScheduler) + .Where(x => x.Method.Name.Equals("set_JobFactory")) + .WhenArgumentsMatch(x => x.Get(0) != null) + .MustHaveHappened(); + + A.CallTo(() => TestSchedulerFactory.MockScheduler.Standby()).MustHaveHappened(); } /// @@ -251,7 +259,7 @@ public void TestInitSchedulerFactory_ConfigLocationReadingShouldPreserverExtraEq InterceptingStdSChedulerFactory factoryToPass = new InterceptingStdSChedulerFactory(); factory.ConfigLocation = new TestConfigLocation(ms, "description"); - + m_InitSchedulerFactory.Invoke(factory, new object[] { factoryToPass }); Assert.AreEqual(ConnectionStringValue, factoryToPass.Properties[ConnectionStringKey]); @@ -307,7 +315,7 @@ public ICollection AllSchedulers public static void Initialize() { - mockScheduler = MockRepository.GenerateMock(); + mockScheduler = A.Fake(); } } diff --git a/test/Spring/Spring.Scheduling.Quartz2.Tests/Spring.Scheduling.Quartz2.Tests.2010.csproj b/test/Spring/Spring.Scheduling.Quartz2.Tests/Spring.Scheduling.Quartz2.Tests.2010.csproj index fae729442..1265de89a 100644 --- a/test/Spring/Spring.Scheduling.Quartz2.Tests/Spring.Scheduling.Quartz2.Tests.2010.csproj +++ b/test/Spring/Spring.Scheduling.Quartz2.Tests/Spring.Scheduling.Quartz2.Tests.2010.csproj @@ -8,10 +8,11 @@ + + - diff --git a/test/Spring/Spring.Services.Tests/Data/Spring/WindowsService/Cassini/wwwroot/bin/Cassini.dll b/test/Spring/Spring.Services.Tests/Data/Spring/WindowsService/Cassini/wwwroot/bin/Cassini.dll deleted file mode 100644 index 60ca15b0f..000000000 Binary files a/test/Spring/Spring.Services.Tests/Data/Spring/WindowsService/Cassini/wwwroot/bin/Cassini.dll and /dev/null differ diff --git a/test/Spring/Spring.Services.Tests/Remoting/SaoExporterTests.cs b/test/Spring/Spring.Services.Tests/Remoting/SaoExporterTests.cs index 1dde98096..4e6f99af5 100644 --- a/test/Spring/Spring.Services.Tests/Remoting/SaoExporterTests.cs +++ b/test/Spring/Spring.Services.Tests/Remoting/SaoExporterTests.cs @@ -21,8 +21,10 @@ #region Imports using System; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Core.IO; using Spring.Objects.Factory; @@ -96,20 +98,18 @@ public void ExportSingleCall() } /// - /// Checks that we can also export if IFactoryObject.ObjectType returns an interface type, + /// Checks that we can also export if IFactoryObject.ObjectType returns an interface type, /// [Test(Description = "http://jira.springframework.org/browse/SPRNET-1251")] public void CanExportFromFactoryObjectIfObjectTypeIsInterface() { using (DefaultListableObjectFactory of = new DefaultListableObjectFactory()) { - MockRepository mocks = new MockRepository(); - IFactoryObject simpleCounterFactory = (IFactoryObject) mocks.DynamicMock(typeof (IFactoryObject)); - Expect.Call(simpleCounterFactory.ObjectType).Return(typeof (ISimpleCounter)); - Expect.Call(simpleCounterFactory.IsSingleton).Return(true); - Expect.Call(simpleCounterFactory.GetObject()).Return(new SimpleCounter()); + IFactoryObject simpleCounterFactory = A.Fake(); + A.CallTo(() => simpleCounterFactory.ObjectType).Returns(typeof (ISimpleCounter)); + A.CallTo(() => simpleCounterFactory.IsSingleton).Returns(true); + A.CallTo(() => simpleCounterFactory.GetObject()).Returns(new SimpleCounter()); - mocks.ReplayAll(); of.RegisterSingleton("simpleCounter", simpleCounterFactory); SaoExporter saoExporter = new SaoExporter(); @@ -120,13 +120,11 @@ public void CanExportFromFactoryObjectIfObjectTypeIsInterface() of.RegisterSingleton("simpleCounterExporter", saoExporter); // also tests SaoExporter.Dispose()! AssertExportedService(saoExporter.ServiceName, 2); - - mocks.VerifyAll(); } } /// - /// Checks that exp an IFactoryObject.ObjectType returns an interface type, + /// Checks that exp an IFactoryObject.ObjectType returns an interface type, /// [Test(Description = "http://jira.springframework.org/browse/SPRNET-1251")] public void ThrowsTypeLoadExceptionIfProxyInterfacesValueIsSpecifiedInsteadOfListElement() @@ -136,10 +134,10 @@ public void ThrowsTypeLoadExceptionIfProxyInterfacesValueIsSpecifiedInsteadOfLis XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(of); reader.LoadObjectDefinitions(new StringResource( @" - - + + - + diff --git a/test/Spring/Spring.Services.Tests/Spring.Services.Tests.2010.csproj b/test/Spring/Spring.Services.Tests/Spring.Services.Tests.2010.csproj index 82fab49a0..57032d29a 100644 --- a/test/Spring/Spring.Services.Tests/Spring.Services.Tests.2010.csproj +++ b/test/Spring/Spring.Services.Tests/Spring.Services.Tests.2010.csproj @@ -10,11 +10,12 @@ + + - diff --git a/test/Spring/Spring.Testing.NUnit.Tests/Spring.Testing.NUnit.Tests.2010.csproj b/test/Spring/Spring.Testing.NUnit.Tests/Spring.Testing.NUnit.Tests.2010.csproj index 1158e5639..2e663efc1 100644 --- a/test/Spring/Spring.Testing.NUnit.Tests/Spring.Testing.NUnit.Tests.2010.csproj +++ b/test/Spring/Spring.Testing.NUnit.Tests/Spring.Testing.NUnit.Tests.2010.csproj @@ -10,9 +10,10 @@ + + - diff --git a/test/Spring/Spring.Testing.NUnit.Tests/Testing/Ado/SimpleAdoTestUtilsTests.cs b/test/Spring/Spring.Testing.NUnit.Tests/Testing/Ado/SimpleAdoTestUtilsTests.cs index 2e8d0e23f..8ff11eeb0 100644 --- a/test/Spring/Spring.Testing.NUnit.Tests/Testing/Ado/SimpleAdoTestUtilsTests.cs +++ b/test/Spring/Spring.Testing.NUnit.Tests/Testing/Ado/SimpleAdoTestUtilsTests.cs @@ -19,8 +19,11 @@ #endregion using System.Data; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Core.IO; using Spring.Data; using Spring.Data.Common; @@ -35,14 +38,12 @@ namespace Spring.Testing.Ado [TestFixture] public class SimpleAdoTestUtilsTests { - private MockRepository mocks; private IAdoOperations adoTemplate; [SetUp] public void SetUp() { - mocks = new MockRepository(); - adoTemplate = mocks.StrictMock(); + adoTemplate = A.Fake(); } [Test] @@ -50,10 +51,7 @@ public void ExecuteEmptyScript() { IResource scriptResource = new StringResource(""); - mocks.ReplayAll(); - SimpleAdoTestUtils.ExecuteSqlScript(adoTemplate, scriptResource, false, SimpleAdoTestUtils.BLOCKDELIM_GO_EXP); - mocks.VerifyAll(); } [Test] @@ -61,11 +59,8 @@ public void ExecuteSingleStatement() { IResource scriptResource = new StringResource("statement 1"); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "statement 1")).Return(0); - mocks.ReplayAll(); - SimpleAdoTestUtils.ExecuteSqlScript(adoTemplate, scriptResource, false, SimpleAdoTestUtils.BLOCKDELIM_GO_EXP); - mocks.VerifyAll(); + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "statement 1")).MustHaveHappened(); } [Test] @@ -73,12 +68,11 @@ public void ExecuteScriptWithMissingSeparatorOnLastBlock() { IResource scriptResource = new StringResource("\tstatement 1 \n\n\t GO\t \n statement 2"); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "\tstatement 1 \n")).Return(0); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "\n statement 2")).Return(0); - mocks.ReplayAll(); - SimpleAdoTestUtils.ExecuteSqlScript(adoTemplate, scriptResource, false, SimpleAdoTestUtils.BLOCKDELIM_GO_EXP); - mocks.VerifyAll(); + + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "\tstatement 1 \n")).MustHaveHappened(); + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "\n statement 2")). MustHaveHappened(); + } [Test] @@ -86,12 +80,10 @@ public void ExecuteScriptWithGOBlocks() { IResource scriptResource = new StringResource("\tstatement 1 \n\n\t GO\t \n statement 2\nGO"); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "\tstatement 1 \n")).Return(0); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "\n statement 2\n")).Return(0); - mocks.ReplayAll(); + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "\tstatement 1 \n")).Returns(0); + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "\n statement 2\n")).Returns(0); SimpleAdoTestUtils.ExecuteSqlScript(adoTemplate, scriptResource, false, SimpleAdoTestUtils.BLOCKDELIM_GO_EXP); - mocks.VerifyAll(); } [Test] @@ -99,65 +91,62 @@ public void ExecuteScriptWithSemicolonSeparatedStatements() { IResource scriptResource = new StringResource("\tstatement 1 ;\nGO\n statement 2;"); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "\tstatement 1 ")).Return(0); - Expect.Call(adoTemplate.ExecuteNonQuery(CommandType.Text, "\nGO\n statement 2")).Return(0); - mocks.ReplayAll(); + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "\tstatement 1 ")).Returns(0); + A.CallTo(() => adoTemplate.ExecuteNonQuery(CommandType.Text, "\nGO\n statement 2")).Returns(0); SimpleAdoTestUtils.ExecuteSqlScript(adoTemplate, scriptResource, false, SimpleAdoTestUtils.BLOCKDELIM_SEMICOLON_EXP); - mocks.VerifyAll(); } [Test] public void ExecuteScriptTransactedSuccess() { - IDbProvider dbProvider = (IDbProvider) mocks.DynamicMock(typeof(IDbProvider)); - IDbConnection dbConnection = mocks.StrictMock(); - IDbTransaction dbTx = mocks.StrictMock(); - IDbCommand dbCommand = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection dbConnection = A.Fake(); + IDbTransaction dbTx = A.Fake(); + IDbCommand dbCommand = A.Fake(); DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition(); - Expect.Call(dbProvider.CreateConnection()).Return(dbConnection); - dbConnection.Open(); - Expect.Call(dbConnection.BeginTransaction(txDefinition.TransactionIsolationLevel)).Return(dbTx); - Expect.Call(dbProvider.CreateCommand()).Return(dbCommand); - dbCommand.Connection = dbConnection; - dbCommand.Transaction = dbTx; - dbCommand.CommandText = "simple sql cmd"; - dbCommand.CommandType = CommandType.Text; - Expect.Call(dbCommand.ExecuteNonQuery()).Return(0); - dbTx.Commit(); - dbCommand.Dispose(); - dbConnection.Dispose(); - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(dbConnection); + A.CallTo(() => dbConnection.BeginTransaction(txDefinition.TransactionIsolationLevel)).Returns(dbTx); + A.CallTo(() => dbProvider.CreateCommand()).Returns(dbCommand); + A.CallTo(() => dbCommand.ExecuteNonQuery()).Returns(0); AdoTemplate adoOps = new AdoTemplate(dbProvider); IPlatformTransaction tx = SimpleAdoTestUtils.CreateTransaction(dbProvider, txDefinition); SimpleAdoTestUtils.ExecuteSqlScript(adoOps, "simple sql cmd"); tx.Commit(); - tx.Dispose(); - mocks.VerifyAll(); + tx.Dispose(); + + A.CallTo(() => dbConnection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => dbTx.Commit()).MustHaveHappenedOnceExactly(); + A.CallTo(() => dbCommand.Dispose()).MustHaveHappenedOnceExactly(); + A.CallTo(() => dbConnection.Dispose()).MustHaveHappenedOnceExactly(); + + A.CallToSet(() => dbCommand.Connection).WhenArgumentsMatch(x => x[0] == dbConnection).MustHaveHappenedOnceExactly(); + A.CallToSet(() => dbCommand.Transaction).WhenArgumentsMatch(x => x[0] == dbTx).MustHaveHappenedOnceExactly(); + A.CallToSet(() => dbCommand.CommandText).WhenArgumentsMatch(x => (string) x[0] == "simple sql cmd").MustHaveHappenedOnceExactly(); + A.CallToSet(() => dbCommand.CommandType).WhenArgumentsMatch(x => (CommandType) x[0] == CommandType.Text).MustHaveHappenedOnceExactly(); } [Test] public void ExecuteScriptTransactedRollsbackIfNoCommit() { - IDbProvider dbProvider = mocks.StrictMock(); - IDbConnection dbConnection = mocks.StrictMock(); - IDbTransaction dbTx = mocks.StrictMock(); + IDbProvider dbProvider = A.Fake(); + IDbConnection dbConnection = A.Fake(); + IDbTransaction dbTx = A.Fake(); DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition(); - Expect.Call(dbProvider.CreateConnection()).Return(dbConnection); - dbConnection.Open(); - Expect.Call(dbConnection.BeginTransaction(txDefinition.TransactionIsolationLevel)).Return(dbTx); - dbTx.Rollback(); - dbConnection.Dispose(); - mocks.ReplayAll(); + A.CallTo(() => dbProvider.CreateConnection()).Returns(dbConnection); + A.CallTo(() => dbConnection.BeginTransaction(txDefinition.TransactionIsolationLevel)).Returns(dbTx); AdoTemplate adoOps = new AdoTemplate(dbProvider); IPlatformTransaction tx = SimpleAdoTestUtils.CreateTransaction(dbProvider, txDefinition); tx.Dispose(); - mocks.VerifyAll(); + + A.CallTo(() => dbConnection.Open()).MustHaveHappenedOnceExactly(); + A.CallTo(() => dbTx.Rollback()).MustHaveHappenedOnceExactly(); + A.CallTo(() => dbConnection.Dispose()).MustHaveHappenedOnceExactly(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Web.Tests/Caching/AspNetCacheTests.cs b/test/Spring/Spring.Web.Tests/Caching/AspNetCacheTests.cs index e1c062e8d..f86970fec 100644 --- a/test/Spring/Spring.Web.Tests/Caching/AspNetCacheTests.cs +++ b/test/Spring/Spring.Web.Tests/Caching/AspNetCacheTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright � 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,14 @@ #endregion -#region Imports - using System; using System.Collections; using System.Web; using System.Web.Caching; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Caching { @@ -43,7 +41,6 @@ public class AspNetCacheTests private readonly Cache aspCache = HttpRuntime.Cache; private readonly TimeSpan ttl10Seconds = new TimeSpan(0, 0, 10); - MockRepository mocks; AspNetCache.IRuntimeCache mockedRuntimeCache; AspNetCache mockedCache; @@ -59,31 +56,24 @@ public void SetUp() thisCache = new AspNetCache(); otherCache = new AspNetCache(); - mocks = new MockRepository(); - mockedRuntimeCache = (AspNetCache.IRuntimeCache)mocks.CreateMock(typeof(AspNetCache.IRuntimeCache)); + mockedRuntimeCache = A.Fake(); mockedCache = new AspNetCache(mockedRuntimeCache); } [Test] public void Get() { - // set expectations - Expect.Call(mockedRuntimeCache.Get(mockedCache.GenerateKey("key"))).Return(null); - mocks.ReplayAll(); - // verify mockedCache.Get("key"); - mocks.VerifyAll(); + + A.CallTo(() => mockedRuntimeCache.Get(mockedCache.GenerateKey("key"))).MustHaveHappened(); } [Test] public void Remove() { - // set expectations - Expect.Call(mockedRuntimeCache.Remove(mockedCache.GenerateKey("key"))).Return(null); - mocks.ReplayAll(); - // verify mockedCache.Remove("key"); - mocks.VerifyAll(); + + A.CallTo(() => mockedRuntimeCache.Remove(mockedCache.GenerateKey("key"))).MustHaveHappened(); } [Test] @@ -107,7 +97,7 @@ public void IgnoreNullKeysOnRemove() [Test] public void ReturnsOnlyKeysOwnedByCache() { - DictionaryEntry[] mockedRuntimeCacheEntries = + DictionaryEntry[] mockedRuntimeCacheEntries = { new DictionaryEntry(mockedCache.GenerateKey("keyA"), null) , new DictionaryEntry(mockedCache.GenerateKey("keyB"), null) @@ -115,13 +105,10 @@ public void ReturnsOnlyKeysOwnedByCache() , new DictionaryEntry(otherCache.GenerateKey("keyD"), null) }; - // set expectations - Expect.Call(mockedRuntimeCache.GetEnumerator()).Return(mockedRuntimeCacheEntries.GetEnumerator()); - mocks.ReplayAll(); - // verify + A.CallTo(() => mockedRuntimeCache.GetEnumerator()).Returns(mockedRuntimeCacheEntries.GetEnumerator()); + ICollection keys = mockedCache.Keys; CollectionAssert.AreEqual(new string[] { "keyA", "keyB" }, keys); - mocks.VerifyAll(); } [Test] @@ -170,8 +157,7 @@ public void DifferentCacheNamesCauseSameKeyToBeDifferent() [Test] public void PassesParametersToRuntimeCache() { - MockRepository mocks = new MockRepository(); - AspNetCache.IRuntimeCache runtimeCache = (AspNetCache.IRuntimeCache) mocks.CreateMock(typeof(AspNetCache.IRuntimeCache)); + AspNetCache.IRuntimeCache runtimeCache = A.Fake(); AspNetCache cache = new AspNetCache(runtimeCache); DateTime expectedAbsoluteExpiration = DateTime.Now; @@ -180,34 +166,26 @@ public void PassesParametersToRuntimeCache() // TODO: find way to test non-sliding expiration case // runtimeCache.Insert(cache.GenerateKey("key"), "value", null, DateTime.Now.Add(ttl10Seconds), Cache.NoSlidingExpiration, expectedPriority, null); - runtimeCache.Insert(cache.GenerateKey("key"), "value", null, Cache.NoAbsoluteExpiration, ttl10Seconds, expectedPriority, null); - - mocks.ReplayAll(); // cache.Insert( "key", "value", ttl10Seconds, false, expectedPriority ); cache.Insert("key", "value", ttl10Seconds, true, expectedPriority); - mocks.VerifyAll(); + A.CallTo(() => runtimeCache.Insert(cache.GenerateKey("key"), "value", null, Cache.NoAbsoluteExpiration, ttl10Seconds, expectedPriority, null)).MustHaveHappened(); } [Test] public void ZeroTTLCausesNoExpiration() { - MockRepository mocks = new MockRepository(); - AspNetCache.IRuntimeCache runtimeCache = (AspNetCache.IRuntimeCache)mocks.CreateMock(typeof(AspNetCache.IRuntimeCache)); + AspNetCache.IRuntimeCache runtimeCache = A.Fake(); AspNetCache cache = new AspNetCache(runtimeCache); CacheItemPriority expectedPriority = CacheItemPriority.Low; - runtimeCache.Insert(cache.GenerateKey("key"), "value", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, expectedPriority, null); - runtimeCache.Insert(cache.GenerateKey("key"), "value", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, expectedPriority, null); - - mocks.ReplayAll(); - cache.Insert("key", "value", TimeSpan.Zero, true, expectedPriority); - cache.Insert("key", "value", TimeSpan.Zero, false, expectedPriority); + A.CallTo(() => runtimeCache.Insert(cache.GenerateKey("key"), "value", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, expectedPriority, null)).MustHaveHappened(); - mocks.VerifyAll(); + cache.Insert("key", "value", TimeSpan.Zero, false, expectedPriority); + A.CallTo(() => runtimeCache.Insert(cache.GenerateKey("key"), "value", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, expectedPriority, null)).MustHaveHappened(); } } } \ No newline at end of file diff --git a/test/Spring/Spring.Web.Tests/Spring.Web.Tests.2010.csproj b/test/Spring/Spring.Web.Tests/Spring.Web.Tests.2010.csproj index a56988724..54da618c9 100644 --- a/test/Spring/Spring.Web.Tests/Spring.Web.Tests.2010.csproj +++ b/test/Spring/Spring.Web.Tests/Spring.Web.Tests.2010.csproj @@ -8,10 +8,11 @@ + + - diff --git a/test/Spring/Spring.Web.Tests/Web/Support/AbstractHandlerFactoryTests.cs b/test/Spring/Spring.Web.Tests/Web/Support/AbstractHandlerFactoryTests.cs index ad4106c25..51e93b046 100644 --- a/test/Spring/Spring.Web.Tests/Web/Support/AbstractHandlerFactoryTests.cs +++ b/test/Spring/Spring.Web.Tests/Web/Support/AbstractHandlerFactoryTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,21 +18,20 @@ #endregion -#region Imports - using System; using System.Web; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Context; using Spring.Objects.Factory.Support; -#endregion - namespace Spring.Web.Support { /// - /// + /// /// /// Erich Eichinger [TestFixture] @@ -125,17 +124,13 @@ protected override IApplicationContext GetContext( string virtualPath ) [Test] public void GetCheckedApplicationContextThrowsExceptionsOnNonConfigurableContexts() { - MockRepository mocks = new MockRepository(); - TestHandlerFactory f = (TestHandlerFactory) mocks.PartialMock(typeof(TestHandlerFactory)); - IApplicationContext simpleAppContext = (IApplicationContext) mocks.DynamicMock(typeof(IApplicationContext)); - IConfigurableApplicationContext allowedAppContext = (IConfigurableApplicationContext) mocks.DynamicMock(typeof(IConfigurableApplicationContext)); + TestHandlerFactory f = A.Fake(options => options.CallsBaseMethods()); + IApplicationContext simpleAppContext = A.Fake(); + IConfigurableApplicationContext allowedAppContext = A.Fake(); - using(Record(mocks)) - { - Expect.Call(f.GetContextStub("/NullContext")).Return(null); - Expect.Call(f.GetContextStub("/NonConfigurableContext")).Return(simpleAppContext); - Expect.Call(f.GetContextStub("/AllowedContext")).Return(allowedAppContext); - } + A.CallTo(() => f.GetContextStub("/NullContext")).Returns(null); + A.CallTo(() => f.GetContextStub("/NonConfigurableContext")).Returns(simpleAppContext); + A.CallTo(() => f.GetContextStub("/AllowedContext")).Returns(allowedAppContext); // (context == null) -> ArgumentException try @@ -144,7 +139,8 @@ public void GetCheckedApplicationContextThrowsExceptionsOnNonConfigurableContext Assert.Fail("should throw ArgumentException"); } catch (ArgumentException) - {} + { + } // !(context is IConfigurableApplicationContext) -> InvalidOperationException try @@ -153,7 +149,8 @@ public void GetCheckedApplicationContextThrowsExceptionsOnNonConfigurableContext Assert.Fail("should throw InvalidOperationException"); } catch (InvalidOperationException) - {} + { + } // (context is IConfigurableApplicationContext) -> OK Assert.AreSame(allowedAppContext, f.GetCheckedApplicationContext("/AllowedContext")); @@ -162,66 +159,40 @@ public void GetCheckedApplicationContextThrowsExceptionsOnNonConfigurableContext [Test] public void CachesReusableHandlers() { - MockRepository mocks = new MockRepository(); - TestHandlerFactory f = (TestHandlerFactory) mocks.PartialMock(typeof(TestHandlerFactory)); - IHttpHandler reusableHandler = (IHttpHandler) mocks.DynamicMock(typeof(IHttpHandler)); - IConfigurableApplicationContext appCtx = (IConfigurableApplicationContext) mocks.DynamicMock(typeof(IConfigurableApplicationContext)); + TestHandlerFactory f = A.Fake(options => options.CallsBaseMethods()); + IHttpHandler reusableHandler = A.Fake(); + IConfigurableApplicationContext appCtx = A.Fake(); - // if (IHttpHandler.IsReusable == true) => always returns the same handler instance + // if (IHttpHandler.IsReusable == true) => always returns the same handler instance // - CreateHandlerInstance() is only called once - using(Record(mocks)) - { - Expect.Call(reusableHandler.IsReusable).Return(true); - Expect.Call(f.GetContextStub("reusable")).Return(appCtx); - Expect.Call(f.CreateHandlerInstanceStub(appCtx, null, null, "reusable", null)).Return(reusableHandler); - } - using (Playback(mocks)) - { - Assert.AreSame( reusableHandler, f.GetHandler( null, null, "reusable", null ) ); - Assert.AreSame( reusableHandler, f.GetHandler( null, null, "reusable", null ) ); - } + A.CallTo(() => reusableHandler.IsReusable).Returns(true); + A.CallTo(() => f.GetContextStub("reusable")).Returns(appCtx); + A.CallTo(() => f.CreateHandlerInstanceStub(appCtx, null, null, "reusable", null)).Returns(reusableHandler); + + Assert.AreSame(reusableHandler, f.GetHandler(null, null, "reusable", null)); + Assert.AreSame(reusableHandler, f.GetHandler(null, null, "reusable", null)); } [Test] public void DoesntCacheNonReusableHandlers() { - MockRepository mocks = new MockRepository(); - TestHandlerFactory f = (TestHandlerFactory) mocks.PartialMock(typeof(TestHandlerFactory)); - IHttpHandler nonReusableHandler = (IHttpHandler) mocks.DynamicMock(typeof(IHttpHandler)); - Expect.Call(nonReusableHandler.IsReusable).Return(false); - IHttpHandler nonReusableHandler2 = (IHttpHandler) mocks.DynamicMock(typeof(IHttpHandler)); - Expect.Call(nonReusableHandler2.IsReusable).Return(false); - IConfigurableApplicationContext appCtx = (IConfigurableApplicationContext) mocks.DynamicMock(typeof(IConfigurableApplicationContext)); - - // if (IHttpHandler.IsReusable == false) => always create new handler instance + TestHandlerFactory f = A.Fake(options => options.CallsBaseMethods()); + IHttpHandler nonReusableHandler = A.Fake(); + A.CallTo(() => nonReusableHandler.IsReusable).Returns(false); + IHttpHandler nonReusableHandler2 = A.Fake(); + A.CallTo(() => nonReusableHandler2.IsReusable).Returns(false); + IConfigurableApplicationContext appCtx = A.Fake(); + + // if (IHttpHandler.IsReusable == false) => always create new handler instance // - CreateHandlerInstance() is called for each request - using(Record(mocks)) - { - Expect.Call(f.GetContextStub("notreusable")).Return(appCtx); - Expect.Call(f.CreateHandlerInstanceStub(appCtx, null, null, "notreusable", null)).Return(nonReusableHandler); - Expect.Call(f.GetContextStub("notreusable")).Return(appCtx); - Expect.Call(f.CreateHandlerInstanceStub(appCtx, null, null, "notreusable", null)).Return(nonReusableHandler2); - } - using (Playback(mocks)) - { - Assert.AreSame( nonReusableHandler, f.GetHandler( null, null, "notreusable", null ) ); - Assert.AreSame( nonReusableHandler2, f.GetHandler( null, null, "notreusable", null ) ); - } - } - #region Rhino.Mocks Compatibility Adapter + A.CallTo(() => f.GetContextStub("notreusable")).Returns(appCtx); + A.CallTo(() => f.CreateHandlerInstanceStub(appCtx, null, null, "notreusable", null)) + .Returns(nonReusableHandler).Once() + .Then.Returns(nonReusableHandler2).Once(); - private static IDisposable Record(MockRepository mocks) - { - return mocks.Record(); + Assert.AreSame(nonReusableHandler, f.GetHandler(null, null, "notreusable", null)); + Assert.AreSame(nonReusableHandler2, f.GetHandler(null, null, "notreusable", null)); } - - private static IDisposable Playback(MockRepository mocks) - { - return mocks.Playback(); - } - - - #endregion Rhino.Mocks Compatibility Adapter } } diff --git a/test/Spring/Spring.Web.Tests/Web/Support/ResultFactoryRegistryTests.cs b/test/Spring/Spring.Web.Tests/Web/Support/ResultFactoryRegistryTests.cs index 766901edc..ce43268e8 100644 --- a/test/Spring/Spring.Web.Tests/Web/Support/ResultFactoryRegistryTests.cs +++ b/test/Spring/Spring.Web.Tests/Web/Support/ResultFactoryRegistryTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,18 +18,16 @@ #endregion -#region Imports - using System; -using NUnit.Framework; -using Rhino.Mocks; -#endregion +using FakeItEasy; + +using NUnit.Framework; namespace Spring.Web.Support { /// - /// + /// /// /// Erich Eichinger [TestFixture] @@ -44,104 +42,56 @@ public void SetUp() [Test] public void SetDefaultFactory() { - MockRepository mocks = new MockRepository(); - IResultFactory resultFactory = (IResultFactory)mocks.CreateMock( typeof( IResultFactory ) ); + IResultFactory resultFactory = A.Fake(); IResultFactory prevFactory = ResultFactoryRegistry.DefaultResultFactory; - Assert.AreSame( prevFactory, ResultFactoryRegistry.SetDefaultFactory( resultFactory ) ); - Assert.AreSame( resultFactory, ResultFactoryRegistry.DefaultResultFactory ); + Assert.AreSame(prevFactory, ResultFactoryRegistry.SetDefaultFactory(resultFactory)); + Assert.AreSame(resultFactory, ResultFactoryRegistry.DefaultResultFactory); // verify default factory is used for unknown result mode - using (Record( mocks )) - { - Expect.Call( resultFactory.CreateResult( null, "resultText" ) ).Return( new Result() ); - Expect.Call( resultFactory.CreateResult( "resultMode", "resultText" ) ).Return( new Result() ); - } + A.CallTo(() => resultFactory.CreateResult(null, "resultText")).Returns(new Result()); + A.CallTo(() => resultFactory.CreateResult("resultMode", "resultText")).Returns(new Result()); - using (Playback( mocks )) - { - ResultFactoryRegistry.CreateResult( "resultText" ); - ResultFactoryRegistry.CreateResult( "resultMode:resultText" ); - } + ResultFactoryRegistry.CreateResult("resultText"); + ResultFactoryRegistry.CreateResult("resultMode:resultText"); } [Test] public void ResultModeValuesHavePredefinedFactories() { - MockRepository mocks = new MockRepository(); - IResultFactory defaultFactory = (IResultFactory)mocks.CreateMock( typeof( IResultFactory ) ); - - ResultFactoryRegistry.SetDefaultFactory( defaultFactory ); - - // verify factory registry knows all ResultModes - using (Record( mocks )) - { - // defaultFactory must never be called! - } + IResultFactory defaultFactory = A.Fake(); + ResultFactoryRegistry.SetDefaultFactory(defaultFactory); - using (Playback( mocks )) + foreach (string resultMode in Enum.GetNames(typeof(ResultMode))) { - foreach (string resultMode in Enum.GetNames( typeof( ResultMode ) )) - { - Assert.IsNotNull( ResultFactoryRegistry.CreateResult( resultMode+":resultText" ) ); - } + Assert.IsNotNull(ResultFactoryRegistry.CreateResult(resultMode + ":resultText")); } } [Test] public void SelectsFactoryByResultMode() { - MockRepository mocks = new MockRepository(); - IResultFactory resultFactory = (IResultFactory)mocks.CreateMock( typeof( IResultFactory ) ); + IResultFactory resultFactory = A.Fake(); - ResultFactoryRegistry.RegisterResultMode( "resultMode", resultFactory ); + ResultFactoryRegistry.RegisterResultMode("resultMode", resultFactory); Result result = new Result(); // verify factory registry does not allow nulls to be returned - using (Record( mocks )) - { - Expect.Call( resultFactory.CreateResult( "resultMode", "resultText" ) ).Return( result ); - } - - using (Playback( mocks )) - { - Assert.AreSame( result, ResultFactoryRegistry.CreateResult( "resultMode:resultText" ) ); - } + A.CallTo(() => resultFactory.CreateResult("resultMode", "resultText")).Returns(result); + Assert.AreSame(result, ResultFactoryRegistry.CreateResult("resultMode:resultText")); } [Test] public void BailsOnNullReturnedFromFactory() { - MockRepository mocks = new MockRepository(); - IResultFactory resultFactory = (IResultFactory) mocks.CreateMock(typeof(IResultFactory)); + IResultFactory resultFactory = A.Fake(); ResultFactoryRegistry.RegisterResultMode("resultMode", resultFactory); // verify factory registry does not allow nulls to be returned - using (Record(mocks)) - { - Expect.Call(resultFactory.CreateResult("resultMode", "resultText")).Return(null); - } - - using (Playback(mocks)) - { - Assert.Throws(() => ResultFactoryRegistry.CreateResult("resultMode:resultText")); - } + A.CallTo(() => resultFactory.CreateResult("resultMode", "resultText")).Returns(null); + Assert.Throws(() => ResultFactoryRegistry.CreateResult("resultMode:resultText")); } - - #region Rhino.Mocks Compatibility Adapter - - private static IDisposable Record( MockRepository mocks ) - { - return mocks.Record(); - } - - private static IDisposable Playback( MockRepository mocks ) - { - return mocks.Playback(); - } - - #endregion Rhino.Mocks Compatibility Adapter } } \ No newline at end of file diff --git a/test/Spring/Spring.Web.Tests/Web/UI/Controls/AbstractValidationControlTests.cs b/test/Spring/Spring.Web.Tests/Web/UI/Controls/AbstractValidationControlTests.cs index b44526a81..d342acca8 100644 --- a/test/Spring/Spring.Web.Tests/Web/UI/Controls/AbstractValidationControlTests.cs +++ b/test/Spring/Spring.Web.Tests/Web/UI/Controls/AbstractValidationControlTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,25 +18,24 @@ #endregion -#region Imports - using System; using System.Collections.Generic; using System.Globalization; using System.Web.UI; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.Context; using Spring.Context.Support; using Spring.Validation; using Spring.Web.UI.Validation; -#endregion - namespace Spring.Web.UI.Controls { /// - /// + /// /// /// Erich Eichinger [TestFixture] @@ -187,8 +186,7 @@ public void ResolveValidationContainerToEnclosingPageRecursively() [Test] public void DefaultsToValidationContainerMessageSource() { - MockRepository mocks = new MockRepository(); - IMessageSource messageSource = (IMessageSource)mocks.DynamicMock(typeof(IMessageSource)); + IMessageSource messageSource = A.Fake(); // IValidationContainer container = (IValidationContainer)mocks.DynamicMock(typeof(IValidationContainer)); Page page = new Page(); @@ -220,7 +218,7 @@ public void DoesNotReadErrorsFromCrossValidationContainerByDefault() // - outerVC // - inBetweenControl1 : IValidationContainer // - innerVC - + Spring.Web.UI.Page page = new Spring.Web.UI.Page(); Spring.Web.UI.UserControl inBetweenControl1 = new Spring.Web.UI.UserControl(); inBetweenControl1.ID = "InBetweenControl1"; @@ -247,7 +245,7 @@ public void CanReadErrorsFromCrossValidationContainerByDefault() // - outerVC // - inBetweenControl1 : IValidationContainer // - innerVC - + Spring.Web.UI.Page page = new Spring.Web.UI.Page(); Spring.Web.UI.UserControl userControl = new Spring.Web.UI.UserControl(); userControl.ID = "userControl"; diff --git a/test/Spring/Spring.Web.Tests/Web/UI/PageTests.cs b/test/Spring/Spring.Web.Tests/Web/UI/PageTests.cs index cff2f2475..87aa41dd5 100644 --- a/test/Spring/Spring.Web.Tests/Web/UI/PageTests.cs +++ b/test/Spring/Spring.Web.Tests/Web/UI/PageTests.cs @@ -18,14 +18,14 @@ #endregion -#region Imports - using System; using System.Globalization; using System.Threading; using System.Web; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; using Spring.Globalization.Resolvers; using Spring.Objects; @@ -33,8 +33,6 @@ using Spring.Validation; using Spring.Web.Support; -#endregion - namespace Spring.Web.UI { /// @@ -150,16 +148,14 @@ public void SetResultThrowsVerboseExceptionOnUnknownResultName() [Test] public void SetResultSelectsCorrectResult() { - MockRepository mocks = new MockRepository(); TestPage page = new TestPage(); - Result theResult = (Result) mocks.CreateMock(typeof (Result)); - theResult.Navigate(page); - mocks.ReplayAll(); + Result theResult = A.Fake(); page.Results.Add( "theResult", theResult ); page.SetResult("theResult"); - mocks.VerifyAll(); + + A.CallTo(() => theResult.Navigate(page)).MustHaveHappened(); } [Test] diff --git a/test/Spring/Spring.Web.Tests/Web/UI/UserControlTests.cs b/test/Spring/Spring.Web.Tests/Web/UI/UserControlTests.cs index 61cf9f2f1..ba09ccfc9 100644 --- a/test/Spring/Spring.Web.Tests/Web/UI/UserControlTests.cs +++ b/test/Spring/Spring.Web.Tests/Web/UI/UserControlTests.cs @@ -1,7 +1,7 @@ #region License /* - * Copyright � 2002-2011 the original author or authors. + * Copyright © 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,23 +18,22 @@ #endregion -#region Imports - using System; using System.Web; using System.Web.UI; + +using FakeItEasy; + using NUnit.Framework; -using Rhino.Mocks; + using Spring.TestSupport; using Spring.Validation; using Spring.Web.Support; -#endregion - namespace Spring.Web.UI { /// - /// + /// /// /// Erich Eichinger [TestFixture] @@ -43,40 +42,28 @@ public class UserControlTests : TestWebContextTests [Test] public void SetResultSelectsCorrectResult() { - MockRepository mocks = new MockRepository(); TestUserControl uc = new TestUserControl(); - Result theResult = (Result)mocks.CreateMock(typeof(Result)); - - using (mocks.Ordered()) - { - theResult.Navigate(uc); - } - mocks.ReplayAll(); + Result theResult = A.Fake(); uc.Results.Add("theResult", theResult); uc.SetResult("theResult"); - mocks.VerifyAll(); + } [Test] public void SetResultBubblesUpHierarchyUntilFirstMatch() { - MockRepository mocks = new MockRepository(); TestUserControl c1 = new TestUserControl(); - Control c11 = new Control(); c1.Controls.Add(c11); + Control c11 = new Control(); + c1.Controls.Add(c11); TestUserControl c111 = new TestUserControl(c11); - Result theResult = (Result)mocks.CreateMock(typeof(Result)); - - using (mocks.Ordered()) - { - // context is the control, that contains matching Result - theResult.Navigate(c1); - } - mocks.ReplayAll(); + Result theResult = A.Fake(); c1.Results.Add("theResult", theResult); c111.SetResult("theResult"); - mocks.VerifyAll(); + + // context is the control, that contains matching Result + A.CallTo(() => theResult.Navigate(c1)).MustHaveHappened(); } [Test] @@ -104,7 +91,7 @@ public void StoresAndLoadsModelUsingModelPersistenceMedium() { TestUserControl tuc = new TestUserControl(); tuc.ModelPersistenceMedium = new DictionaryModelPersistenceMedium(); - tuc.SaveModelToPersistenceMedium( this ); + tuc.SaveModelToPersistenceMedium(this); Assert.AreEqual(this, tuc.LoadModelFromPersistenceMedium()); } }