diff --git a/Rhino.Mocks.Tests/FieldsProblem/FieldProblem_JPBoodhoo.cs b/Rhino.Mocks.Tests/FieldsProblem/FieldProblem_JPBoodhoo.cs new file mode 100644 index 00000000..8d42fbc3 --- /dev/null +++ b/Rhino.Mocks.Tests/FieldsProblem/FieldProblem_JPBoodhoo.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using MbUnit.Framework; + +namespace Rhino.Mocks.Tests.FieldsProblem +{ + public class FieldProblem_JPBoodhoo + { + public class VirtualClass + { + public virtual DateTime virtual_property_public_read_private_write { get; private set; } + public virtual string run_sheet_name { get; set; } + } + + [TestFixture] + public class when_setting_up_a_return_value_for_a_virtual_property_on_a_class_with_a_public_getter_and_private_setter + { + VirtualClass target; + + [SetUp] + public void setup() + { + target = MockRepository.GenerateStub(); + target.Stub(entry_model => entry_model.virtual_property_public_read_private_write).Return(DateTime.Now); + } + + [Test] + public void should_not_throw_the_exception_suggesting_to_assign_the_property_value_directly() + { + target.virtual_property_public_read_private_write.Equals(DateTime.Now); + } + } + } +} \ No newline at end of file diff --git a/Rhino.Mocks.Tests/PartialMockTests.cs b/Rhino.Mocks.Tests/PartialMockTests.cs index 925b3efc..8d2b711c 100644 --- a/Rhino.Mocks.Tests/PartialMockTests.cs +++ b/Rhino.Mocks.Tests/PartialMockTests.cs @@ -1,144 +1,144 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Text; -using System.Windows.Forms; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class PartialMockTests - { - MockRepository mocks; - AbstractClass abs; - - [SetUp] - public void SetUp() - { - mocks = new MockRepository(); - abs = (AbstractClass)mocks.PartialMock(typeof(AbstractClass)); - } - - [Test] - public void AutomaticallCallBaseMethodIfNoExpectationWasSet() - { - mocks.ReplayAll(); - Assert.AreEqual(1, abs.Increment()); - Assert.AreEqual(6, abs.Add(5)); - Assert.AreEqual(6, abs.Count); - mocks.VerifyAll(); - - } - - [Test] - public void CanMockVirtualMethods() - { - Expect.Call(abs.Increment()).Return(5); - Expect.Call(abs.Add(2)).Return(3); - mocks.ReplayAll(); - Assert.AreEqual(5, abs.Increment()); - Assert.AreEqual(3, abs.Add(2)); - Assert.AreEqual(0, abs.Count); - mocks.VerifyAll(); - } - - [Test] - public void CanMockAbstractMethods() - { - Expect.Call(abs.Decrement()).Return(5); - mocks.ReplayAll(); - Assert.AreEqual(5, abs.Decrement()); - Assert.AreEqual(0, abs.Count); - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException), "Can't create a partial mock from an interface")] - public void CantCreatePartialMockFromInterfaces() - { - new MockRepository().PartialMock(typeof(IDemo)); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "AbstractClass.Decrement(); Expected #0, Actual #1.")] - public void CallAnAbstractMethodWithoutSettingExpectation() - { - mocks.ReplayAll(); - abs.Decrement(); - } - - [Test] - public void CanMockWithCtorParams() - { - WithParameters withParameters = mocks.PartialMock(1); - Expect.Call(withParameters.Int).Return(4); - mocks.ReplayAll(); - Assert.AreEqual(4, withParameters.Int); - mocks.VerifyAll(); - } - } - - public abstract class AbstractClass - { - public int Count = 0; - - public virtual int Increment() - { - return ++Count; - } - - public virtual int Add(int n) - { - return Count += n; - } - - public abstract int Decrement(); - } - - public class WithParameters - { - private int i; - - - public WithParameters(int i) - { - this.i = i; - } - - - public virtual int Int - { - get { return i; } - set { i = value; } - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Text; +using System.Windows.Forms; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class PartialMockTests + { + MockRepository mocks; + AbstractClass abs; + + [SetUp] + public void SetUp() + { + mocks = new MockRepository(); + abs = (AbstractClass)mocks.PartialMock(typeof(AbstractClass)); + } + + [Test] + public void AutomaticallCallBaseMethodIfNoExpectationWasSet() + { + mocks.ReplayAll(); + Assert.AreEqual(1, abs.Increment()); + Assert.AreEqual(6, abs.Add(5)); + Assert.AreEqual(6, abs.Count); + mocks.VerifyAll(); + + } + + [Test] + public void CanMockVirtualMethods() + { + Expect.Call(abs.Increment()).Return(5); + Expect.Call(abs.Add(2)).Return(3); + mocks.ReplayAll(); + Assert.AreEqual(5, abs.Increment()); + Assert.AreEqual(3, abs.Add(2)); + Assert.AreEqual(0, abs.Count); + mocks.VerifyAll(); + } + + [Test] + public void CanMockAbstractMethods() + { + Expect.Call(abs.Decrement()).Return(5); + mocks.ReplayAll(); + Assert.AreEqual(5, abs.Decrement()); + Assert.AreEqual(0, abs.Count); + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException), "Can't create a partial mock from an interface")] + public void CantCreatePartialMockFromInterfaces() + { + new MockRepository().PartialMock(typeof(IDemo)); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "AbstractClass.Decrement(); Expected #0, Actual #1.")] + public void CallAnAbstractMethodWithoutSettingExpectation() + { + mocks.ReplayAll(); + abs.Decrement(); + } + + [Test] + public void CanMockWithCtorParams() + { + WithParameters withParameters = mocks.PartialMock(1); + Expect.Call(withParameters.Int).Return(4); + mocks.ReplayAll(); + Assert.AreEqual(4, withParameters.Int); + mocks.VerifyAll(); + } + } + + public abstract class AbstractClass + { + public int Count = 0; + + public virtual int Increment() + { + return ++Count; + } + + public virtual int Add(int n) + { + return Count += n; + } + + public abstract int Decrement(); + } + + public class WithParameters + { + private int i; + + + public WithParameters(int i) + { + this.i = i; + } + + + public virtual int Int + { + get { return i; } + set { i = value; } + } + } +} diff --git a/Rhino.Mocks.Tests/PartialMockTestsAAA.cs b/Rhino.Mocks.Tests/PartialMockTestsAAA.cs index 6e49bd07..d2daa296 100644 --- a/Rhino.Mocks.Tests/PartialMockTestsAAA.cs +++ b/Rhino.Mocks.Tests/PartialMockTestsAAA.cs @@ -1,101 +1,101 @@ -#region license - -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class PartialMockTestsAAA - { - private AbstractClass abs; - - [SetUp] - public void SetUp() - { - abs = (AbstractClass) MockRepository.GeneratePartialMock(typeof (AbstractClass), new Type[] {}); - } - - [Test] - public void AutomaticallCallBaseMethodIfNoExpectationWasSet() - { - Assert.AreEqual(1, abs.Increment()); - Assert.AreEqual(6, abs.Add(5)); - Assert.AreEqual(6, abs.Count); - abs.VerifyAllExpectations(); - } - - [Test] - public void CanMockVirtualMethods() - { - abs.Expect(x => x.Increment()).Return(5); - abs.Expect(x => x.Add(2)).Return(3); - - Assert.AreEqual(5, abs.Increment()); - Assert.AreEqual(3, abs.Add(2)); - Assert.AreEqual(0, abs.Count); - abs.VerifyAllExpectations(); - } - - [Test] - public void CanMockAbstractMethods() - { - abs.Expect(x => x.Decrement()).Return(5); - Assert.AreEqual(5, abs.Decrement()); - Assert.AreEqual(0, abs.Count); - abs.VerifyAllExpectations(); - } - - [Test] - [ExpectedException(typeof (InvalidOperationException), "Can't create a partial mock from an interface")] - public void CantCreatePartialMockFromInterfaces() - { - MockRepository.GeneratePartialMock(); - } - - [Test] - [ExpectedException(typeof (ExpectationViolationException), "AbstractClass.Decrement(); Expected #0, Actual #1.")] - public void CallAnAbstractMethodWithoutSettingExpectation() - { - abs.Decrement(); - } - - [Test] - public void CanMockWithCtorParams() - { - var withParameters = MockRepository.GeneratePartialMock(1); - withParameters.Expect(x => x.Int).Return(4); - Assert.AreEqual(4, withParameters.Int); - withParameters.VerifyAllExpectations(); - } - } +#region license + +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class PartialMockTestsAAA + { + private AbstractClass abs; + + [SetUp] + public void SetUp() + { + abs = (AbstractClass) MockRepository.GeneratePartialMock(typeof (AbstractClass), new Type[] {}); + } + + [Test] + public void AutomaticallCallBaseMethodIfNoExpectationWasSet() + { + Assert.AreEqual(1, abs.Increment()); + Assert.AreEqual(6, abs.Add(5)); + Assert.AreEqual(6, abs.Count); + abs.VerifyAllExpectations(); + } + + [Test] + public void CanMockVirtualMethods() + { + abs.Expect(x => x.Increment()).Return(5); + abs.Expect(x => x.Add(2)).Return(3); + + Assert.AreEqual(5, abs.Increment()); + Assert.AreEqual(3, abs.Add(2)); + Assert.AreEqual(0, abs.Count); + abs.VerifyAllExpectations(); + } + + [Test] + public void CanMockAbstractMethods() + { + abs.Expect(x => x.Decrement()).Return(5); + Assert.AreEqual(5, abs.Decrement()); + Assert.AreEqual(0, abs.Count); + abs.VerifyAllExpectations(); + } + + [Test] + [ExpectedException(typeof (InvalidOperationException), "Can't create a partial mock from an interface")] + public void CantCreatePartialMockFromInterfaces() + { + MockRepository.GeneratePartialMock(); + } + + [Test] + [ExpectedException(typeof (ExpectationViolationException), "AbstractClass.Decrement(); Expected #0, Actual #1.")] + public void CallAnAbstractMethodWithoutSettingExpectation() + { + abs.Decrement(); + } + + [Test] + public void CanMockWithCtorParams() + { + var withParameters = MockRepository.GeneratePartialMock(1); + withParameters.Expect(x => x.Int).Return(4); + Assert.AreEqual(4, withParameters.Int); + withParameters.VerifyAllExpectations(); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/PropertySetterFixture.cs b/Rhino.Mocks.Tests/PropertySetterFixture.cs index 54ffea70..09d395b5 100644 --- a/Rhino.Mocks.Tests/PropertySetterFixture.cs +++ b/Rhino.Mocks.Tests/PropertySetterFixture.cs @@ -1,95 +1,95 @@ -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class PropertySetterFixture - { - [Test] - public void Setter_Expectation_With_Custom_Ignore_Arguments() - { - MockRepository mocks = new MockRepository(); - - IBar bar = mocks.StrictMock(); - - using(mocks.Record()) - { - Expect.Call(bar.Foo).SetPropertyAndIgnoreArgument(); - } - - using(mocks.Playback()) - { - bar.Foo = 2; - } - - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IBar.set_Foo(any); Expected #1, Actual #0.")] - public void Setter_Expectation_Not_Fullfilled() - { - MockRepository mocks = new MockRepository(); - - IBar bar = mocks.StrictMock(); - - using (mocks.Record()) - { - Expect.Call(bar.Foo).SetPropertyAndIgnoreArgument(); - } - - using (mocks.Playback()) - { - } - - mocks.VerifyAll(); - } - - [Test] - public void Setter_Expectation_With_Correct_Argument() - { - MockRepository mocks = new MockRepository(); - - IBar bar = mocks.StrictMock(); - - using (mocks.Record()) - { - Expect.Call(bar.Foo).SetPropertyWithArgument(1); - } - - using (mocks.Playback()) - { - bar.Foo = 1; - } - - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IBar.set_Foo(0); Expected #0, Actual #1.\r\nIBar.set_Foo(1); Expected #1, Actual #0.")] - public void Setter_Expectation_With_Wrong_Argument() - { - MockRepository mocks = new MockRepository(); - - IBar bar = mocks.StrictMock(); - - using (mocks.Record()) - { - Expect.Call(bar.Foo).SetPropertyWithArgument(1); - } - - using (mocks.Playback()) - { - bar.Foo = 0; - } - - mocks.VerifyAll(); - } - } - - public interface IBar - { - int Foo { get; set; } - } +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class PropertySetterFixture + { + [Test] + public void Setter_Expectation_With_Custom_Ignore_Arguments() + { + MockRepository mocks = new MockRepository(); + + IBar bar = mocks.StrictMock(); + + using(mocks.Record()) + { + Expect.Call(bar.Foo).SetPropertyAndIgnoreArgument(); + } + + using(mocks.Playback()) + { + bar.Foo = 2; + } + + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IBar.set_Foo(any); Expected #1, Actual #0.")] + public void Setter_Expectation_Not_Fullfilled() + { + MockRepository mocks = new MockRepository(); + + IBar bar = mocks.StrictMock(); + + using (mocks.Record()) + { + Expect.Call(bar.Foo).SetPropertyAndIgnoreArgument(); + } + + using (mocks.Playback()) + { + } + + mocks.VerifyAll(); + } + + [Test] + public void Setter_Expectation_With_Correct_Argument() + { + MockRepository mocks = new MockRepository(); + + IBar bar = mocks.StrictMock(); + + using (mocks.Record()) + { + Expect.Call(bar.Foo).SetPropertyWithArgument(1); + } + + using (mocks.Playback()) + { + bar.Foo = 1; + } + + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IBar.set_Foo(0); Expected #0, Actual #1.\r\nIBar.set_Foo(1); Expected #1, Actual #0.")] + public void Setter_Expectation_With_Wrong_Argument() + { + MockRepository mocks = new MockRepository(); + + IBar bar = mocks.StrictMock(); + + using (mocks.Record()) + { + Expect.Call(bar.Foo).SetPropertyWithArgument(1); + } + + using (mocks.Playback()) + { + bar.Foo = 0; + } + + mocks.VerifyAll(); + } + } + + public interface IBar + { + int Foo { get; set; } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/RecordReplaySyntax/RecordPlaybackTests.cs b/Rhino.Mocks.Tests/RecordReplaySyntax/RecordPlaybackTests.cs index ebf95c25..592dd234 100644 --- a/Rhino.Mocks.Tests/RecordReplaySyntax/RecordPlaybackTests.cs +++ b/Rhino.Mocks.Tests/RecordReplaySyntax/RecordPlaybackTests.cs @@ -1,105 +1,105 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using MbUnit.Framework; - -namespace Rhino.Mocks.Tests.RecordPlaybackSyntax -{ - [TestFixture] - public class RecordPlaybackTests - { - [Test] - public void CanRecordPlayback() - { - MockRepository mockRepository; - mockRepository = new MockRepository(); - IFoo mockedFoo = mockRepository.StrictMock(); - using (mockRepository.Record()) - { - Expect.Call(mockedFoo.Bar()).Return(42); - } - using (mockRepository.Playback()) - { - Fooz fooz = new Fooz(mockedFoo); - fooz.Barz(); - } - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void PlaybackThrowsOtherExceptionDoesntReport() - { - MockRepository mockRepository; - mockRepository = new MockRepository(); - IFoo mockedFoo = mockRepository.StrictMock(); - using (mockRepository.Record()) - { - Expect.Call(mockedFoo.Bar()).Return(42); - } - using (mockRepository.Playback()) - { - throw new ArgumentException(); - } - } - - [Test] - [ExpectedException(typeof(ArgumentException))] - public void RecordThrowsOtherExceptionDoesntReport() - { - MockRepository mockRepository; - mockRepository = new MockRepository(); - IFoo mockedFoo = mockRepository.StrictMock(); - using (mockRepository.Record()) - { - mockedFoo.Bar();//create expectation but doesn't setup return value - throw new ArgumentException(); - } - } - } - - internal interface IFoo - { - int Bar(); - } - - internal class Fooz - { - private readonly IFoo m_foo; - - public Fooz(IFoo foo) - { - m_foo = foo; - } - - public void Barz() - { - m_foo.Bar(); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using MbUnit.Framework; + +namespace Rhino.Mocks.Tests.RecordPlaybackSyntax +{ + [TestFixture] + public class RecordPlaybackTests + { + [Test] + public void CanRecordPlayback() + { + MockRepository mockRepository; + mockRepository = new MockRepository(); + IFoo mockedFoo = mockRepository.StrictMock(); + using (mockRepository.Record()) + { + Expect.Call(mockedFoo.Bar()).Return(42); + } + using (mockRepository.Playback()) + { + Fooz fooz = new Fooz(mockedFoo); + fooz.Barz(); + } + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void PlaybackThrowsOtherExceptionDoesntReport() + { + MockRepository mockRepository; + mockRepository = new MockRepository(); + IFoo mockedFoo = mockRepository.StrictMock(); + using (mockRepository.Record()) + { + Expect.Call(mockedFoo.Bar()).Return(42); + } + using (mockRepository.Playback()) + { + throw new ArgumentException(); + } + } + + [Test] + [ExpectedException(typeof(ArgumentException))] + public void RecordThrowsOtherExceptionDoesntReport() + { + MockRepository mockRepository; + mockRepository = new MockRepository(); + IFoo mockedFoo = mockRepository.StrictMock(); + using (mockRepository.Record()) + { + mockedFoo.Bar();//create expectation but doesn't setup return value + throw new ArgumentException(); + } + } + } + + internal interface IFoo + { + int Bar(); + } + + internal class Fooz + { + private readonly IFoo m_foo; + + public Fooz(IFoo foo) + { + m_foo = foo; + } + + public void Barz() + { + m_foo.Bar(); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/RecordingMocks.cs b/Rhino.Mocks.Tests/RecordingMocks.cs index 1f212952..06506867 100644 --- a/Rhino.Mocks.Tests/RecordingMocks.cs +++ b/Rhino.Mocks.Tests/RecordingMocks.cs @@ -1,692 +1,692 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -#if DOTNET35 -using System; -using System.Collections.Generic; -using MbUnit.Framework; -using Rhino.Mocks.Constraints; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class RecordingMocks - { - [Test] - public void CanGetMockRepositoryForMock() - { - MockRepository repository = new MockRepository(); - var foo = repository.StrictMock(); - Assert.AreSame(repository, foo.GetMockRepository()); - } - - [Test] - public void CanResetStubAndReuseIt() - { - var foo = MockRepository.GenerateStub(); - - foo.Stub(x => x.bar()).Return("open"); - // several calls to 'foo.bar() - Assert.AreEqual(foo.bar(), "open"); - Assert.AreEqual(foo.bar(), "open"); - - foo.BackToRecord(); - - foo.Stub(x => x.bar()).Return("closed"); - - foo.Replay(); - - // several calls to 'foo.bar() - Assert.AreEqual(foo.bar(), "closed"); - Assert.AreEqual(foo.bar(), "closed"); - } - - - [Test] - public void WhenStubbingWillAllowManyCallsOnTheSameExpectation() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1); - - for (int i = 0; i < 59; i++) - { - Assert.AreEqual(1, foo54.DoSomething()); - } - } - - [Test] - public void WhenStubbingCanSetNumberOfCallsThatWillBeMatched() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1).Repeat.Once(); - foo54.Stub(x => x.DoSomething()).Return(2).Repeat.Once(); - - Assert.AreEqual(1, foo54.DoSomething()); - Assert.AreEqual(2, foo54.DoSomething()); - Assert.AreEqual(0, foo54.DoSomething());// unexpected - } - - [Test] - public void CanAssertOnCountOfCallsMade() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1); - - Assert.AreEqual(1, foo54.DoSomething()); - - foo54.AssertWasCalled(x => x.DoSomething()); - Assert.AreEqual(1, foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething()).Count); - } - - [Test] - public void CanAssertMethodArgumentsNaturally() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.Bar("asd")).Return(1); - - Assert.AreEqual(1, foo54.Bar("asd")); - - foo54.AssertWasCalled(x => x.Bar(Arg.Text.EndsWith("d"))); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "IFoo54.Bar(ends with \"d\"); Expected #1, Actual #0.")] - public void CanAssertMethodArgumentsNaturally_WhenFailed() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.Bar("asdg")).Return(1); - - Assert.AreEqual(1, foo54.Bar("asdg")); - - foo54.AssertWasCalled(x => x.Bar(Arg.Text.EndsWith("d"))); - } - - [Test] - public void WhenCallingMethodWithNoParameters_WillReturnZeroLengthArrayForEachCall() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1); - - Assert.AreEqual(1, foo54.DoSomething()); - - foo54.AssertWasCalled(x => x.DoSomething()); - IList arguments = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething()); - Assert.AreEqual(0, arguments[0].Length); - } - - [Test] - public void WhenCallingMethodWithParameters_WillReturnArgumentsInResultingArray() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.Bar("foo")).Return(1); - - Assert.AreEqual(1, foo54.Bar("foo")); - Assert.AreEqual(0, foo54.Bar("bar")); - - IList arguments = foo54.GetArgumentsForCallsMadeOn(x => x.Bar(Arg.Matches((string s) => true))); - Assert.AreEqual(2, arguments.Count); - Assert.AreEqual("foo", arguments[0][0]); - Assert.AreEqual("bar", arguments[1][0]); - } - - [Test] - public void WhenCallingMethodWithParameters_WillReturnArgumentsInResultingArray_UsingConstraints() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.Bar("foo")).Return(1); - - Assert.AreEqual(1, foo54.Bar("foo")); - Assert.AreEqual(0, foo54.Bar("bar")); - - IList arguments = foo54.GetArgumentsForCallsMadeOn(x => x.Bar(null), o => o.IgnoreArguments()); - Assert.AreEqual(2, arguments.Count); - Assert.AreEqual("foo", arguments[0][0]); - Assert.AreEqual("bar", arguments[1][0]); - } - - [Test] - public void CanUseNonRecordReplayModel_Expect() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Expect(x => x.DoSomething()).Return(1).Repeat.Once(); - mocks.Replay(demo); - Assert.AreEqual(1, demo.DoSomething()); - demo.Expect(x => x.DoSomething()).Return(15).Repeat.Once(); - Assert.AreEqual(15, demo.DoSomething()); - - mocks.VerifyAll(); - } - - [Test] - public void CanUseNonRecordReplayModel_Expect_OnVoidMethod() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Expect(x => x.DoSomethingElse()); - mocks.Replay(demo); - demo.DoSomethingElse(); - mocks.VerifyAll(); - } - - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomethingElse(); Expected #1, Actual #0.")] - public void CanUseNonRecordReplayModel_Expect_OnVoidMethod_WhenMethodNotcall_WillFailTest() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Expect(x => x.DoSomethingElse()); - mocks.Replay(demo); - - mocks.VerifyAll(); - } - - - [Test] - [ExpectedException(typeof(InvalidOperationException), "Method 'IFoo54.DoSomething();' requires a return value or an exception to throw.")] - public void UsingExpectWithoutSettingReturnValueThrows() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Expect(x => x.DoSomething()); - mocks.Replay(demo); - Assert.AreEqual(1, demo.DoSomething()); - } - - [Test] - public void CanUseNonRecordReplayModel_Stub() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Stub(x => x.DoSomething()).Return(1); - - mocks.Replay(demo); - Assert.AreEqual(1, demo.DoSomething()); - } - - [Test] - public void CanUseStubSyntax_WithoutExplicitMockRepository() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1); - - Assert.AreEqual(1, foo54.DoSomething()); - - foo54.AssertWasCalled(x => x.DoSomething()); - } - - [Test] - public void CanUseStubSyntax_WithoutExplicitMockRepository_VerifyMethodWasNotCalled() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1); - - - foo54.AssertWasNotCalled(x => x.DoSomething()); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "Expected that IFoo54.DoSomething(); would not be called, but it was found on the actual calls made on the mocked object.")] - public void CanUseStubSyntax_WithoutExplicitMockRepository_VerifyMethodWasNotCalled_WillThrowIfCalled() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.DoSomething()).Return(1); - - Assert.AreEqual(1, foo54.DoSomething()); - - foo54.AssertWasNotCalled(x => x.DoSomething()); - } - - [Test] - public void CanAssertOnMethodUsingDirectArgumentMatching() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Bar("blah"); - - foo54.AssertWasCalled(x => x.Bar("blah")); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "IFoo54.Bar(\"blah1\"); Expected #1, Actual #0.")] - public void CanAssertOnMethodUsingDirectArgumentMatching_WhenWrongArumentPassed() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Bar("blah"); - - foo54.AssertWasCalled(x => x.Bar("blah1")); - } - - [Test] - public void CanUseExpectSyntax_WithoutExplicitMockRepository() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Expect(x => x.DoSomething()).Return(1); - - Assert.AreEqual(1, foo54.DoSomething()); - - foo54.VerifyAllExpectations(); - } - - [Test] - public void CanUseExpectSyntax_WithoutExplicitMockRepository_UsingConsraints() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Expect(x => x.Bar(null)).Constraints(Text.StartsWith("boo")).Return(1); - - Assert.AreEqual(1, foo54.Bar("boo is a great language")); - - foo54.VerifyAllExpectations(); - } - - [Test] - public void CanExpectOnNumberOfCallsMade() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Expect(x => x.DoSomething()).Repeat.Twice().Return(1); - - foo54.DoSomething(); - foo54.DoSomething(); - - foo54.VerifyAllExpectations(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "IFoo54.DoSomething(); Expected #2, Actual #1.")] - public void CanExpectOnNumberOfCallsMade_WhenRepeatCountNotMet() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Expect(x => x.DoSomething()).Repeat.Twice().Return(1); - - foo54.DoSomething(); - - foo54.VerifyAllExpectations(); - } - - [Test] - public void CanAssertOnNumberOfCallsMade() - { - var foo54 = MockRepository.GenerateMock(); - - - foo54.DoSomething(); - foo54.DoSomething(); - - foo54.AssertWasCalled(x => x.DoSomething(), o => o.Repeat.Twice()); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "IFoo54.DoSomething(); Expected #2, Actual #1.")] - public void CanAssertOnNumberOfCallsMade_WhenRepeatCountNotMet() - { - var foo54 = MockRepository.GenerateMock(); - - - foo54.DoSomething(); - - foo54.AssertWasCalled(x => x.DoSomething(), o => o.Repeat.Twice()); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), @"IFoo54.Bar(starts with ""boo""); Expected #1, Actual #0.")] - public void CanUseExpectSyntax_WithoutExplicitMockRepository_UsingConsraints_WhenViolated() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Expect(x => x.Bar(null)).Constraints(Text.StartsWith("boo")).Return(1); - - Assert.AreEqual(0, foo54.Bar("great test")); - - foo54.VerifyAllExpectations(); - } - - [Test] - public void CanUseStubSyntax_WithoutExplicitMockRepository_UsingConsraints_WhenExpectationNotMatching() - { - var foo54 = MockRepository.GenerateStub(); - - foo54.Stub(x => x.Bar(null)).Constraints(Text.StartsWith("boo")).Return(1); - - Assert.AreEqual(0, foo54.Bar("great test")); - - foo54.VerifyAllExpectations(); - } - - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomething(); Expected #1, Actual #0.")] - public void CanUseExpectSyntax_WithoutExplicitMockRepository_WhenCallIsNotBeingMade() - { - var foo54 = MockRepository.GenerateMock(); - - foo54.Expect(x => x.DoSomething()).Return(1); - - foo54.VerifyAllExpectations(); - } - - - [Test] - public void CanUseNonRecordReplayModel_Stub_OnVoidMethod() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Stub(x => x.DoSomethingElse()).Throw(new InvalidOperationException("foo")); - mocks.Replay(demo); - - try - { - demo.DoSomethingElse(); - Assert.Fail("Should throw"); - } - catch (InvalidOperationException e) - { - Assert.AreEqual("foo", e.Message); - } - } - - [Test] - public void CanUseNonRecordReplayModel_Stub_AndThenVerify() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Stub(x => x.DoSomething()).Return(1); - mocks.Replay(demo); - - Assert.AreEqual(1, demo.DoSomething()); - demo.AssertWasCalled(x => x.DoSomething()); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomething(); Expected #1, Actual #0.")] - public void CanUseNonRecordReplayModel_Stub_AndThenVerify_WhenNotCalled_WillCauseError() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Stub(x => x.DoSomething()).Return(1); - mocks.Replay(demo); - - demo.AssertWasCalled(x => x.DoSomething()); - } - - [Test] - public void CanUseNonRecordReplayModel_Stub_WillNotThrowIfExpectationIsNotMet() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - demo.Stub(x => x.DoSomething()).Return(1); - mocks.Replay(demo); - - mocks.VerifyAll(); - } - - [Test] - public void WhenNoExpectationIsSetup_WillReturnDefaultValues() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - Assert.AreEqual(0, demo.DoSomething()); - } - - [Test] - public void CanAssertOnMethodCall() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - demo.DoSomething(); - - demo.AssertWasCalled(x => x.DoSomething()); - } - - [Test] - public void CanAssertOnMethodCallUsingConstraints() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - demo.Bar("blah baba"); - - demo.AssertWasCalled(x => x.Bar(Arg.Matches((string a) => a.StartsWith("b") && a.Contains("ba")))); - } - - [Test] - public void CanAssertOnPropertyAccess() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - var result = demo.FooBar; - - demo.AssertWasCalled(x => x.FooBar); - } - - [Test] - public void CanAssertOnPropertyAccessWithConstraints() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - var result = demo.FooBar; - result = demo.FooBar; - - demo.AssertWasCalled(x => x.FooBar, o => o.Repeat.Twice()); - } - - [Test] - public void CanAssertNotCalledOnPropertyAccess() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - demo.DoSomething(); - - demo.AssertWasNotCalled(x => x.FooBar); - } - -#if !FOR_NET_2_0 // we can't get the structure from a delegate, as happens on 2.0, so ignore this - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "IFoo54.Bar(a => (a.StartsWith(\"b\") && a.Contains(\"ba\"))); Expected #1, Actual #0.")] - public void CanAssertOnMethodCallUsingConstraints_WhenMethodNotFound() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - mocks.ReplayAll(); - - demo.Bar("yoho"); - - demo.AssertWasCalled(x => x.Bar(Arg.Matches((string a) => a.StartsWith("b") && a.Contains("ba")))); - } -#endif - - [Test] - [ExpectedException(typeof(InvalidOperationException), "The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()")] - public void CannotUseRepeatAny() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.ReplayAll(); - demo.AssertWasCalled(x => x.Bar("a"), o => o.Repeat.Any()); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomething(); Expected #1, Actual #0.")] - public void WillFailVerificationsOfMethod_IfWereNotCalled() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.ReplayAll(); - - demo.AssertWasCalled(x => x.DoSomething()); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomethingElse(); Expected #1, Actual #0.")] - public void WillFailVerificationsOfMethod_IfWereNotCalled_OnVoidMethod() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - - mocks.ReplayAll(); - demo.AssertWasCalled(x => x.DoSomethingElse()); - } - - - [Test] - [ExpectedException(typeof(InvalidOperationException), "You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations")] - public void CanOnlyPassSingleExpectationToVerify() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - demo.AssertWasCalled(x => - { - x.DoSomethingElse(); - x.DoSomethingElse(); - }); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException), "No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call")] - public void WillRaiseErrorIfNoExpectationWasSetup() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(); - mocks.Replay(demo); - - demo.AssertWasCalled(x => { }); - } - - [Test] - public void TypeShouldBeInferredFromMockNotReference() - { - MockRepository mocks = new MockRepository(); - IFoo54 demo = mocks.DynamicMock(0); - - demo.Stub(x => x.DoSomethingElse()); - mocks.Replay(demo); - - demo.DoSomethingElse(); - - demo.AssertWasCalled(x => x.DoSomethingElse()); - } - - [Test] - public void AssertShouldWorkWithoutStub() - { - var mocks = new MockRepository(); - var demo = mocks.DynamicMock(); - mocks.Replay(demo); - demo.DoSomethingElse(); - - demo.AssertWasCalled(x => x.DoSomethingElse()); - } - } - - public interface IFoo54 - { - int DoSomething(); - void DoSomethingElse(); - int Bar(string x); - string bar(); - string FooBar { get; set; } - } - - public class Foo54 : IFoo54 - { - public Foo54(int i) - { - - } - - public virtual int DoSomething() - { - return 0; - } - - public virtual void DoSomethingElse() - { - } - - public virtual int Bar(string x) - { - return 0; - } - - #region IFoo54 Members - - public string bar() - { - return null; - } - - public string FooBar { get; set; } - - #endregion - } -} -#endif +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +#if DOTNET35 +using System; +using System.Collections.Generic; +using MbUnit.Framework; +using Rhino.Mocks.Constraints; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class RecordingMocks + { + [Test] + public void CanGetMockRepositoryForMock() + { + MockRepository repository = new MockRepository(); + var foo = repository.StrictMock(); + Assert.AreSame(repository, foo.GetMockRepository()); + } + + [Test] + public void CanResetStubAndReuseIt() + { + var foo = MockRepository.GenerateStub(); + + foo.Stub(x => x.bar()).Return("open"); + // several calls to 'foo.bar() + Assert.AreEqual(foo.bar(), "open"); + Assert.AreEqual(foo.bar(), "open"); + + foo.BackToRecord(); + + foo.Stub(x => x.bar()).Return("closed"); + + foo.Replay(); + + // several calls to 'foo.bar() + Assert.AreEqual(foo.bar(), "closed"); + Assert.AreEqual(foo.bar(), "closed"); + } + + + [Test] + public void WhenStubbingWillAllowManyCallsOnTheSameExpectation() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1); + + for (int i = 0; i < 59; i++) + { + Assert.AreEqual(1, foo54.DoSomething()); + } + } + + [Test] + public void WhenStubbingCanSetNumberOfCallsThatWillBeMatched() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1).Repeat.Once(); + foo54.Stub(x => x.DoSomething()).Return(2).Repeat.Once(); + + Assert.AreEqual(1, foo54.DoSomething()); + Assert.AreEqual(2, foo54.DoSomething()); + Assert.AreEqual(0, foo54.DoSomething());// unexpected + } + + [Test] + public void CanAssertOnCountOfCallsMade() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1); + + Assert.AreEqual(1, foo54.DoSomething()); + + foo54.AssertWasCalled(x => x.DoSomething()); + Assert.AreEqual(1, foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething()).Count); + } + + [Test] + public void CanAssertMethodArgumentsNaturally() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.Bar("asd")).Return(1); + + Assert.AreEqual(1, foo54.Bar("asd")); + + foo54.AssertWasCalled(x => x.Bar(Arg.Text.EndsWith("d"))); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "IFoo54.Bar(ends with \"d\"); Expected #1, Actual #0.")] + public void CanAssertMethodArgumentsNaturally_WhenFailed() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.Bar("asdg")).Return(1); + + Assert.AreEqual(1, foo54.Bar("asdg")); + + foo54.AssertWasCalled(x => x.Bar(Arg.Text.EndsWith("d"))); + } + + [Test] + public void WhenCallingMethodWithNoParameters_WillReturnZeroLengthArrayForEachCall() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1); + + Assert.AreEqual(1, foo54.DoSomething()); + + foo54.AssertWasCalled(x => x.DoSomething()); + IList arguments = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething()); + Assert.AreEqual(0, arguments[0].Length); + } + + [Test] + public void WhenCallingMethodWithParameters_WillReturnArgumentsInResultingArray() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.Bar("foo")).Return(1); + + Assert.AreEqual(1, foo54.Bar("foo")); + Assert.AreEqual(0, foo54.Bar("bar")); + + IList arguments = foo54.GetArgumentsForCallsMadeOn(x => x.Bar(Arg.Matches((string s) => true))); + Assert.AreEqual(2, arguments.Count); + Assert.AreEqual("foo", arguments[0][0]); + Assert.AreEqual("bar", arguments[1][0]); + } + + [Test] + public void WhenCallingMethodWithParameters_WillReturnArgumentsInResultingArray_UsingConstraints() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.Bar("foo")).Return(1); + + Assert.AreEqual(1, foo54.Bar("foo")); + Assert.AreEqual(0, foo54.Bar("bar")); + + IList arguments = foo54.GetArgumentsForCallsMadeOn(x => x.Bar(null), o => o.IgnoreArguments()); + Assert.AreEqual(2, arguments.Count); + Assert.AreEqual("foo", arguments[0][0]); + Assert.AreEqual("bar", arguments[1][0]); + } + + [Test] + public void CanUseNonRecordReplayModel_Expect() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Expect(x => x.DoSomething()).Return(1).Repeat.Once(); + mocks.Replay(demo); + Assert.AreEqual(1, demo.DoSomething()); + demo.Expect(x => x.DoSomething()).Return(15).Repeat.Once(); + Assert.AreEqual(15, demo.DoSomething()); + + mocks.VerifyAll(); + } + + [Test] + public void CanUseNonRecordReplayModel_Expect_OnVoidMethod() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Expect(x => x.DoSomethingElse()); + mocks.Replay(demo); + demo.DoSomethingElse(); + mocks.VerifyAll(); + } + + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomethingElse(); Expected #1, Actual #0.")] + public void CanUseNonRecordReplayModel_Expect_OnVoidMethod_WhenMethodNotcall_WillFailTest() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Expect(x => x.DoSomethingElse()); + mocks.Replay(demo); + + mocks.VerifyAll(); + } + + + [Test] + [ExpectedException(typeof(InvalidOperationException), "Method 'IFoo54.DoSomething();' requires a return value or an exception to throw.")] + public void UsingExpectWithoutSettingReturnValueThrows() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Expect(x => x.DoSomething()); + mocks.Replay(demo); + Assert.AreEqual(1, demo.DoSomething()); + } + + [Test] + public void CanUseNonRecordReplayModel_Stub() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Stub(x => x.DoSomething()).Return(1); + + mocks.Replay(demo); + Assert.AreEqual(1, demo.DoSomething()); + } + + [Test] + public void CanUseStubSyntax_WithoutExplicitMockRepository() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1); + + Assert.AreEqual(1, foo54.DoSomething()); + + foo54.AssertWasCalled(x => x.DoSomething()); + } + + [Test] + public void CanUseStubSyntax_WithoutExplicitMockRepository_VerifyMethodWasNotCalled() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1); + + + foo54.AssertWasNotCalled(x => x.DoSomething()); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "Expected that IFoo54.DoSomething(); would not be called, but it was found on the actual calls made on the mocked object.")] + public void CanUseStubSyntax_WithoutExplicitMockRepository_VerifyMethodWasNotCalled_WillThrowIfCalled() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.DoSomething()).Return(1); + + Assert.AreEqual(1, foo54.DoSomething()); + + foo54.AssertWasNotCalled(x => x.DoSomething()); + } + + [Test] + public void CanAssertOnMethodUsingDirectArgumentMatching() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Bar("blah"); + + foo54.AssertWasCalled(x => x.Bar("blah")); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "IFoo54.Bar(\"blah1\"); Expected #1, Actual #0.")] + public void CanAssertOnMethodUsingDirectArgumentMatching_WhenWrongArumentPassed() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Bar("blah"); + + foo54.AssertWasCalled(x => x.Bar("blah1")); + } + + [Test] + public void CanUseExpectSyntax_WithoutExplicitMockRepository() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Expect(x => x.DoSomething()).Return(1); + + Assert.AreEqual(1, foo54.DoSomething()); + + foo54.VerifyAllExpectations(); + } + + [Test] + public void CanUseExpectSyntax_WithoutExplicitMockRepository_UsingConsraints() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Expect(x => x.Bar(null)).Constraints(Text.StartsWith("boo")).Return(1); + + Assert.AreEqual(1, foo54.Bar("boo is a great language")); + + foo54.VerifyAllExpectations(); + } + + [Test] + public void CanExpectOnNumberOfCallsMade() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Expect(x => x.DoSomething()).Repeat.Twice().Return(1); + + foo54.DoSomething(); + foo54.DoSomething(); + + foo54.VerifyAllExpectations(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "IFoo54.DoSomething(); Expected #2, Actual #1.")] + public void CanExpectOnNumberOfCallsMade_WhenRepeatCountNotMet() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Expect(x => x.DoSomething()).Repeat.Twice().Return(1); + + foo54.DoSomething(); + + foo54.VerifyAllExpectations(); + } + + [Test] + public void CanAssertOnNumberOfCallsMade() + { + var foo54 = MockRepository.GenerateMock(); + + + foo54.DoSomething(); + foo54.DoSomething(); + + foo54.AssertWasCalled(x => x.DoSomething(), o => o.Repeat.Twice()); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "IFoo54.DoSomething(); Expected #2, Actual #1.")] + public void CanAssertOnNumberOfCallsMade_WhenRepeatCountNotMet() + { + var foo54 = MockRepository.GenerateMock(); + + + foo54.DoSomething(); + + foo54.AssertWasCalled(x => x.DoSomething(), o => o.Repeat.Twice()); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), @"IFoo54.Bar(starts with ""boo""); Expected #1, Actual #0.")] + public void CanUseExpectSyntax_WithoutExplicitMockRepository_UsingConsraints_WhenViolated() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Expect(x => x.Bar(null)).Constraints(Text.StartsWith("boo")).Return(1); + + Assert.AreEqual(0, foo54.Bar("great test")); + + foo54.VerifyAllExpectations(); + } + + [Test] + public void CanUseStubSyntax_WithoutExplicitMockRepository_UsingConsraints_WhenExpectationNotMatching() + { + var foo54 = MockRepository.GenerateStub(); + + foo54.Stub(x => x.Bar(null)).Constraints(Text.StartsWith("boo")).Return(1); + + Assert.AreEqual(0, foo54.Bar("great test")); + + foo54.VerifyAllExpectations(); + } + + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomething(); Expected #1, Actual #0.")] + public void CanUseExpectSyntax_WithoutExplicitMockRepository_WhenCallIsNotBeingMade() + { + var foo54 = MockRepository.GenerateMock(); + + foo54.Expect(x => x.DoSomething()).Return(1); + + foo54.VerifyAllExpectations(); + } + + + [Test] + public void CanUseNonRecordReplayModel_Stub_OnVoidMethod() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Stub(x => x.DoSomethingElse()).Throw(new InvalidOperationException("foo")); + mocks.Replay(demo); + + try + { + demo.DoSomethingElse(); + Assert.Fail("Should throw"); + } + catch (InvalidOperationException e) + { + Assert.AreEqual("foo", e.Message); + } + } + + [Test] + public void CanUseNonRecordReplayModel_Stub_AndThenVerify() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Stub(x => x.DoSomething()).Return(1); + mocks.Replay(demo); + + Assert.AreEqual(1, demo.DoSomething()); + demo.AssertWasCalled(x => x.DoSomething()); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomething(); Expected #1, Actual #0.")] + public void CanUseNonRecordReplayModel_Stub_AndThenVerify_WhenNotCalled_WillCauseError() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Stub(x => x.DoSomething()).Return(1); + mocks.Replay(demo); + + demo.AssertWasCalled(x => x.DoSomething()); + } + + [Test] + public void CanUseNonRecordReplayModel_Stub_WillNotThrowIfExpectationIsNotMet() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + demo.Stub(x => x.DoSomething()).Return(1); + mocks.Replay(demo); + + mocks.VerifyAll(); + } + + [Test] + public void WhenNoExpectationIsSetup_WillReturnDefaultValues() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + Assert.AreEqual(0, demo.DoSomething()); + } + + [Test] + public void CanAssertOnMethodCall() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + demo.DoSomething(); + + demo.AssertWasCalled(x => x.DoSomething()); + } + + [Test] + public void CanAssertOnMethodCallUsingConstraints() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + demo.Bar("blah baba"); + + demo.AssertWasCalled(x => x.Bar(Arg.Matches((string a) => a.StartsWith("b") && a.Contains("ba")))); + } + + [Test] + public void CanAssertOnPropertyAccess() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + var result = demo.FooBar; + + demo.AssertWasCalled(x => x.FooBar); + } + + [Test] + public void CanAssertOnPropertyAccessWithConstraints() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + var result = demo.FooBar; + result = demo.FooBar; + + demo.AssertWasCalled(x => x.FooBar, o => o.Repeat.Twice()); + } + + [Test] + public void CanAssertNotCalledOnPropertyAccess() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + demo.DoSomething(); + + demo.AssertWasNotCalled(x => x.FooBar); + } + +#if !FOR_NET_2_0 // we can't get the structure from a delegate, as happens on 2.0, so ignore this + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "IFoo54.Bar(a => (a.StartsWith(\"b\") && a.Contains(\"ba\"))); Expected #1, Actual #0.")] + public void CanAssertOnMethodCallUsingConstraints_WhenMethodNotFound() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + mocks.ReplayAll(); + + demo.Bar("yoho"); + + demo.AssertWasCalled(x => x.Bar(Arg.Matches((string a) => a.StartsWith("b") && a.Contains("ba")))); + } +#endif + + [Test] + [ExpectedException(typeof(InvalidOperationException), "The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()")] + public void CannotUseRepeatAny() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.ReplayAll(); + demo.AssertWasCalled(x => x.Bar("a"), o => o.Repeat.Any()); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomething(); Expected #1, Actual #0.")] + public void WillFailVerificationsOfMethod_IfWereNotCalled() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.ReplayAll(); + + demo.AssertWasCalled(x => x.DoSomething()); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IFoo54.DoSomethingElse(); Expected #1, Actual #0.")] + public void WillFailVerificationsOfMethod_IfWereNotCalled_OnVoidMethod() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + + mocks.ReplayAll(); + demo.AssertWasCalled(x => x.DoSomethingElse()); + } + + + [Test] + [ExpectedException(typeof(InvalidOperationException), "You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations")] + public void CanOnlyPassSingleExpectationToVerify() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + demo.AssertWasCalled(x => + { + x.DoSomethingElse(); + x.DoSomethingElse(); + }); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException), "No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call")] + public void WillRaiseErrorIfNoExpectationWasSetup() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(); + mocks.Replay(demo); + + demo.AssertWasCalled(x => { }); + } + + [Test] + public void TypeShouldBeInferredFromMockNotReference() + { + MockRepository mocks = new MockRepository(); + IFoo54 demo = mocks.DynamicMock(0); + + demo.Stub(x => x.DoSomethingElse()); + mocks.Replay(demo); + + demo.DoSomethingElse(); + + demo.AssertWasCalled(x => x.DoSomethingElse()); + } + + [Test] + public void AssertShouldWorkWithoutStub() + { + var mocks = new MockRepository(); + var demo = mocks.DynamicMock(); + mocks.Replay(demo); + demo.DoSomethingElse(); + + demo.AssertWasCalled(x => x.DoSomethingElse()); + } + } + + public interface IFoo54 + { + int DoSomething(); + void DoSomethingElse(); + int Bar(string x); + string bar(); + string FooBar { get; set; } + } + + public class Foo54 : IFoo54 + { + public Foo54(int i) + { + + } + + public virtual int DoSomething() + { + return 0; + } + + public virtual void DoSomethingElse() + { + } + + public virtual int Bar(string x) + { + return 0; + } + + #region IFoo54 Members + + public string bar() + { + return null; + } + + public string FooBar { get; set; } + + #endregion + } +} +#endif diff --git a/Rhino.Mocks.Tests/RecursiveMocks.cs b/Rhino.Mocks.Tests/RecursiveMocks.cs index 842a7561..8723df15 100644 --- a/Rhino.Mocks.Tests/RecursiveMocks.cs +++ b/Rhino.Mocks.Tests/RecursiveMocks.cs @@ -1,122 +1,122 @@ -#if DOTNET35 -using System; -using System.Collections; -using System.Linq; -using MbUnit.Framework; -using Rhino.Mocks.Impl; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class RecursiveMocks - { - [Test] - public void CanUseRecursiveMocks() - { - var session = MockRepository.GenerateMock(); - session.Stub(x => - x.CreateCriteria(typeof (Customer)) - .List() - ).Return(new[] {new Customer {Id = 1, Name = "ayende"}}); - - Customer customer = session.CreateCriteria(typeof (Customer)) - .List() - .Cast() - .First(); - - Assert.AreEqual("ayende", customer.Name); - Assert.AreEqual(1, customer.Id); - } - - [Test] - public void CanUseRecursiveMocksSimpler() - { - var mockService = MockRepository.GenerateMock(); - - mockService.Expect(x => x.Identity.Name).Return("foo"); - - Assert.AreEqual("foo", mockService.Identity.Name); - } - - [Test] - [Ignore("Not supported right now as per Oren")] - public void CanUseRecursiveMocksSimplerAlternateSyntax() - { - var mockService = MockRepository.GenerateMock(); - - Expect.Call(mockService.Identity.Name).Return("foo"); - - Assert.AreEqual("foo", mockService.Identity.Name); - } - - [Test] - [Ignore("Not supported in replay mode")] - public void WillGetSameInstanceOfRecursedMockForGenerateMockStatic() - { - var mock = MockRepository.GenerateMock(); - - IIdentity i1 = mock.Identity; - IIdentity i2 = mock.Identity; - - Assert.AreSame(i1, i2); - Assert.IsNotNull(i1); - } - - [Test] - [Ignore("Not supported in replay mode")] - public void WillGetSameInstanceOfRecursedMockInReplayMode() - { - RhinoMocks.Logger = new TraceWriterExpectationLogger(true, true, true); - - MockRepository mocks = new MockRepository(); - var mock = mocks.DynamicMock(); - mocks.Replay(mock); - - IIdentity i1 = mock.Identity; - IIdentity i2 = mock.Identity; - - Assert.AreSame(i1, i2); - Assert.IsNotNull(i1); - } - - [Test] - public void WillGetSameInstanceOfRecursedMockWhenNotInReplayMode() - { - RhinoMocks.Logger = new TraceWriterExpectationLogger(true,true,true); - - var mock = new MockRepository().DynamicMock(); - - IIdentity i1 = mock.Identity; - IIdentity i2 = mock.Identity; - - Assert.AreSame(i1, i2); - Assert.IsNotNull(i1); - } - - public interface ISession - { - ICriteria CreateCriteria(Type type); - } - - public interface ICriteria - { - IList List(); - } - public class Customer - { - public string Name { get; set; } - public int Id { get; set; } - } - - public interface IIdentity - { - string Name { get; set; } - } - - public interface IMyService - { - IIdentity Identity { get; set; } - } - } -} -#endif +#if DOTNET35 +using System; +using System.Collections; +using System.Linq; +using MbUnit.Framework; +using Rhino.Mocks.Impl; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class RecursiveMocks + { + [Test] + public void CanUseRecursiveMocks() + { + var session = MockRepository.GenerateMock(); + session.Stub(x => + x.CreateCriteria(typeof (Customer)) + .List() + ).Return(new[] {new Customer {Id = 1, Name = "ayende"}}); + + Customer customer = session.CreateCriteria(typeof (Customer)) + .List() + .Cast() + .First(); + + Assert.AreEqual("ayende", customer.Name); + Assert.AreEqual(1, customer.Id); + } + + [Test] + public void CanUseRecursiveMocksSimpler() + { + var mockService = MockRepository.GenerateMock(); + + mockService.Expect(x => x.Identity.Name).Return("foo"); + + Assert.AreEqual("foo", mockService.Identity.Name); + } + + [Test] + [Ignore("Not supported right now as per Oren")] + public void CanUseRecursiveMocksSimplerAlternateSyntax() + { + var mockService = MockRepository.GenerateMock(); + + Expect.Call(mockService.Identity.Name).Return("foo"); + + Assert.AreEqual("foo", mockService.Identity.Name); + } + + [Test] + [Ignore("Not supported in replay mode")] + public void WillGetSameInstanceOfRecursedMockForGenerateMockStatic() + { + var mock = MockRepository.GenerateMock(); + + IIdentity i1 = mock.Identity; + IIdentity i2 = mock.Identity; + + Assert.AreSame(i1, i2); + Assert.IsNotNull(i1); + } + + [Test] + [Ignore("Not supported in replay mode")] + public void WillGetSameInstanceOfRecursedMockInReplayMode() + { + RhinoMocks.Logger = new TraceWriterExpectationLogger(true, true, true); + + MockRepository mocks = new MockRepository(); + var mock = mocks.DynamicMock(); + mocks.Replay(mock); + + IIdentity i1 = mock.Identity; + IIdentity i2 = mock.Identity; + + Assert.AreSame(i1, i2); + Assert.IsNotNull(i1); + } + + [Test] + public void WillGetSameInstanceOfRecursedMockWhenNotInReplayMode() + { + RhinoMocks.Logger = new TraceWriterExpectationLogger(true,true,true); + + var mock = new MockRepository().DynamicMock(); + + IIdentity i1 = mock.Identity; + IIdentity i2 = mock.Identity; + + Assert.AreSame(i1, i2); + Assert.IsNotNull(i1); + } + + public interface ISession + { + ICriteria CreateCriteria(Type type); + } + + public interface ICriteria + { + IList List(); + } + public class Customer + { + public string Name { get; set; } + public int Id { get; set; } + } + + public interface IIdentity + { + string Name { get; set; } + } + + public interface IMyService + { + IIdentity Identity { get; set; } + } + } +} +#endif diff --git a/Rhino.Mocks.Tests/RefOutParameters.cs b/Rhino.Mocks.Tests/RefOutParameters.cs index 81790198..617e8154 100644 --- a/Rhino.Mocks.Tests/RefOutParameters.cs +++ b/Rhino.Mocks.Tests/RefOutParameters.cs @@ -1,99 +1,99 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Text; -using MbUnit.Framework; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class RefOutParameters - { - public class MyClass - { - public virtual void MyMethod(out int i, ref string s, int i1, out string s2) - { - throw new NotImplementedException(); - } - } - - [Test] - public void UseTheOutMethodToSpecifyOutputAndRefParameters() - { - MockRepository mocks = new MockRepository(); - MyClass myClass = (MyClass) mocks.StrictMock(typeof (MyClass)); - int i; - string s = null, s2; - myClass.MyMethod(out i, ref s, 1, out s2); - LastCall.IgnoreArguments().OutRef(100, "s", "b"); - mocks.ReplayAll(); - - myClass.MyMethod(out i, ref s, 1, out s2); - - mocks.VerifyAll(); - - Assert.AreEqual(100, i); - Assert.AreEqual("s", s); - Assert.AreEqual("b", s2); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException), "Output and ref parameters has already been set for this expectation")] - public void UseTheOutMethodToSpecifyOutputAndRefParameters_CanOnlyBeCalledOnce() - { - MockRepository mocks = new MockRepository(); - MyClass myClass = (MyClass) mocks.StrictMock(typeof (MyClass)); - int i; - string s = null, s2; - myClass.MyMethod(out i, ref s, 1, out s2); - LastCall.OutRef(100, "s", "b").OutRef(100, "s", "b"); - } - - [Test] - public void GivingLessParametersThanWhatIsInTheMethodWillNotThrow() - { - MockRepository mocks = new MockRepository(); - MyClass myClass = (MyClass) mocks.StrictMock(typeof (MyClass)); - int i; - string s = null, s2; - myClass.MyMethod(out i, ref s, 1, out s2); - LastCall.IgnoreArguments().OutRef(100); - mocks.ReplayAll(); - - myClass.MyMethod(out i, ref s, 1, out s2); - - mocks.VerifyAll(); - - Assert.AreEqual(100, i); - Assert.IsNull(s); - Assert.IsNull(s2); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Text; +using MbUnit.Framework; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class RefOutParameters + { + public class MyClass + { + public virtual void MyMethod(out int i, ref string s, int i1, out string s2) + { + throw new NotImplementedException(); + } + } + + [Test] + public void UseTheOutMethodToSpecifyOutputAndRefParameters() + { + MockRepository mocks = new MockRepository(); + MyClass myClass = (MyClass) mocks.StrictMock(typeof (MyClass)); + int i; + string s = null, s2; + myClass.MyMethod(out i, ref s, 1, out s2); + LastCall.IgnoreArguments().OutRef(100, "s", "b"); + mocks.ReplayAll(); + + myClass.MyMethod(out i, ref s, 1, out s2); + + mocks.VerifyAll(); + + Assert.AreEqual(100, i); + Assert.AreEqual("s", s); + Assert.AreEqual("b", s2); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException), "Output and ref parameters has already been set for this expectation")] + public void UseTheOutMethodToSpecifyOutputAndRefParameters_CanOnlyBeCalledOnce() + { + MockRepository mocks = new MockRepository(); + MyClass myClass = (MyClass) mocks.StrictMock(typeof (MyClass)); + int i; + string s = null, s2; + myClass.MyMethod(out i, ref s, 1, out s2); + LastCall.OutRef(100, "s", "b").OutRef(100, "s", "b"); + } + + [Test] + public void GivingLessParametersThanWhatIsInTheMethodWillNotThrow() + { + MockRepository mocks = new MockRepository(); + MyClass myClass = (MyClass) mocks.StrictMock(typeof (MyClass)); + int i; + string s = null, s2; + myClass.MyMethod(out i, ref s, 1, out s2); + LastCall.IgnoreArguments().OutRef(100); + mocks.ReplayAll(); + + myClass.MyMethod(out i, ref s, 1, out s2); + + mocks.VerifyAll(); + + Assert.AreEqual(100, i); + Assert.IsNull(s); + Assert.IsNull(s2); + } + } +} diff --git a/Rhino.Mocks.Tests/Remoting/ContextSwitchTests.cs b/Rhino.Mocks.Tests/Remoting/ContextSwitchTests.cs index 6695f605..e4477e33 100644 --- a/Rhino.Mocks.Tests/Remoting/ContextSwitchTests.cs +++ b/Rhino.Mocks.Tests/Remoting/ContextSwitchTests.cs @@ -1,168 +1,168 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.IO; -using System.Reflection; -using System.Security.Permissions; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; -[assembly:EnvironmentPermission(SecurityAction.RequestMinimum)] - - -namespace Rhino.Mocks.Tests.Remoting -{ - - /// - /// Test scenarios where mock objects are called from different - /// application domain. - /// - [TestFixture] - public class ContextSwitchTests - { - private AppDomain otherDomain; - private ContextSwitcher contextSwitcher; - - [TestFixtureSetUp] - public void FixtureSetUp() - { - FileInfo assemblyFile = new FileInfo( - Assembly.GetExecutingAssembly().Location); - - otherDomain = AppDomain.CreateDomain("other domain", null, - AppDomain.CurrentDomain.BaseDirectory, null, false); - - contextSwitcher = (ContextSwitcher)otherDomain.CreateInstanceAndUnwrap( - Assembly.GetExecutingAssembly().GetName().Name, - typeof(ContextSwitcher).FullName); - - } - - - - [TestFixtureTearDown] - public void FixtureTearDown() - { - AppDomain.Unload(otherDomain); - } - - [Test] - public void MockInterface() - { - MockRepository mocks = new MockRepository(); - IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); - Expect.Call(demo.ReturnIntNoArgs()).Return(54); - demo.VoidStringArg("54"); - mocks.ReplayAll(); - contextSwitcher.DoStuff(demo); - mocks.VerifyAll(); - } - - - [Test] - public void MockInterfaceWithSameName() - { - MockRepository mocks = new MockRepository(); - IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); - Expect.Call(demo.ReturnIntNoArgs()).Return(54); - demo.VoidStringArg("54"); - Other.IDemo remotingDemo = (Other.IDemo)mocks.StrictMock(typeof(Other.IDemo)); - remotingDemo.ProcessString("in"); - mocks.ReplayAll(); - contextSwitcher.DoStuff(demo); - contextSwitcher.DoStuff(remotingDemo); - mocks.VerifyAll(); - } - - - - [Test, ExpectedException(typeof(InvalidOperationException), "That was expected.")] - public void MockInterfaceExpectException() - { - MockRepository mocks = new MockRepository(); - IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); - Expect.Call(demo.ReturnIntNoArgs()).Throw(new InvalidOperationException("That was expected.")); - mocks.ReplayAll(); - contextSwitcher.DoStuff(demo); - } - - - - [Test, ExpectedException(typeof(ExpectationViolationException), - "IDemo.VoidStringArg(\"34\"); Expected #0, Actual #1.\r\nIDemo.VoidStringArg(\"bang\"); Expected #1, Actual #0.")] - public void MockInterfaceUnexpectedCall() - { - MockRepository mocks = new MockRepository(); - IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); - Expect.Call(demo.ReturnIntNoArgs()).Return(34); - demo.VoidStringArg("bang"); - mocks.ReplayAll(); - contextSwitcher.DoStuff(demo); - } - - - - [Test] - public void MockClass() - { - MockRepository mocks = new MockRepository(); - RemotableDemoClass demo = (RemotableDemoClass)mocks.StrictMock(typeof(RemotableDemoClass)); - Expect.Call(demo.Two()).Return(44); - mocks.ReplayAll(); - Assert.AreEqual(44, contextSwitcher.DoStuff(demo)); - mocks.VerifyAll(); - } - - - - [Test, ExpectedException(typeof(InvalidOperationException), "That was expected for class.")] - public void MockClassExpectException() - { - MockRepository mocks = new MockRepository(); - RemotableDemoClass demo = (RemotableDemoClass)mocks.StrictMock(typeof(RemotableDemoClass)); - Expect.Call(demo.Two()).Throw(new InvalidOperationException("That was expected for class.")); - mocks.ReplayAll(); - contextSwitcher.DoStuff(demo); - } - - - - [Test, ExpectedException(typeof(ExpectationViolationException), - "RemotableDemoClass.Two(); Expected #0, Actual #1.")] - public void MockClassUnexpectedCall() - { - MockRepository mocks = new MockRepository(); - RemotableDemoClass demo = (RemotableDemoClass)mocks.StrictMock(typeof(RemotableDemoClass)); - Expect.Call(demo.Prop).Return(11); - mocks.ReplayAll(); - contextSwitcher.DoStuff(demo); - } - } - -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.IO; +using System.Reflection; +using System.Security.Permissions; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; +[assembly:EnvironmentPermission(SecurityAction.RequestMinimum)] + + +namespace Rhino.Mocks.Tests.Remoting +{ + + /// + /// Test scenarios where mock objects are called from different + /// application domain. + /// + [TestFixture] + public class ContextSwitchTests + { + private AppDomain otherDomain; + private ContextSwitcher contextSwitcher; + + [TestFixtureSetUp] + public void FixtureSetUp() + { + FileInfo assemblyFile = new FileInfo( + Assembly.GetExecutingAssembly().Location); + + otherDomain = AppDomain.CreateDomain("other domain", null, + AppDomain.CurrentDomain.BaseDirectory, null, false); + + contextSwitcher = (ContextSwitcher)otherDomain.CreateInstanceAndUnwrap( + Assembly.GetExecutingAssembly().GetName().Name, + typeof(ContextSwitcher).FullName); + + } + + + + [TestFixtureTearDown] + public void FixtureTearDown() + { + AppDomain.Unload(otherDomain); + } + + [Test] + public void MockInterface() + { + MockRepository mocks = new MockRepository(); + IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); + Expect.Call(demo.ReturnIntNoArgs()).Return(54); + demo.VoidStringArg("54"); + mocks.ReplayAll(); + contextSwitcher.DoStuff(demo); + mocks.VerifyAll(); + } + + + [Test] + public void MockInterfaceWithSameName() + { + MockRepository mocks = new MockRepository(); + IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); + Expect.Call(demo.ReturnIntNoArgs()).Return(54); + demo.VoidStringArg("54"); + Other.IDemo remotingDemo = (Other.IDemo)mocks.StrictMock(typeof(Other.IDemo)); + remotingDemo.ProcessString("in"); + mocks.ReplayAll(); + contextSwitcher.DoStuff(demo); + contextSwitcher.DoStuff(remotingDemo); + mocks.VerifyAll(); + } + + + + [Test, ExpectedException(typeof(InvalidOperationException), "That was expected.")] + public void MockInterfaceExpectException() + { + MockRepository mocks = new MockRepository(); + IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); + Expect.Call(demo.ReturnIntNoArgs()).Throw(new InvalidOperationException("That was expected.")); + mocks.ReplayAll(); + contextSwitcher.DoStuff(demo); + } + + + + [Test, ExpectedException(typeof(ExpectationViolationException), + "IDemo.VoidStringArg(\"34\"); Expected #0, Actual #1.\r\nIDemo.VoidStringArg(\"bang\"); Expected #1, Actual #0.")] + public void MockInterfaceUnexpectedCall() + { + MockRepository mocks = new MockRepository(); + IDemo demo = (IDemo)mocks.StrictMock(typeof(IDemo)); + Expect.Call(demo.ReturnIntNoArgs()).Return(34); + demo.VoidStringArg("bang"); + mocks.ReplayAll(); + contextSwitcher.DoStuff(demo); + } + + + + [Test] + public void MockClass() + { + MockRepository mocks = new MockRepository(); + RemotableDemoClass demo = (RemotableDemoClass)mocks.StrictMock(typeof(RemotableDemoClass)); + Expect.Call(demo.Two()).Return(44); + mocks.ReplayAll(); + Assert.AreEqual(44, contextSwitcher.DoStuff(demo)); + mocks.VerifyAll(); + } + + + + [Test, ExpectedException(typeof(InvalidOperationException), "That was expected for class.")] + public void MockClassExpectException() + { + MockRepository mocks = new MockRepository(); + RemotableDemoClass demo = (RemotableDemoClass)mocks.StrictMock(typeof(RemotableDemoClass)); + Expect.Call(demo.Two()).Throw(new InvalidOperationException("That was expected for class.")); + mocks.ReplayAll(); + contextSwitcher.DoStuff(demo); + } + + + + [Test, ExpectedException(typeof(ExpectationViolationException), + "RemotableDemoClass.Two(); Expected #0, Actual #1.")] + public void MockClassUnexpectedCall() + { + MockRepository mocks = new MockRepository(); + RemotableDemoClass demo = (RemotableDemoClass)mocks.StrictMock(typeof(RemotableDemoClass)); + Expect.Call(demo.Prop).Return(11); + mocks.ReplayAll(); + contextSwitcher.DoStuff(demo); + } + } + +} diff --git a/Rhino.Mocks.Tests/Remoting/ContextSwitcher.cs b/Rhino.Mocks.Tests/Remoting/ContextSwitcher.cs index ab8f635d..c15b1d62 100644 --- a/Rhino.Mocks.Tests/Remoting/ContextSwitcher.cs +++ b/Rhino.Mocks.Tests/Remoting/ContextSwitcher.cs @@ -1,58 +1,58 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; - -namespace Rhino.Mocks.Tests.Remoting -{ - - public class ContextSwitcher : MarshalByRefObject - { - public void DoStuff(IDemo mock) - { - int n = mock.ReturnIntNoArgs(); - mock.VoidStringArg(n.ToString()); - } - - - - public int DoStuff(RemotableDemoClass mock) - { - return mock.Two(); - } - - - - public void DoStuff(Other.IDemo remotingDemo) - { - remotingDemo.ProcessString("in"); - } - } - -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; + +namespace Rhino.Mocks.Tests.Remoting +{ + + public class ContextSwitcher : MarshalByRefObject + { + public void DoStuff(IDemo mock) + { + int n = mock.ReturnIntNoArgs(); + mock.VoidStringArg(n.ToString()); + } + + + + public int DoStuff(RemotableDemoClass mock) + { + return mock.Two(); + } + + + + public void DoStuff(Other.IDemo remotingDemo) + { + remotingDemo.ProcessString("in"); + } + } + +} diff --git a/Rhino.Mocks.Tests/Remoting/IDemo.cs b/Rhino.Mocks.Tests/Remoting/IDemo.cs index 8422bf1f..cbce04a0 100644 --- a/Rhino.Mocks.Tests/Remoting/IDemo.cs +++ b/Rhino.Mocks.Tests/Remoting/IDemo.cs @@ -1,38 +1,38 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; - -namespace Rhino.Mocks.Tests.Remoting.Other -{ - public interface IDemo - { - void ProcessString(string s); - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; + +namespace Rhino.Mocks.Tests.Remoting.Other +{ + public interface IDemo + { + void ProcessString(string s); + } +} diff --git a/Rhino.Mocks.Tests/Remoting/RemotableDemoClass.cs b/Rhino.Mocks.Tests/Remoting/RemotableDemoClass.cs index 3bec8d0b..27ddf731 100644 --- a/Rhino.Mocks.Tests/Remoting/RemotableDemoClass.cs +++ b/Rhino.Mocks.Tests/Remoting/RemotableDemoClass.cs @@ -1,57 +1,57 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; - -namespace Rhino.Mocks.Tests.Remoting -{ - - [Serializable] - public class RemotableDemoClass - { - int _prop; - - public virtual int Prop - { - get { return _prop; } - set { _prop = value; } - } - - public int One() - { - return 1; - } - - public virtual int Two() - { - return 2; - } - } - -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; + +namespace Rhino.Mocks.Tests.Remoting +{ + + [Serializable] + public class RemotableDemoClass + { + int _prop; + + public virtual int Prop + { + get { return _prop; } + set { _prop = value; } + } + + public int One() + { + return 1; + } + + public virtual int Two() + { + return 2; + } + } + +} diff --git a/Rhino.Mocks.Tests/RemotingMockTests.cs b/Rhino.Mocks.Tests/RemotingMockTests.cs index a7875a43..40624926 100644 --- a/Rhino.Mocks.Tests/RemotingMockTests.cs +++ b/Rhino.Mocks.Tests/RemotingMockTests.cs @@ -1,389 +1,389 @@ -#region license - -// Copyright (c) 2007 Ivan Krivyakov (ivan@ikriv.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class StrictMockTests - { - public class TestClass : MarshalByRefObject - { - public TestClass(string unused) - { - throw new InvalidCastException("Real method should never be called"); - } - - public void Method() - { - throw new InvalidCastException("Real method should never be called"); - } - - public int MethodReturningInt() - { - throw new InvalidCastException("Real method should never be called"); - } - - public string MethodReturningString() - { - throw new InvalidCastException("Real method should never be called"); - } - - public string MethodGettingParameters(int intParam, string stringParam) - { - throw new InvalidCastException("Real method should never be called"); - } - - public void MethodAcceptingTestClass(TestClass other) - { - throw new InvalidCastException("Real method should never be called"); - } - - public int GenericMethod(string parameter) - { - throw new InvalidCastException("Real method should never be called"); - } - - public T GenericMethodReturningGenericType(string parameter) - { - throw new InvalidCastException("Real method should never be called"); - } - - public T GenericMethodWithGenericParam( T parameter ) - { - throw new InvalidCastException("Real method should never be called"); - } - - public string StringProperty - { - get - { - throw new InvalidCastException("Real method should never be called"); - } - set - { - throw new InvalidCastException("Real method should never be called"); - } - } - } - - public class GenericTestClass : MarshalByRefObject - { - public int Method(T parameter) - { - throw new InvalidCastException("Real method should never be called"); - } - - public U GenericMethod(T parameter) - { - throw new InvalidCastException("Real method should never be called"); - } - } - - [Test] - public void CanMockVoidMethod() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - t.Method(); - mocks.ReplayAll(); - t.Method(); - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "TestClass.Method(); Expected #0, Actual #1.")] - public void ThrowOnUnexpectedVoidMethod() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - mocks.ReplayAll(); - t.Method(); - mocks.VerifyAll(); - } - - [Test] - public void CanMockMethodReturningInt() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.MethodReturningInt()).Return(42); - mocks.ReplayAll(); - Assert.AreEqual(42, t.MethodReturningInt()); - mocks.VerifyAll(); - } - - [Test] - public void CanMockMethodReturningString() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.MethodReturningString()).Return("foo"); - mocks.ReplayAll(); - Assert.AreEqual("foo", t.MethodReturningString()); - mocks.VerifyAll(); - } - - [Test] - public void CanMockMethodGettingParameters() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.MethodGettingParameters(42, "foo")).Return("bar"); - mocks.ReplayAll(); - Assert.AreEqual("bar", t.MethodGettingParameters(42, "foo")); - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "TestClass.MethodGettingParameters(19, \"foo\"); Expected #0, Actual #1.\r\nTestClass.MethodGettingParameters(42, \"foo\"); Expected #1, Actual #0.")] - public void CanRejectIncorrectParameters() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.MethodGettingParameters(42, "foo")).Return("bar"); - mocks.ReplayAll(); - Assert.AreEqual("bar", t.MethodGettingParameters(19, "foo")); - mocks.VerifyAll(); - } - - [Test] - public void CanMockPropertyGet() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.StringProperty).Return("foo"); - mocks.ReplayAll(); - Assert.AreEqual("foo", t.StringProperty); - mocks.VerifyAll(); - } - - [Test] - public void CanMockPropertySet() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - t.StringProperty = "foo"; - mocks.ReplayAll(); - t.StringProperty = "foo"; - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), - "TestClass.set_StringProperty(\"bar\"); Expected #0, Actual #1.\r\nTestClass.set_StringProperty(\"foo\"); Expected #1, Actual #0.")] - public void CanRejectIncorrectPropertySet() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - t.StringProperty = "foo"; - mocks.ReplayAll(); - t.StringProperty = "bar"; - mocks.VerifyAll(); - } - - [Test] - public void CanMockGenericClass() - { - MockRepository mocks = new MockRepository(); - GenericTestClass t = (GenericTestClass)mocks.StrictMock(typeof(GenericTestClass)); - Expect.Call(t.Method("foo")).Return(42); - mocks.ReplayAll(); - Assert.AreEqual(42, t.Method("foo")); - mocks.VerifyAll(); - } - - [Test] - public void CanMockGenericMethod() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.GenericMethod("foo")).Return(42); - mocks.ReplayAll(); - Assert.AreEqual(42, t.GenericMethod("foo")); - mocks.VerifyAll(); - } - - [Test,ExpectedException(typeof(ExpectationViolationException), -@"TestClass.GenericMethod(""foo""); Expected #1, Actual #1. -TestClass.GenericMethod(""foo""); Expected #1, Actual #0.")] - public void CanMockGenericMethod_WillErrorOnWrongType() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.GenericMethod("foo")).Return(42); - mocks.ReplayAll(); - Assert.AreEqual(42, t.GenericMethod("foo")); - mocks.VerifyAll(); - } - - [Test] - public void CanMockGenericMethodReturningGenericType() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.GenericMethodReturningGenericType("foo")).Return("bar"); - mocks.ReplayAll(); - Assert.AreEqual("bar", t.GenericMethodReturningGenericType("foo")); - mocks.VerifyAll(); - } - - [Test] - public void CanMockGenericMethodWithGenericParam() - { - MockRepository mocks = new MockRepository(); - TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); - Expect.Call(t.GenericMethodWithGenericParam("foo")).Return("bar"); - mocks.ReplayAll(); - Assert.AreEqual("bar", t.GenericMethodWithGenericParam("foo")); - mocks.VerifyAll(); - } - - [Test] - public void CanMockGenericMethodInGenericClass() - { - MockRepository mocks = new MockRepository(); - GenericTestClass t = mocks.StrictMock>(); - Expect.Call(t.GenericMethod("foo")).Return(42); - mocks.ReplayAll(); - Assert.AreEqual(42, t.GenericMethod("foo")); - mocks.VerifyAll(); - } - - [Test] - public void CanMockAppDomain() - { - MockRepository mocks = new MockRepository(); - AppDomain appDomain = mocks.StrictMock(); - Expect.Call(appDomain.BaseDirectory).Return("/home/user/ayende"); - mocks.ReplayAll(); - Assert.AreEqual(appDomain.BaseDirectory, "/home/user/ayende" ); - mocks.VerifyAll(); - } - - [Test, ExpectedException(typeof(ExpectationViolationException), -@"AppDomain.get_BaseDirectory(); Expected #1, Actual #0.")] - public void NotCallingExpectedMethodWillCauseVerificationError() - { - MockRepository mocks = new MockRepository(); - AppDomain appDomain = mocks.StrictMock(); - Expect.Call(appDomain.BaseDirectory).Return("/home/user/ayende"); - mocks.ReplayAll(); - mocks.VerifyAll(); - } - - [Test] - public void CanMockMethodAcceptingTestClass() - { - MockRepository mocks = new MockRepository(); - TestClass t1 = mocks.StrictMock(); - TestClass t2 = mocks.StrictMock(); - t1.MethodAcceptingTestClass(t2); - mocks.ReplayAll(); - t1.MethodAcceptingTestClass(t2); - mocks.VerifyAll(); - } - - [Test] - // can't use ExpectedException since expected message is dynamic - public void CanMockMethodAcceptingTestClass_WillErrorOnWrongParameter() - { - string t2Text = "@"; - string t3Text = "@"; - - try - { - - MockRepository mocks = new MockRepository(); - TestClass t1 = mocks.StrictMock(); - TestClass t2 = mocks.StrictMock(); - TestClass t3 = mocks.StrictMock(); - t2Text = t2.ToString(); - t3Text = t3.ToString(); - - t1.MethodAcceptingTestClass(t2); - mocks.ReplayAll(); - t1.MethodAcceptingTestClass(t3); - mocks.VerifyAll(); - - Assert.Fail("Expected ExpectationViolationException"); - } - catch (ExpectationViolationException ex) - { - string msg = - String.Format("TestClass.MethodAcceptingTestClass({0}); Expected #0, Actual #1.\r\n" + - "TestClass.MethodAcceptingTestClass({1}); Expected #1, Actual #0.", - t3Text, - t2Text); - - Assert.AreEqual(msg, ex.Message); - } - } - - [Test] - public void StrictMockGetTypeReturnsMockedType() - { - MockRepository mocks = new MockRepository(); - TestClass t = mocks.StrictMock(); - Assert.AreSame(typeof(TestClass), t.GetType()); - } - - [Test] - public void StrictMockGetHashCodeWorks() - { - MockRepository mocks = new MockRepository(); - TestClass t = mocks.StrictMock(); - t.GetHashCode(); - } - - [Test] - public void StrictMockToStringReturnsDescription() - { - MockRepository mocks = new MockRepository(); - TestClass t = mocks.StrictMock(); - int hashCode = t.GetHashCode(); - string toString = t.ToString(); - Assert.AreEqual(String.Format("RemotingMock_{0}", hashCode), toString); - } - - [Test] - public void StrictMockEquality() - { - MockRepository mocks = new MockRepository(); - TestClass t = mocks.StrictMock(); - - Assert.IsFalse(t.Equals(null)); - Assert.IsFalse(t.Equals(42)); - Assert.IsFalse(t.Equals("foo")); - Assert.IsTrue(t.Equals(t)); - } - } -} +#region license + +// Copyright (c) 2007 Ivan Krivyakov (ivan@ikriv.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class StrictMockTests + { + public class TestClass : MarshalByRefObject + { + public TestClass(string unused) + { + throw new InvalidCastException("Real method should never be called"); + } + + public void Method() + { + throw new InvalidCastException("Real method should never be called"); + } + + public int MethodReturningInt() + { + throw new InvalidCastException("Real method should never be called"); + } + + public string MethodReturningString() + { + throw new InvalidCastException("Real method should never be called"); + } + + public string MethodGettingParameters(int intParam, string stringParam) + { + throw new InvalidCastException("Real method should never be called"); + } + + public void MethodAcceptingTestClass(TestClass other) + { + throw new InvalidCastException("Real method should never be called"); + } + + public int GenericMethod(string parameter) + { + throw new InvalidCastException("Real method should never be called"); + } + + public T GenericMethodReturningGenericType(string parameter) + { + throw new InvalidCastException("Real method should never be called"); + } + + public T GenericMethodWithGenericParam( T parameter ) + { + throw new InvalidCastException("Real method should never be called"); + } + + public string StringProperty + { + get + { + throw new InvalidCastException("Real method should never be called"); + } + set + { + throw new InvalidCastException("Real method should never be called"); + } + } + } + + public class GenericTestClass : MarshalByRefObject + { + public int Method(T parameter) + { + throw new InvalidCastException("Real method should never be called"); + } + + public U GenericMethod(T parameter) + { + throw new InvalidCastException("Real method should never be called"); + } + } + + [Test] + public void CanMockVoidMethod() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + t.Method(); + mocks.ReplayAll(); + t.Method(); + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "TestClass.Method(); Expected #0, Actual #1.")] + public void ThrowOnUnexpectedVoidMethod() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + mocks.ReplayAll(); + t.Method(); + mocks.VerifyAll(); + } + + [Test] + public void CanMockMethodReturningInt() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.MethodReturningInt()).Return(42); + mocks.ReplayAll(); + Assert.AreEqual(42, t.MethodReturningInt()); + mocks.VerifyAll(); + } + + [Test] + public void CanMockMethodReturningString() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.MethodReturningString()).Return("foo"); + mocks.ReplayAll(); + Assert.AreEqual("foo", t.MethodReturningString()); + mocks.VerifyAll(); + } + + [Test] + public void CanMockMethodGettingParameters() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.MethodGettingParameters(42, "foo")).Return("bar"); + mocks.ReplayAll(); + Assert.AreEqual("bar", t.MethodGettingParameters(42, "foo")); + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "TestClass.MethodGettingParameters(19, \"foo\"); Expected #0, Actual #1.\r\nTestClass.MethodGettingParameters(42, \"foo\"); Expected #1, Actual #0.")] + public void CanRejectIncorrectParameters() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.MethodGettingParameters(42, "foo")).Return("bar"); + mocks.ReplayAll(); + Assert.AreEqual("bar", t.MethodGettingParameters(19, "foo")); + mocks.VerifyAll(); + } + + [Test] + public void CanMockPropertyGet() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.StringProperty).Return("foo"); + mocks.ReplayAll(); + Assert.AreEqual("foo", t.StringProperty); + mocks.VerifyAll(); + } + + [Test] + public void CanMockPropertySet() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + t.StringProperty = "foo"; + mocks.ReplayAll(); + t.StringProperty = "foo"; + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), + "TestClass.set_StringProperty(\"bar\"); Expected #0, Actual #1.\r\nTestClass.set_StringProperty(\"foo\"); Expected #1, Actual #0.")] + public void CanRejectIncorrectPropertySet() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + t.StringProperty = "foo"; + mocks.ReplayAll(); + t.StringProperty = "bar"; + mocks.VerifyAll(); + } + + [Test] + public void CanMockGenericClass() + { + MockRepository mocks = new MockRepository(); + GenericTestClass t = (GenericTestClass)mocks.StrictMock(typeof(GenericTestClass)); + Expect.Call(t.Method("foo")).Return(42); + mocks.ReplayAll(); + Assert.AreEqual(42, t.Method("foo")); + mocks.VerifyAll(); + } + + [Test] + public void CanMockGenericMethod() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.GenericMethod("foo")).Return(42); + mocks.ReplayAll(); + Assert.AreEqual(42, t.GenericMethod("foo")); + mocks.VerifyAll(); + } + + [Test,ExpectedException(typeof(ExpectationViolationException), +@"TestClass.GenericMethod(""foo""); Expected #1, Actual #1. +TestClass.GenericMethod(""foo""); Expected #1, Actual #0.")] + public void CanMockGenericMethod_WillErrorOnWrongType() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.GenericMethod("foo")).Return(42); + mocks.ReplayAll(); + Assert.AreEqual(42, t.GenericMethod("foo")); + mocks.VerifyAll(); + } + + [Test] + public void CanMockGenericMethodReturningGenericType() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.GenericMethodReturningGenericType("foo")).Return("bar"); + mocks.ReplayAll(); + Assert.AreEqual("bar", t.GenericMethodReturningGenericType("foo")); + mocks.VerifyAll(); + } + + [Test] + public void CanMockGenericMethodWithGenericParam() + { + MockRepository mocks = new MockRepository(); + TestClass t = (TestClass)mocks.StrictMock(typeof(TestClass)); + Expect.Call(t.GenericMethodWithGenericParam("foo")).Return("bar"); + mocks.ReplayAll(); + Assert.AreEqual("bar", t.GenericMethodWithGenericParam("foo")); + mocks.VerifyAll(); + } + + [Test] + public void CanMockGenericMethodInGenericClass() + { + MockRepository mocks = new MockRepository(); + GenericTestClass t = mocks.StrictMock>(); + Expect.Call(t.GenericMethod("foo")).Return(42); + mocks.ReplayAll(); + Assert.AreEqual(42, t.GenericMethod("foo")); + mocks.VerifyAll(); + } + + [Test] + public void CanMockAppDomain() + { + MockRepository mocks = new MockRepository(); + AppDomain appDomain = mocks.StrictMock(); + Expect.Call(appDomain.BaseDirectory).Return("/home/user/ayende"); + mocks.ReplayAll(); + Assert.AreEqual(appDomain.BaseDirectory, "/home/user/ayende" ); + mocks.VerifyAll(); + } + + [Test, ExpectedException(typeof(ExpectationViolationException), +@"AppDomain.get_BaseDirectory(); Expected #1, Actual #0.")] + public void NotCallingExpectedMethodWillCauseVerificationError() + { + MockRepository mocks = new MockRepository(); + AppDomain appDomain = mocks.StrictMock(); + Expect.Call(appDomain.BaseDirectory).Return("/home/user/ayende"); + mocks.ReplayAll(); + mocks.VerifyAll(); + } + + [Test] + public void CanMockMethodAcceptingTestClass() + { + MockRepository mocks = new MockRepository(); + TestClass t1 = mocks.StrictMock(); + TestClass t2 = mocks.StrictMock(); + t1.MethodAcceptingTestClass(t2); + mocks.ReplayAll(); + t1.MethodAcceptingTestClass(t2); + mocks.VerifyAll(); + } + + [Test] + // can't use ExpectedException since expected message is dynamic + public void CanMockMethodAcceptingTestClass_WillErrorOnWrongParameter() + { + string t2Text = "@"; + string t3Text = "@"; + + try + { + + MockRepository mocks = new MockRepository(); + TestClass t1 = mocks.StrictMock(); + TestClass t2 = mocks.StrictMock(); + TestClass t3 = mocks.StrictMock(); + t2Text = t2.ToString(); + t3Text = t3.ToString(); + + t1.MethodAcceptingTestClass(t2); + mocks.ReplayAll(); + t1.MethodAcceptingTestClass(t3); + mocks.VerifyAll(); + + Assert.Fail("Expected ExpectationViolationException"); + } + catch (ExpectationViolationException ex) + { + string msg = + String.Format("TestClass.MethodAcceptingTestClass({0}); Expected #0, Actual #1.\r\n" + + "TestClass.MethodAcceptingTestClass({1}); Expected #1, Actual #0.", + t3Text, + t2Text); + + Assert.AreEqual(msg, ex.Message); + } + } + + [Test] + public void StrictMockGetTypeReturnsMockedType() + { + MockRepository mocks = new MockRepository(); + TestClass t = mocks.StrictMock(); + Assert.AreSame(typeof(TestClass), t.GetType()); + } + + [Test] + public void StrictMockGetHashCodeWorks() + { + MockRepository mocks = new MockRepository(); + TestClass t = mocks.StrictMock(); + t.GetHashCode(); + } + + [Test] + public void StrictMockToStringReturnsDescription() + { + MockRepository mocks = new MockRepository(); + TestClass t = mocks.StrictMock(); + int hashCode = t.GetHashCode(); + string toString = t.ToString(); + Assert.AreEqual(String.Format("RemotingMock_{0}", hashCode), toString); + } + + [Test] + public void StrictMockEquality() + { + MockRepository mocks = new MockRepository(); + TestClass t = mocks.StrictMock(); + + Assert.IsFalse(t.Equals(null)); + Assert.IsFalse(t.Equals(42)); + Assert.IsFalse(t.Equals("foo")); + Assert.IsTrue(t.Equals(t)); + } + } +} diff --git a/Rhino.Mocks.Tests/Rhino.Mocks.Tests 2.0.csproj b/Rhino.Mocks.Tests/Rhino.Mocks.Tests 2.0.csproj index c16c583a..d0b5a6ce 100644 --- a/Rhino.Mocks.Tests/Rhino.Mocks.Tests 2.0.csproj +++ b/Rhino.Mocks.Tests/Rhino.Mocks.Tests 2.0.csproj @@ -1,405 +1,405 @@ - - - Local - 8.0.50727 - 2.0 - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20} - Debug - AnyCPU - Rhino.Mocks.Tests - JScript - Grid - IE50 - false - Library - Rhino.Mocks.Tests - OnBuildSuccess - true - ..\..\ayende-open-source.snk - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - bin\debug\ - false - 285212672 - false - TRACE;DEBUG;dotNet2 - true - 4096 - false - false - false - false - false - 4 - false - Full - - - ..\..\Build\Tests\Release\ - false - 285212672 - false - TRACE;dotNet2 - false - 4096 - false - true - false - false - false - 4 - - - Program - C:\Program Files\MbUnit\MbUnit.GUI.exe - D:\OSS\rhino-tools\rhino-mocks\Rhino.Mocks.Tests\bin\debug\Rhino.Mocks.Tests.dll - - - Auto - AnyCPU - - - - False - ..\..\SharedLibs\Castle\Castle.Core.dll - - - False - ..\..\SharedLibs\Castle\Castle.DynamicProxy2.dll - - - False - ..\..\SharedLibs\Tools\MbUnit\MbUnit.Framework.dll - - - False - ..\Rhino.Mocks.CPP.Interfaces\Rhino.Mocks.CPP.Interfaces.dll - - - System - - - System.Data - - - System.EnterpriseServices - - - System.Web - - - - System.XML - - - - - - - Code - - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - - - - - - - Component - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - - Code - - - - - - - - - - - - - - Code - - - Code - - - - - - - - - - Code - - - Code - - - - - Rhino.Mocks - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} - {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - {2A75196C-D9EB-4129-B803-931327F72D5C} - 2 - 8 - 0 - tlbimp - False - - - {3050F1C5-98B5-11CF-BB82-00AA00BDCE0B} - 4 - 0 - 0 - tlbimp - False - - - {420B2830-E718-11CF-893D-00A0C9054228} - 1 - 0 - 0 - tlbimp - False - - - - - - - - ayende-open-source.snk - - - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - + + + Local + 8.0.50727 + 2.0 + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20} + Debug + AnyCPU + Rhino.Mocks.Tests + JScript + Grid + IE50 + false + Library + Rhino.Mocks.Tests + OnBuildSuccess + true + ..\..\ayende-open-source.snk + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + bin\debug\ + false + 285212672 + false + TRACE;DEBUG;dotNet2 + true + 4096 + false + false + false + false + false + 4 + false + Full + + + ..\..\Build\Tests\Release\ + false + 285212672 + false + TRACE;dotNet2 + false + 4096 + false + true + false + false + false + 4 + + + Program + C:\Program Files\MbUnit\MbUnit.GUI.exe + D:\OSS\rhino-tools\rhino-mocks\Rhino.Mocks.Tests\bin\debug\Rhino.Mocks.Tests.dll + + + Auto + AnyCPU + + + + False + ..\..\SharedLibs\Castle\Castle.Core.dll + + + False + ..\..\SharedLibs\Castle\Castle.DynamicProxy2.dll + + + False + ..\..\SharedLibs\Tools\MbUnit\MbUnit.Framework.dll + + + False + ..\Rhino.Mocks.CPP.Interfaces\Rhino.Mocks.CPP.Interfaces.dll + + + System + + + System.Data + + + System.EnterpriseServices + + + System.Web + + + + System.XML + + + + + + + Code + + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + + + + + + + Component + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + + Code + + + + + + + + + + + + + + Code + + + Code + + + + + + + + + + Code + + + Code + + + + + Rhino.Mocks + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + {2A75196C-D9EB-4129-B803-931327F72D5C} + 2 + 8 + 0 + tlbimp + False + + + {3050F1C5-98B5-11CF-BB82-00AA00BDCE0B} + 4 + 0 + 0 + tlbimp + False + + + {420B2830-E718-11CF-893D-00A0C9054228} + 1 + 0 + 0 + tlbimp + False + + + + + + + + ayende-open-source.snk + + + + + False + .NET Framework 2.0 %28x86%29 + true + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + false + + + \ No newline at end of file diff --git a/Rhino.Mocks.Tests/Rhino.Mocks.Tests.csproj b/Rhino.Mocks.Tests/Rhino.Mocks.Tests.csproj index f800731e..670d6a1a 100644 --- a/Rhino.Mocks.Tests/Rhino.Mocks.Tests.csproj +++ b/Rhino.Mocks.Tests/Rhino.Mocks.Tests.csproj @@ -1,448 +1,449 @@ - - - Local - 9.0.30729 - 2.0 - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20} - Debug - AnyCPU - Rhino.Mocks.Tests - JScript - Grid - IE50 - false - Library - Rhino.Mocks.Tests - OnBuildSuccess - true - ..\ayende-open-source.snk - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - v3.5 - - - bin\debug\ - false - 285212672 - false - TRACE;DEBUG;DOTNET35 - true - 4096 - false - false - false - false - false - 4 - false - Full - - - ..\..\Build\Tests\Release\ - false - 285212672 - false - TRACE;dotNet2 - false - 4096 - false - true - false - false - false - 4 - - - Program - C:\Program Files\MbUnit\MbUnit.GUI.exe - D:\OSS\rhino-tools\rhino-mocks\Rhino.Mocks.Tests\bin\debug\Rhino.Mocks.Tests.dll - - - Auto - AnyCPU - - - - False - ..\SharedLibs\Castle.Core.dll - - - False - ..\SharedLibs\Castle.DynamicProxy2.dll - - - False - ..\SharedLibs\Interop.ADODB.dll - - - False - ..\SharedLibs\Interop.MSHTML.dll - - - False - ..\SharedLibs\MbUnit.Framework.dll - - - False - ..\SharedLibs\Microsoft.Practices.Unity.dll - - - False - ..\SharedLibs\Rhino.Mocks.CPP.Interfaces.dll - - - False - ..\SharedLibs\Scripting.dll - - - System - - - - 3.5 - - - System.Data - - - System.EnterpriseServices - - - 3.0 - - - System.Web - - - - System.XML - - - - - - Code - - - - Code - - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - Component - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - - Code - - - - - - - - - - - - - - - - - - Code - - - Code - - - - - - - - - - - - Code - - - Code - - - - - {3078B943-10A5-41FA-A68A-7C4FC98506A0} - Rhino.Mocks.Tests.Model - - - Rhino.Mocks - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} - {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - - - - - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - - - ayende-open-source.snk - - - + + + Local + 9.0.30729 + 2.0 + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20} + Debug + AnyCPU + Rhino.Mocks.Tests + JScript + Grid + IE50 + false + Library + Rhino.Mocks.Tests + OnBuildSuccess + true + ..\ayende-open-source.snk + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + v3.5 + + + bin\debug\ + false + 285212672 + false + TRACE;DEBUG;DOTNET35 + true + 4096 + false + false + false + false + false + 4 + false + Full + + + ..\..\Build\Tests\Release\ + false + 285212672 + false + TRACE;dotNet2 + false + 4096 + false + true + false + false + false + 4 + + + Program + C:\Program Files\MbUnit\MbUnit.GUI.exe + D:\OSS\rhino-tools\rhino-mocks\Rhino.Mocks.Tests\bin\debug\Rhino.Mocks.Tests.dll + + + Auto + AnyCPU + + + + False + ..\SharedLibs\Castle.Core.dll + + + False + ..\SharedLibs\Castle.DynamicProxy2.dll + + + False + ..\SharedLibs\Interop.ADODB.dll + + + False + ..\SharedLibs\Interop.MSHTML.dll + + + False + ..\SharedLibs\MbUnit.Framework.dll + + + False + ..\SharedLibs\Microsoft.Practices.Unity.dll + + + False + ..\SharedLibs\Rhino.Mocks.CPP.Interfaces.dll + + + False + ..\SharedLibs\Scripting.dll + + + System + + + + 3.5 + + + System.Data + + + System.EnterpriseServices + + + 3.0 + + + System.Web + + + + System.XML + + + + + + Code + + + + Code + + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + + + + + + + + + + + + + + + Component + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + + Code + + + + + + + + + + + + + + + + + + Code + + + Code + + + + + + + + + + + + Code + + + Code + + + + + {3078B943-10A5-41FA-A68A-7C4FC98506A0} + Rhino.Mocks.Tests.Model + + + Rhino.Mocks + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} + {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + + + + + + + + False + .NET Framework 2.0 %28x86%29 + true + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + false + + + + + ayende-open-source.snk + + + \ No newline at end of file diff --git a/Rhino.Mocks.Tests/RhinoMockTests.cs b/Rhino.Mocks.Tests/RhinoMockTests.cs index c56408da..decb7ec7 100644 --- a/Rhino.Mocks.Tests/RhinoMockTests.cs +++ b/Rhino.Mocks.Tests/RhinoMockTests.cs @@ -1,367 +1,367 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections; -using MbUnit.Core.Exceptions; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Tests.Callbacks; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class RhinoMockTests - { - private MockRepository mocks; - private IDemo demo; - - [SetUp] - public void SetUp() - { - mocks = new MockRepository(); - demo = this.mocks.StrictMock(typeof (IDemo)) as IDemo; - } - - [Test] - public void CallsAreNotOrderDependant() - { - this.demo.ReturnStringNoArgs(); - LastCall.On(this.demo).Return(null); - this.demo.VoidStringArg("Hello"); - this.mocks.Replay(this.demo); - this.demo.VoidStringArg("Hello"); - this.demo.ReturnStringNoArgs(); - this.mocks.Verify(this.demo); - } - - [Test] - public void OrderedCallsTrackingAsExpected() - { - RecordOrdered(mocks, demo); - - mocks.Replay(demo); - demo.ReturnStringNoArgs(); - demo.VoidNoArgs(); - demo.VoidNoArgs(); - demo.VoidStringArg("Hello"); - demo.VoidStringArg("World"); - mocks.Verify(demo); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.VoidNoArgs(); }' but was: 'IDemo.VoidStringArg(\"Hello\");'")] - public void GetDocumentationMessageWhenExpectationNotMet() - { - RecordOrdered(mocks, demo); - mocks.Replay(demo); - - demo.ReturnStringNoArgs(); - demo.VoidNoArgs(); - demo.VoidStringArg("Hello"); - - mocks.Verify(demo); - } - - [Test] - [ExpectedException(typeof (ExpectationViolationException), "Message: Called to prefar foo for bar\nIDemo.VoidNoArgs(); Expected #1, Actual #0.")] - public void WillDisplayDocumentationMessageIfNotCalled() - { - demo.VoidNoArgs(); - LastCall.On(demo) - .IgnoreArguments() - .Message("Called to prefar foo for bar"); - - mocks.Replay(demo); - - mocks.Verify(demo); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), @"IDemo.VoidNoArgs(); Expected #1, Actual #2. -Message: Should be called only once")] - public void WillDiplayDocumentationMessageIfCalledTooMuch() - { - demo.VoidNoArgs(); - LastCall.Message("Should be called only once"); - - mocks.ReplayAll(); - - demo.VoidNoArgs(); - demo.VoidNoArgs(); - - } - - [Test] - [ExpectedException(typeof (InvalidOperationException), "Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).")] - public void LastMockedObjectIsNullAfterDisposingMockRepository() - { - MockRepository mocks = new MockRepository(); - mocks.ReplayAll(); - mocks.VerifyAll(); - LastCall.IgnoreArguments(); - } - - [Test] - public void MixOrderedAndUnorderedBehaviour() - { - using (mocks.Ordered()) - { - demo.EnumNoArgs(); - LastCall.On(demo).Return(EnumDemo.Dozen).Repeat.Twice(); - demo.VoidStringArg("Ayende"); - using (mocks.Unordered()) - { - demo.VoidStringArg("Rahien"); - demo.VoidThreeStringArgs("1", "2", "3"); - } - demo.StringArgString("Hello"); - LastCall.On(demo).Return("World"); - } - mocks.Replay(demo); - Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); - Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); - demo.VoidStringArg("Ayende"); - demo.VoidThreeStringArgs("1", "2", "3"); - demo.VoidStringArg("Rahien"); - Assert.AreEqual("World", demo.StringArgString("Hello")); - - mocks.Verify(demo); - } - - [Test] - public void ChangingRecordersWhenReplayingDoesNotInterruptVerification() - { - demo.VoidStringArg("ayende"); - mocks.Replay(demo); - using (mocks.Ordered()) - { - demo.VoidStringArg("ayende"); - } - mocks.Verify(demo); - } - - [Test] - [ExpectedException(typeof (InvalidOperationException), "Can't start replaying because Ordered or Unordered properties were call and not yet disposed.")] - public void CallingReplayInOrderringThrows() - { - demo.VoidStringArg("ayende"); - using (mocks.Ordered()) - { - mocks.Replay(demo); - } - } - - [Test] - public void UsingSeveralObjectAndMixingOrderAndUnorder() - { - IList second = mocks.StrictMock(typeof (IList)) as IList; - using (mocks.Ordered()) - { - demo.EnumNoArgs(); - LastCall.On(demo).Return(EnumDemo.Dozen).Repeat.Twice(); - second.Clear(); - demo.VoidStringArg("Ayende"); - using (mocks.Unordered()) - { - int i = second.Count; - LastCall.On(second).Repeat.Twice().Return(3); - demo.VoidStringArg("Rahien"); - demo.VoidThreeStringArgs("1", "2", "3"); - } - demo.StringArgString("Hello"); - LastCall.On(demo).Return("World"); - second.IndexOf(null); - LastCall.On(second).Return(2); - } - - mocks.Replay(demo); - mocks.Replay(second); - - Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); - Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); - second.Clear(); - demo.VoidStringArg("Ayende"); - Assert.AreEqual(3, second.Count); - demo.VoidThreeStringArgs("1", "2", "3"); - Assert.AreEqual(3, second.Count); - demo.VoidStringArg("Rahien"); - Assert.AreEqual("World", demo.StringArgString("Hello")); - second.IndexOf(null); - mocks.Verify(demo); - } - - [Test] - [ExpectedException(typeof (ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.EnumNoArgs(); }' but was: 'IList.Clear();'")] - public void SeveralMocksUsingOrdered() - { - IList second = mocks.StrictMock(typeof (IList)) as IList; - using (mocks.Ordered()) - { - demo.EnumNoArgs(); - LastCall.On(demo).Return(EnumDemo.Dozen).Repeat.Twice(); - second.Clear(); - demo.VoidStringArg("Ayende"); - using (mocks.Unordered()) - { - int i = second.Count; - LastCall.On(second).Repeat.Twice().Return(3); - demo.VoidStringArg("Rahien"); - demo.VoidThreeStringArgs("1", "2", "3"); - } - demo.StringArgString("Hello"); - LastCall.On(demo).Return("World"); - second.IndexOf(null); - LastCall.On(second).Return(2); - } - - mocks.Replay(demo); - mocks.Replay(second); - - demo.EnumNoArgs(); - second.Clear(); - } - - [Test] - public void RecursiveExpectationsOnUnordered() - { - demo = (IDemo) mocks.StrictMock(typeof (IDemo)); - demo.VoidNoArgs(); - LastCall.On(demo).Callback(new DelegateDefinations.NoArgsDelegate(CallMethodOnDemo)); - demo.VoidStringArg("Ayende"); - mocks.Replay(demo); - demo.VoidNoArgs(); - mocks.Verify(demo); - } - - [Test] - [ExpectedException(typeof (ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.VoidNoArgs(callback method: RhinoMockTests.CallMethodOnDemo); }' but was: 'IDemo.VoidStringArg(\"Ayende\");'")] - public void RecursiveExpectationsOnOrdered() - { - demo = (IDemo) mocks.StrictMock(typeof (IDemo)); - using (mocks.Ordered()) - { - demo.VoidNoArgs(); - LastCall.On(demo).Callback(CallMethodOnDemo); - demo.VoidStringArg("Ayende"); - } - mocks.Replay(demo); - demo.VoidNoArgs(); - } - - - [Test] - [ExpectedException(typeof (ExpectationViolationException), "IDemo.VoidThreeStringArgs(\"c\", \"b\", \"a\"); Expected #0, Actual #1.\r\nIDemo.VoidThreeStringArgs(\"a\", \"b\", \"c\"); Expected #1, Actual #0.")] - public void GetArgsOfEpectedAndActualMethodCallOnException() - { - demo = (IDemo) mocks.StrictMock(typeof (IDemo)); - demo.VoidThreeStringArgs("a","b","c"); - mocks.Replay(demo); - demo.VoidThreeStringArgs("c","b","a"); - } - - - [Test] - [ExpectedException(typeof (ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.VoidStringArg(\"Ayende\"); }' but was: 'IDemo.VoidThreeStringArgs(\"\", \"\", \"\");'")] - public void SteppingFromInnerOrderringToOuterWithoutFullifingAllOrderringInInnerThrows() - { - demo = (IDemo) mocks.StrictMock(typeof (IDemo)); - demo.VoidThreeStringArgs("", "", ""); - using (mocks.Ordered()) - { - demo.VoidNoArgs(); - demo.VoidStringArg("Ayende"); - } - mocks.Replay(demo); - demo.VoidNoArgs(); - demo.VoidThreeStringArgs("", "", ""); - } - - [Test] - public void Overrideing_ToString() - { - MockRepository mocks = new MockRepository(); - ObjectThatOverrideToString oid = (ObjectThatOverrideToString) - mocks.StrictMock(typeof (ObjectThatOverrideToString)); - Expect.On(oid).Call(oid.ToString()).Return("bla"); - mocks.ReplayAll(); - Assert.AreEqual("bla", oid.ToString()); - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof (AssertionException), "ErrorMessage")] - public void CallbackThatThrows() - { - demo = (IDemo) mocks.StrictMock(typeof (IDemo)); - demo.VoidNoArgs(); - LastCall.Callback(new DelegateDefinations.NoArgsDelegate(ThrowFromCallback)); - mocks.ReplayAll(); - demo.VoidNoArgs(); - - } - - #region Private Methods - - private static void RecordOrdered(MockRepository mocks, IDemo demo) - { - using (mocks.Ordered()) - { - demo.ReturnStringNoArgs(); - LastCall.On(demo).Return(null); - demo.VoidNoArgs(); - LastCall.On(demo).Repeat.Twice(); - demo.VoidStringArg("Hello"); - demo.VoidStringArg("World"); - } - } - - #endregion - - private bool CallMethodOnDemo() - { - demo.VoidStringArg("Ayende"); - return true; - } - - private bool ThrowFromCallback() - { - Assert.Fail("ErrorMessage"); - return true; - } - - public class ObjectThatOverrideToString - { - public override string ToString() - { - return base.ToString (); - } - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections; +using MbUnit.Core.Exceptions; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Tests.Callbacks; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class RhinoMockTests + { + private MockRepository mocks; + private IDemo demo; + + [SetUp] + public void SetUp() + { + mocks = new MockRepository(); + demo = this.mocks.StrictMock(typeof (IDemo)) as IDemo; + } + + [Test] + public void CallsAreNotOrderDependant() + { + this.demo.ReturnStringNoArgs(); + LastCall.On(this.demo).Return(null); + this.demo.VoidStringArg("Hello"); + this.mocks.Replay(this.demo); + this.demo.VoidStringArg("Hello"); + this.demo.ReturnStringNoArgs(); + this.mocks.Verify(this.demo); + } + + [Test] + public void OrderedCallsTrackingAsExpected() + { + RecordOrdered(mocks, demo); + + mocks.Replay(demo); + demo.ReturnStringNoArgs(); + demo.VoidNoArgs(); + demo.VoidNoArgs(); + demo.VoidStringArg("Hello"); + demo.VoidStringArg("World"); + mocks.Verify(demo); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.VoidNoArgs(); }' but was: 'IDemo.VoidStringArg(\"Hello\");'")] + public void GetDocumentationMessageWhenExpectationNotMet() + { + RecordOrdered(mocks, demo); + mocks.Replay(demo); + + demo.ReturnStringNoArgs(); + demo.VoidNoArgs(); + demo.VoidStringArg("Hello"); + + mocks.Verify(demo); + } + + [Test] + [ExpectedException(typeof (ExpectationViolationException), "Message: Called to prefar foo for bar\nIDemo.VoidNoArgs(); Expected #1, Actual #0.")] + public void WillDisplayDocumentationMessageIfNotCalled() + { + demo.VoidNoArgs(); + LastCall.On(demo) + .IgnoreArguments() + .Message("Called to prefar foo for bar"); + + mocks.Replay(demo); + + mocks.Verify(demo); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), @"IDemo.VoidNoArgs(); Expected #1, Actual #2. +Message: Should be called only once")] + public void WillDiplayDocumentationMessageIfCalledTooMuch() + { + demo.VoidNoArgs(); + LastCall.Message("Should be called only once"); + + mocks.ReplayAll(); + + demo.VoidNoArgs(); + demo.VoidNoArgs(); + + } + + [Test] + [ExpectedException(typeof (InvalidOperationException), "Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).")] + public void LastMockedObjectIsNullAfterDisposingMockRepository() + { + MockRepository mocks = new MockRepository(); + mocks.ReplayAll(); + mocks.VerifyAll(); + LastCall.IgnoreArguments(); + } + + [Test] + public void MixOrderedAndUnorderedBehaviour() + { + using (mocks.Ordered()) + { + demo.EnumNoArgs(); + LastCall.On(demo).Return(EnumDemo.Dozen).Repeat.Twice(); + demo.VoidStringArg("Ayende"); + using (mocks.Unordered()) + { + demo.VoidStringArg("Rahien"); + demo.VoidThreeStringArgs("1", "2", "3"); + } + demo.StringArgString("Hello"); + LastCall.On(demo).Return("World"); + } + mocks.Replay(demo); + Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); + Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); + demo.VoidStringArg("Ayende"); + demo.VoidThreeStringArgs("1", "2", "3"); + demo.VoidStringArg("Rahien"); + Assert.AreEqual("World", demo.StringArgString("Hello")); + + mocks.Verify(demo); + } + + [Test] + public void ChangingRecordersWhenReplayingDoesNotInterruptVerification() + { + demo.VoidStringArg("ayende"); + mocks.Replay(demo); + using (mocks.Ordered()) + { + demo.VoidStringArg("ayende"); + } + mocks.Verify(demo); + } + + [Test] + [ExpectedException(typeof (InvalidOperationException), "Can't start replaying because Ordered or Unordered properties were call and not yet disposed.")] + public void CallingReplayInOrderringThrows() + { + demo.VoidStringArg("ayende"); + using (mocks.Ordered()) + { + mocks.Replay(demo); + } + } + + [Test] + public void UsingSeveralObjectAndMixingOrderAndUnorder() + { + IList second = mocks.StrictMock(typeof (IList)) as IList; + using (mocks.Ordered()) + { + demo.EnumNoArgs(); + LastCall.On(demo).Return(EnumDemo.Dozen).Repeat.Twice(); + second.Clear(); + demo.VoidStringArg("Ayende"); + using (mocks.Unordered()) + { + int i = second.Count; + LastCall.On(second).Repeat.Twice().Return(3); + demo.VoidStringArg("Rahien"); + demo.VoidThreeStringArgs("1", "2", "3"); + } + demo.StringArgString("Hello"); + LastCall.On(demo).Return("World"); + second.IndexOf(null); + LastCall.On(second).Return(2); + } + + mocks.Replay(demo); + mocks.Replay(second); + + Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); + Assert.AreEqual(EnumDemo.Dozen, demo.EnumNoArgs()); + second.Clear(); + demo.VoidStringArg("Ayende"); + Assert.AreEqual(3, second.Count); + demo.VoidThreeStringArgs("1", "2", "3"); + Assert.AreEqual(3, second.Count); + demo.VoidStringArg("Rahien"); + Assert.AreEqual("World", demo.StringArgString("Hello")); + second.IndexOf(null); + mocks.Verify(demo); + } + + [Test] + [ExpectedException(typeof (ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.EnumNoArgs(); }' but was: 'IList.Clear();'")] + public void SeveralMocksUsingOrdered() + { + IList second = mocks.StrictMock(typeof (IList)) as IList; + using (mocks.Ordered()) + { + demo.EnumNoArgs(); + LastCall.On(demo).Return(EnumDemo.Dozen).Repeat.Twice(); + second.Clear(); + demo.VoidStringArg("Ayende"); + using (mocks.Unordered()) + { + int i = second.Count; + LastCall.On(second).Repeat.Twice().Return(3); + demo.VoidStringArg("Rahien"); + demo.VoidThreeStringArgs("1", "2", "3"); + } + demo.StringArgString("Hello"); + LastCall.On(demo).Return("World"); + second.IndexOf(null); + LastCall.On(second).Return(2); + } + + mocks.Replay(demo); + mocks.Replay(second); + + demo.EnumNoArgs(); + second.Clear(); + } + + [Test] + public void RecursiveExpectationsOnUnordered() + { + demo = (IDemo) mocks.StrictMock(typeof (IDemo)); + demo.VoidNoArgs(); + LastCall.On(demo).Callback(new DelegateDefinations.NoArgsDelegate(CallMethodOnDemo)); + demo.VoidStringArg("Ayende"); + mocks.Replay(demo); + demo.VoidNoArgs(); + mocks.Verify(demo); + } + + [Test] + [ExpectedException(typeof (ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.VoidNoArgs(callback method: RhinoMockTests.CallMethodOnDemo); }' but was: 'IDemo.VoidStringArg(\"Ayende\");'")] + public void RecursiveExpectationsOnOrdered() + { + demo = (IDemo) mocks.StrictMock(typeof (IDemo)); + using (mocks.Ordered()) + { + demo.VoidNoArgs(); + LastCall.On(demo).Callback(CallMethodOnDemo); + demo.VoidStringArg("Ayende"); + } + mocks.Replay(demo); + demo.VoidNoArgs(); + } + + + [Test] + [ExpectedException(typeof (ExpectationViolationException), "IDemo.VoidThreeStringArgs(\"c\", \"b\", \"a\"); Expected #0, Actual #1.\r\nIDemo.VoidThreeStringArgs(\"a\", \"b\", \"c\"); Expected #1, Actual #0.")] + public void GetArgsOfEpectedAndActualMethodCallOnException() + { + demo = (IDemo) mocks.StrictMock(typeof (IDemo)); + demo.VoidThreeStringArgs("a","b","c"); + mocks.Replay(demo); + demo.VoidThreeStringArgs("c","b","a"); + } + + + [Test] + [ExpectedException(typeof (ExpectationViolationException), "Unordered method call! The expected call is: 'Ordered: { IDemo.VoidStringArg(\"Ayende\"); }' but was: 'IDemo.VoidThreeStringArgs(\"\", \"\", \"\");'")] + public void SteppingFromInnerOrderringToOuterWithoutFullifingAllOrderringInInnerThrows() + { + demo = (IDemo) mocks.StrictMock(typeof (IDemo)); + demo.VoidThreeStringArgs("", "", ""); + using (mocks.Ordered()) + { + demo.VoidNoArgs(); + demo.VoidStringArg("Ayende"); + } + mocks.Replay(demo); + demo.VoidNoArgs(); + demo.VoidThreeStringArgs("", "", ""); + } + + [Test] + public void Overrideing_ToString() + { + MockRepository mocks = new MockRepository(); + ObjectThatOverrideToString oid = (ObjectThatOverrideToString) + mocks.StrictMock(typeof (ObjectThatOverrideToString)); + Expect.On(oid).Call(oid.ToString()).Return("bla"); + mocks.ReplayAll(); + Assert.AreEqual("bla", oid.ToString()); + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof (AssertionException), "ErrorMessage")] + public void CallbackThatThrows() + { + demo = (IDemo) mocks.StrictMock(typeof (IDemo)); + demo.VoidNoArgs(); + LastCall.Callback(new DelegateDefinations.NoArgsDelegate(ThrowFromCallback)); + mocks.ReplayAll(); + demo.VoidNoArgs(); + + } + + #region Private Methods + + private static void RecordOrdered(MockRepository mocks, IDemo demo) + { + using (mocks.Ordered()) + { + demo.ReturnStringNoArgs(); + LastCall.On(demo).Return(null); + demo.VoidNoArgs(); + LastCall.On(demo).Repeat.Twice(); + demo.VoidStringArg("Hello"); + demo.VoidStringArg("World"); + } + } + + #endregion + + private bool CallMethodOnDemo() + { + demo.VoidStringArg("Ayende"); + return true; + } + + private bool ThrowFromCallback() + { + Assert.Fail("ErrorMessage"); + return true; + } + + public class ObjectThatOverrideToString + { + public override string ToString() + { + return base.ToString (); + } + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/SetupResultTests.cs b/Rhino.Mocks.Tests/SetupResultTests.cs index 10a6ad24..05012e65 100644 --- a/Rhino.Mocks.Tests/SetupResultTests.cs +++ b/Rhino.Mocks.Tests/SetupResultTests.cs @@ -1,153 +1,153 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class SetupResultTests - { - private MockRepository mocks; - private IDemo demo; - - [SetUp] - public void SetUp() - { - mocks = new MockRepository(); - demo = mocks.StrictMock(typeof (IDemo)) as IDemo; - } - - [Test] - public void CanSetupResultForMethodAndIgnoreArgs() - { - SetupResult.For(demo.StringArgString(null)).Return("Ayende").IgnoreArguments(); - mocks.ReplayAll(); - Assert.AreEqual("Ayende", demo.StringArgString("a")); - Assert.AreEqual("Ayende", demo.StringArgString("b")); - mocks.VerifyAll(); - - } - - [Test] - public void CanSetupResult() - { - SetupResult.For(demo.Prop).Return("Ayende"); - mocks.ReplayAll(); - Assert.AreEqual("Ayende", demo.Prop); - mocks.VerifyAll(); - - } - - [Test] - [ExpectedException(typeof (InvalidOperationException), "Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).")] - public void SetupResultForNoCall() - { - SetupResult.For(null); - } - - [Test] - public void SetupResultCanRepeatAsManyTimeAsItWant() - { - SetupResult.For(demo.Prop).Return("Ayende"); - mocks.ReplayAll(); - for (int i = 0; i < 30; i++) - { - Assert.AreEqual("Ayende", demo.Prop); - } - mocks.VerifyAll(); - - } - - [Test] - public void SetupResultUsingOn() - { - SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); - mocks.ReplayAll(); - for (int i = 0; i < 30; i++) - { - Assert.AreEqual("Ayende", demo.Prop); - } - mocks.VerifyAll(); - - } - - [Test] - public void SetupResultUsingOrdered() - { - SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); - using (mocks.Ordered()) - { - demo.VoidNoArgs(); - LastCall.On(demo).Repeat.Twice(); - } - mocks.ReplayAll(); - demo.VoidNoArgs(); - for (int i = 0; i < 30; i++) - { - Assert.AreEqual("Ayende", demo.Prop); - } - demo.VoidNoArgs(); - mocks.VerifyAll(); - - } - - [Test] - [ExpectedException(typeof (InvalidOperationException), "The result for IDemo.get_Prop(); has already been setup.")] - public void SetupResultForTheSameMethodTwiceCauseExcetion() - { - SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); - SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException),"IDemo.ReturnIntNoArgs(); Expected #0, Actual #1.")] - public void ExpectNever() - { - demo.ReturnStringNoArgs(); - LastCall.Repeat.Never(); - mocks.ReplayAll(); - demo.ReturnIntNoArgs(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException), - "The result for IDemo.ReturnStringNoArgs(); has already been setup.")] - public void ExpectNeverSetupTwiceThrows() - { - demo.ReturnStringNoArgs(); - LastCall.Repeat.Never(); - demo.ReturnStringNoArgs(); - LastCall.Repeat.Never(); - - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class SetupResultTests + { + private MockRepository mocks; + private IDemo demo; + + [SetUp] + public void SetUp() + { + mocks = new MockRepository(); + demo = mocks.StrictMock(typeof (IDemo)) as IDemo; + } + + [Test] + public void CanSetupResultForMethodAndIgnoreArgs() + { + SetupResult.For(demo.StringArgString(null)).Return("Ayende").IgnoreArguments(); + mocks.ReplayAll(); + Assert.AreEqual("Ayende", demo.StringArgString("a")); + Assert.AreEqual("Ayende", demo.StringArgString("b")); + mocks.VerifyAll(); + + } + + [Test] + public void CanSetupResult() + { + SetupResult.For(demo.Prop).Return("Ayende"); + mocks.ReplayAll(); + Assert.AreEqual("Ayende", demo.Prop); + mocks.VerifyAll(); + + } + + [Test] + [ExpectedException(typeof (InvalidOperationException), "Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).")] + public void SetupResultForNoCall() + { + SetupResult.For(null); + } + + [Test] + public void SetupResultCanRepeatAsManyTimeAsItWant() + { + SetupResult.For(demo.Prop).Return("Ayende"); + mocks.ReplayAll(); + for (int i = 0; i < 30; i++) + { + Assert.AreEqual("Ayende", demo.Prop); + } + mocks.VerifyAll(); + + } + + [Test] + public void SetupResultUsingOn() + { + SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); + mocks.ReplayAll(); + for (int i = 0; i < 30; i++) + { + Assert.AreEqual("Ayende", demo.Prop); + } + mocks.VerifyAll(); + + } + + [Test] + public void SetupResultUsingOrdered() + { + SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); + using (mocks.Ordered()) + { + demo.VoidNoArgs(); + LastCall.On(demo).Repeat.Twice(); + } + mocks.ReplayAll(); + demo.VoidNoArgs(); + for (int i = 0; i < 30; i++) + { + Assert.AreEqual("Ayende", demo.Prop); + } + demo.VoidNoArgs(); + mocks.VerifyAll(); + + } + + [Test] + [ExpectedException(typeof (InvalidOperationException), "The result for IDemo.get_Prop(); has already been setup.")] + public void SetupResultForTheSameMethodTwiceCauseExcetion() + { + SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); + SetupResult.On(demo).Call(demo.Prop).Return("Ayende"); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException),"IDemo.ReturnIntNoArgs(); Expected #0, Actual #1.")] + public void ExpectNever() + { + demo.ReturnStringNoArgs(); + LastCall.Repeat.Never(); + mocks.ReplayAll(); + demo.ReturnIntNoArgs(); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException), + "The result for IDemo.ReturnStringNoArgs(); has already been setup.")] + public void ExpectNeverSetupTwiceThrows() + { + demo.ReturnStringNoArgs(); + LastCall.Repeat.Never(); + demo.ReturnStringNoArgs(); + LastCall.Repeat.Never(); + + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/StubAllTest.cs b/Rhino.Mocks.Tests/StubAllTest.cs index e3d39348..3860e997 100644 --- a/Rhino.Mocks.Tests/StubAllTest.cs +++ b/Rhino.Mocks.Tests/StubAllTest.cs @@ -1,227 +1,227 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using MbUnit.Framework; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class StubAllTest - { - [Test] - public void StaticAccessorForStubAll() - { - ICat cat = MockRepository.GenerateStub(); - cat.Eyes = 2; - Assert.AreEqual(2, cat.Eyes ); - } - - [Test] - public void StubAllHasPropertyBehaviorForAllProperties() - { - MockRepository mocks = new MockRepository(); - ICat cat = mocks.Stub(); - cat.Legs = 4; - Assert.AreEqual(4, cat.Legs); - - cat.Name = "Esther"; - Assert.AreEqual("Esther", cat.Name); - - Assert.IsNull(cat.Species, "Should return default value if not set"); - cat.Species = "Ordinary housecat"; - Assert.AreEqual("Ordinary housecat", cat.Species); - - cat.IsDeclawed = true; - Assert.IsTrue(cat.IsDeclawed); - } - - [Test] - public void StubAllHasPropertyBehaviorForAllPropertiesWhenStubbingClasses() - { - MockRepository mocks = new MockRepository(); - Housecat housecat = mocks.Stub(); - - housecat.FurLength = 7; - Assert.AreEqual(7, housecat.FurLength); - - housecat.Color = "Black"; - Assert.AreEqual("Black", housecat.Color); - } - - [Test] - public void StubAllCanRegisterToEventsAndRaiseThem() - { - MockRepository mocks = new MockRepository(); - ICat cat = mocks.Stub(); - cat.Hungry += null; //Note, no expectation! - IEventRaiser eventRaiser = LastCall.GetEventRaiser(); - - bool raised = false; - cat.Hungry += delegate - { - raised = true; - }; - - eventRaiser.Raise(cat, EventArgs.Empty); - Assert.IsTrue(raised); - } - - [Test] - public void CallingMethodOnStubAllDoesNotCreateExpectations() - { - MockRepository mocks = new MockRepository(); - ICat cat = mocks.Stub(); - using (mocks.Record()) - { - cat.Legs = 4; - cat.Name = "Esther"; - cat.Species = "Ordinary housecat"; - cat.IsDeclawed = true; - cat.GetMood(); - } - mocks.VerifyAll(); - } - - [Test] - public void DemoStubAllLegsProperty() - { - ICat catStub = MockRepository.GenerateStub(); - - catStub.Legs = 0; - Assert.AreEqual(0, catStub.Legs); - - SomeClass instance = new SomeClass(catStub); - instance.SetLegs(10); - Assert.AreEqual(10, catStub.Legs); - } - - [Test] - public void StubAllCanCreateExpectationOnMethod() - { - MockRepository mocks = new MockRepository(); - ICat cat = mocks.Stub(); - using (mocks.Record()) - { - cat.Legs = 4; - cat.Name = "Esther"; - cat.Species = "Ordinary housecat"; - cat.IsDeclawed = true; - cat.GetMood(); - LastCall.Return("Happy"); - } - Assert.AreEqual("Happy", cat.GetMood()); - mocks.VerifyAll(); - } - - [Test] - public void StubAllCanHandlePropertiesGettingRegisteredMultipleTimes() - { - MockRepository mocks = new MockRepository(); - SpecificFish fish = mocks.Stub(); - - fish.IsFreshWater = true; - Assert.IsTrue(fish.IsFreshWater); - } - - [Test] - public void StubCanHandlePolymorphicArgConstraints() - { - IAquarium aquarium = MockRepository.GenerateStub(); - aquarium.Stub(x => x.DetermineAge(Arg.Matches(arg => arg.Planet == "mars"))).Return(100); - aquarium.Stub(x => x.DetermineAge(Arg.Is.TypeOf)).Return(5); - - Assert.IsFalse(typeof(MartianFish).IsAssignableFrom(typeof(SpecificFish))); - Assert.AreEqual(5, aquarium.DetermineAge(new SpecificFish())); - } - - } - - public interface ICat : IAnimal - { - bool IsDeclawed { get; set; } - } - - public class Feline - { - private int _furLength; - - public virtual int FurLength - { - get { return _furLength; } - set { _furLength = value; } - } - } - - public class Housecat : Feline - { - private String _color; - - public virtual String Color - { - get { return _color; } - set { _color = value; } - } - } - - - - public interface IAquarium - { - int DetermineAge(IFish fish); - } - - public interface IFish - { - bool IsFreshWater { get; set; } - } - - public abstract class Fish : IFish - { - public abstract bool IsFreshWater { get; set; } - } - - public class MartianFish : IFish - { - public bool IsFreshWater { get; set; } - public string Planet { get; set; } - } - - public class SpecificFish : Fish - { - private bool _isFreshWater; - - public override bool IsFreshWater - { - get { return _isFreshWater; } - set { _isFreshWater = value; } - } - } - -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using MbUnit.Framework; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class StubAllTest + { + [Test] + public void StaticAccessorForStubAll() + { + ICat cat = MockRepository.GenerateStub(); + cat.Eyes = 2; + Assert.AreEqual(2, cat.Eyes ); + } + + [Test] + public void StubAllHasPropertyBehaviorForAllProperties() + { + MockRepository mocks = new MockRepository(); + ICat cat = mocks.Stub(); + cat.Legs = 4; + Assert.AreEqual(4, cat.Legs); + + cat.Name = "Esther"; + Assert.AreEqual("Esther", cat.Name); + + Assert.IsNull(cat.Species, "Should return default value if not set"); + cat.Species = "Ordinary housecat"; + Assert.AreEqual("Ordinary housecat", cat.Species); + + cat.IsDeclawed = true; + Assert.IsTrue(cat.IsDeclawed); + } + + [Test] + public void StubAllHasPropertyBehaviorForAllPropertiesWhenStubbingClasses() + { + MockRepository mocks = new MockRepository(); + Housecat housecat = mocks.Stub(); + + housecat.FurLength = 7; + Assert.AreEqual(7, housecat.FurLength); + + housecat.Color = "Black"; + Assert.AreEqual("Black", housecat.Color); + } + + [Test] + public void StubAllCanRegisterToEventsAndRaiseThem() + { + MockRepository mocks = new MockRepository(); + ICat cat = mocks.Stub(); + cat.Hungry += null; //Note, no expectation! + IEventRaiser eventRaiser = LastCall.GetEventRaiser(); + + bool raised = false; + cat.Hungry += delegate + { + raised = true; + }; + + eventRaiser.Raise(cat, EventArgs.Empty); + Assert.IsTrue(raised); + } + + [Test] + public void CallingMethodOnStubAllDoesNotCreateExpectations() + { + MockRepository mocks = new MockRepository(); + ICat cat = mocks.Stub(); + using (mocks.Record()) + { + cat.Legs = 4; + cat.Name = "Esther"; + cat.Species = "Ordinary housecat"; + cat.IsDeclawed = true; + cat.GetMood(); + } + mocks.VerifyAll(); + } + + [Test] + public void DemoStubAllLegsProperty() + { + ICat catStub = MockRepository.GenerateStub(); + + catStub.Legs = 0; + Assert.AreEqual(0, catStub.Legs); + + SomeClass instance = new SomeClass(catStub); + instance.SetLegs(10); + Assert.AreEqual(10, catStub.Legs); + } + + [Test] + public void StubAllCanCreateExpectationOnMethod() + { + MockRepository mocks = new MockRepository(); + ICat cat = mocks.Stub(); + using (mocks.Record()) + { + cat.Legs = 4; + cat.Name = "Esther"; + cat.Species = "Ordinary housecat"; + cat.IsDeclawed = true; + cat.GetMood(); + LastCall.Return("Happy"); + } + Assert.AreEqual("Happy", cat.GetMood()); + mocks.VerifyAll(); + } + + [Test] + public void StubAllCanHandlePropertiesGettingRegisteredMultipleTimes() + { + MockRepository mocks = new MockRepository(); + SpecificFish fish = mocks.Stub(); + + fish.IsFreshWater = true; + Assert.IsTrue(fish.IsFreshWater); + } + + [Test] + public void StubCanHandlePolymorphicArgConstraints() + { + IAquarium aquarium = MockRepository.GenerateStub(); + aquarium.Stub(x => x.DetermineAge(Arg.Matches(arg => arg.Planet == "mars"))).Return(100); + aquarium.Stub(x => x.DetermineAge(Arg.Is.TypeOf)).Return(5); + + Assert.IsFalse(typeof(MartianFish).IsAssignableFrom(typeof(SpecificFish))); + Assert.AreEqual(5, aquarium.DetermineAge(new SpecificFish())); + } + + } + + public interface ICat : IAnimal + { + bool IsDeclawed { get; set; } + } + + public class Feline + { + private int _furLength; + + public virtual int FurLength + { + get { return _furLength; } + set { _furLength = value; } + } + } + + public class Housecat : Feline + { + private String _color; + + public virtual String Color + { + get { return _color; } + set { _color = value; } + } + } + + + + public interface IAquarium + { + int DetermineAge(IFish fish); + } + + public interface IFish + { + bool IsFreshWater { get; set; } + } + + public abstract class Fish : IFish + { + public abstract bool IsFreshWater { get; set; } + } + + public class MartianFish : IFish + { + public bool IsFreshWater { get; set; } + public string Planet { get; set; } + } + + public class SpecificFish : Fish + { + private bool _isFreshWater; + + public override bool IsFreshWater + { + get { return _isFreshWater; } + set { _isFreshWater = value; } + } + } + +} diff --git a/Rhino.Mocks.Tests/StubTest.cs b/Rhino.Mocks.Tests/StubTest.cs index a0122a2f..265fded5 100644 --- a/Rhino.Mocks.Tests/StubTest.cs +++ b/Rhino.Mocks.Tests/StubTest.cs @@ -1,151 +1,151 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using MbUnit.Framework; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class StubTest - { - [Test] - public void StaticAccessorForStub() - { - IAnimal animal = MockRepository.GenerateStub(); - animal.Eyes = 2; - Assert.AreEqual(2, animal.Eyes ); - } - - [Test] - public void StubHasPropertyBehaviorForAllProperties() - { - MockRepository mocks = new MockRepository(); - IAnimal animal = mocks.Stub(); - animal.Legs = 4; - Assert.AreEqual(4, animal.Legs); - - animal.Name = "Rose"; - Assert.AreEqual("Rose", animal.Name); - - Assert.IsNull(animal.Species, "Should return default value if not set"); - animal.Species = "Caucasusian Shepherd"; - Assert.AreEqual("Caucasusian Shepherd", animal.Species); - } - - [Test] - public void CanRegisterToEventsAndRaiseThem() - { - MockRepository mocks = new MockRepository(); - IAnimal animal = mocks.Stub(); - animal.Hungry += null; //Note, no expectation! - IEventRaiser eventRaiser = LastCall.GetEventRaiser(); - - bool raised = false; - animal.Hungry += delegate - { - raised = true; - }; - - eventRaiser.Raise(animal, EventArgs.Empty); - Assert.IsTrue(raised); - } - - [Test] - public void CallingMethodOnStubsDoesNotCreateExpectations() - { - MockRepository mocks = new MockRepository(); - IAnimal animal = mocks.Stub(); - using (mocks.Record()) - { - animal.Legs = 4; - animal.Name = "Rose"; - animal.Species = "Caucasusian Shepherd"; - animal.GetMood(); - } - mocks.VerifyAll(); - } - - [Test] - public void DemoLegsProperty() - { - IAnimal animalStub = MockRepository.GenerateStub(); - - animalStub.Legs = 0; - Assert.AreEqual(0, animalStub.Legs); - - SomeClass instance = new SomeClass(animalStub); - instance.SetLegs(10); - Assert.AreEqual(10, animalStub.Legs); - } - - [Test] - public void CanCreateExpectationOnMethod() - { - MockRepository mocks = new MockRepository(); - IAnimal animal = mocks.Stub(); - using (mocks.Record()) - { - animal.Legs = 4; - animal.Name = "Rose"; - animal.Species = "Caucasusian Shepherd"; - animal.GetMood(); - LastCall.Return("Happy"); - } - Assert.AreEqual("Happy", animal.GetMood()); - mocks.VerifyAll(); - } - } - - public interface IAnimal - { - int Legs { get; set; } - int Eyes { get; set; } - string Name { get; set; } - string Species { get; set; } - - event EventHandler Hungry; - string GetMood(); - } - - public class SomeClass - { - private IAnimal animal; - - public SomeClass(IAnimal animal) - { - this.animal = animal; - } - - public void SetLegs(int count) - { - animal.Legs = count; - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using MbUnit.Framework; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class StubTest + { + [Test] + public void StaticAccessorForStub() + { + IAnimal animal = MockRepository.GenerateStub(); + animal.Eyes = 2; + Assert.AreEqual(2, animal.Eyes ); + } + + [Test] + public void StubHasPropertyBehaviorForAllProperties() + { + MockRepository mocks = new MockRepository(); + IAnimal animal = mocks.Stub(); + animal.Legs = 4; + Assert.AreEqual(4, animal.Legs); + + animal.Name = "Rose"; + Assert.AreEqual("Rose", animal.Name); + + Assert.IsNull(animal.Species, "Should return default value if not set"); + animal.Species = "Caucasusian Shepherd"; + Assert.AreEqual("Caucasusian Shepherd", animal.Species); + } + + [Test] + public void CanRegisterToEventsAndRaiseThem() + { + MockRepository mocks = new MockRepository(); + IAnimal animal = mocks.Stub(); + animal.Hungry += null; //Note, no expectation! + IEventRaiser eventRaiser = LastCall.GetEventRaiser(); + + bool raised = false; + animal.Hungry += delegate + { + raised = true; + }; + + eventRaiser.Raise(animal, EventArgs.Empty); + Assert.IsTrue(raised); + } + + [Test] + public void CallingMethodOnStubsDoesNotCreateExpectations() + { + MockRepository mocks = new MockRepository(); + IAnimal animal = mocks.Stub(); + using (mocks.Record()) + { + animal.Legs = 4; + animal.Name = "Rose"; + animal.Species = "Caucasusian Shepherd"; + animal.GetMood(); + } + mocks.VerifyAll(); + } + + [Test] + public void DemoLegsProperty() + { + IAnimal animalStub = MockRepository.GenerateStub(); + + animalStub.Legs = 0; + Assert.AreEqual(0, animalStub.Legs); + + SomeClass instance = new SomeClass(animalStub); + instance.SetLegs(10); + Assert.AreEqual(10, animalStub.Legs); + } + + [Test] + public void CanCreateExpectationOnMethod() + { + MockRepository mocks = new MockRepository(); + IAnimal animal = mocks.Stub(); + using (mocks.Record()) + { + animal.Legs = 4; + animal.Name = "Rose"; + animal.Species = "Caucasusian Shepherd"; + animal.GetMood(); + LastCall.Return("Happy"); + } + Assert.AreEqual("Happy", animal.GetMood()); + mocks.VerifyAll(); + } + } + + public interface IAnimal + { + int Legs { get; set; } + int Eyes { get; set; } + string Name { get; set; } + string Species { get; set; } + + event EventHandler Hungry; + string GetMood(); + } + + public class SomeClass + { + private IAnimal animal; + + public SomeClass(IAnimal animal) + { + this.animal = animal; + } + + public void SetLegs(int count) + { + animal.Legs = count; + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/TestInfo.cs b/Rhino.Mocks.Tests/TestInfo.cs index 67c08d13..b5a4dfda 100644 --- a/Rhino.Mocks.Tests/TestInfo.cs +++ b/Rhino.Mocks.Tests/TestInfo.cs @@ -1,34 +1,34 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Runtime.CompilerServices; -using Rhino.Mocks; - -[assembly: InternalsVisibleTo(RhinoMocks.StrongName)] -//[assembly: InternalsVisibleTo(RhinoMocks.NormalName)] +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Runtime.CompilerServices; +using Rhino.Mocks; + +[assembly: InternalsVisibleTo(RhinoMocks.StrongName)] +//[assembly: InternalsVisibleTo(RhinoMocks.NormalName)] diff --git a/Rhino.Mocks.Tests/Throws.cs b/Rhino.Mocks.Tests/Throws.cs index 0e179282..ea8601a4 100644 --- a/Rhino.Mocks.Tests/Throws.cs +++ b/Rhino.Mocks.Tests/Throws.cs @@ -1,35 +1,35 @@ -namespace Rhino.Mocks.Tests -{ - using System; - using MbUnit.Framework; - - public class Throws - { - public static void Exception(Delegates.Action action) - where TException : Exception - { - try - { - action(); - Assert.Fail("Should have thrown exception"); - } - catch(TException) - { - } - } - - public static void Exception(string message, Delegates.Action action) - where TException : Exception - { - try - { - action(); - Assert.Fail("Should have thrown exception"); - } - catch (TException e) - { - Assert.AreEqual(message, e.Message); - } - } - } +namespace Rhino.Mocks.Tests +{ + using System; + using MbUnit.Framework; + + public class Throws + { + public static void Exception(Delegates.Action action) + where TException : Exception + { + try + { + action(); + Assert.Fail("Should have thrown exception"); + } + catch(TException) + { + } + } + + public static void Exception(string message, Delegates.Action action) + where TException : Exception + { + try + { + action(); + Assert.Fail("Should have thrown exception"); + } + catch (TException e) + { + Assert.AreEqual(message, e.Message); + } + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/TraceWriterWithStackTraceExpectationWriterFixture.cs b/Rhino.Mocks.Tests/TraceWriterWithStackTraceExpectationWriterFixture.cs index e3b51327..f43c27c5 100644 --- a/Rhino.Mocks.Tests/TraceWriterWithStackTraceExpectationWriterFixture.cs +++ b/Rhino.Mocks.Tests/TraceWriterWithStackTraceExpectationWriterFixture.cs @@ -1,30 +1,30 @@ -namespace Rhino.Mocks.Tests -{ - using System.IO; - using MbUnit.Framework; - using Rhino.Mocks.Impl; - - [TestFixture] - public class TraceWriterWithStackTraceExpectationWriterFixture - { - [Test] - public void WillPrintLogInfoWithStackTrace() - { - TraceWriterWithStackTraceExpectationWriter expectationWriter = new TraceWriterWithStackTraceExpectationWriter(); - StringWriter writer = new StringWriter(); - expectationWriter.AlternativeWriter = writer; - - RhinoMocks.Logger = expectationWriter; - - MockRepository mocks = new MockRepository(); - IDemo mock = mocks.StrictMock(); - mock.VoidNoArgs(); - mocks.ReplayAll(); - mock.VoidNoArgs(); - mocks.VerifyAll(); - - Assert.Contains(writer.GetStringBuilder().ToString(), - "WillPrintLogInfoWithStackTrace"); - } - } +namespace Rhino.Mocks.Tests +{ + using System.IO; + using MbUnit.Framework; + using Rhino.Mocks.Impl; + + [TestFixture] + public class TraceWriterWithStackTraceExpectationWriterFixture + { + [Test] + public void WillPrintLogInfoWithStackTrace() + { + TraceWriterWithStackTraceExpectationWriter expectationWriter = new TraceWriterWithStackTraceExpectationWriter(); + StringWriter writer = new StringWriter(); + expectationWriter.AlternativeWriter = writer; + + RhinoMocks.Logger = expectationWriter; + + MockRepository mocks = new MockRepository(); + IDemo mock = mocks.StrictMock(); + mock.VoidNoArgs(); + mocks.ReplayAll(); + mock.VoidNoArgs(); + mocks.VerifyAll(); + + Assert.Contains(writer.GetStringBuilder().ToString(), + "WillPrintLogInfoWithStackTrace"); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/UsingComObject.cs b/Rhino.Mocks.Tests/UsingComObject.cs index 8a5aaef0..07805647 100644 --- a/Rhino.Mocks.Tests/UsingComObject.cs +++ b/Rhino.Mocks.Tests/UsingComObject.cs @@ -1,58 +1,58 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Text; -using MbUnit.Framework; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class UsingComObject - { - public interface IMockTest - { - Scripting.FileSystemObject GetFileSystemObject(); - } - - [Test] - public void UsingScriptingFileSystem() - { - MockRepository mocks = new MockRepository(); - Type fsoType = Type.GetTypeFromProgID("Scripting.FileSystemObject"); - Scripting.FileSystemObject fso = (Scripting.FileSystemObject)Activator.CreateInstance(fsoType); - IMockTest test = mocks.StrictMock(typeof(IMockTest)) as IMockTest; - Expect.Call(test.GetFileSystemObject()).Return(fso); - mocks.ReplayAll(); - Assert.AreSame(fso, test.GetFileSystemObject()); - mocks.VerifyAll(); - - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Text; +using MbUnit.Framework; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class UsingComObject + { + public interface IMockTest + { + Scripting.FileSystemObject GetFileSystemObject(); + } + + [Test] + public void UsingScriptingFileSystem() + { + MockRepository mocks = new MockRepository(); + Type fsoType = Type.GetTypeFromProgID("Scripting.FileSystemObject"); + Scripting.FileSystemObject fso = (Scripting.FileSystemObject)Activator.CreateInstance(fsoType); + IMockTest test = mocks.StrictMock(typeof(IMockTest)) as IMockTest; + Expect.Call(test.GetFileSystemObject()).Return(fso); + mocks.ReplayAll(); + Assert.AreSame(fso, test.GetFileSystemObject()); + mocks.VerifyAll(); + + } + } +} diff --git a/Rhino.Mocks.Tests/Utilities/MethodCallTests.cs b/Rhino.Mocks.Tests/Utilities/MethodCallTests.cs index 6de44736..c99a5ff7 100644 --- a/Rhino.Mocks.Tests/Utilities/MethodCallTests.cs +++ b/Rhino.Mocks.Tests/Utilities/MethodCallTests.cs @@ -1,98 +1,98 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using MbUnit.Framework; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Tests.Utilities -{ - [TestFixture] - public class MethodCallTests - { - [Test] - public void MethodCallToString() - { - string actual = MethodCallUtil.StringPresentation(null, GetMethodInfo("StartsWith", ""), new object[] {"abcd"}); - Assert.AreEqual("String.StartsWith(\"abcd\");", actual); - } - - [Test] - public void MethodCallToStringWithSeveralArguments() - { - string actual = MethodCallUtil.StringPresentation(null,GetMethodInfo("IndexOf", "abcd", 4), new object[] {"abcd", 4}); - Assert.AreEqual("String.IndexOf(\"abcd\", 4);", actual); - } - - [Test] - [ExpectedException(typeof (ArgumentNullException), "Value cannot be null.\r\nParameter name: method")] - public void MethodCallCtorWontAcceptNullMethod() - { - MethodCallUtil.StringPresentation(null,null, null); - } - - [Test] - [ExpectedException(typeof (ArgumentNullException), "Value cannot be null.\r\nParameter name: args")] - public void MethodCallCtorWontAcceptNullArgs() - { - MethodInfo method = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }); - MethodCallUtil.StringPresentation(null,method, null); - } - - [Test] - public void MethodCallWithArgumentsMissing() - { - MethodInfo method = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }); - Assert.AreEqual("String.StartsWith(missing parameter);", MethodCallUtil.StringPresentation(null,method, new object[0])); - - } - - #region Implementation - - private static Type[] TypesFromArgs(object[] args) - { - Type[] types = new Type[args.Length]; - for (int i = 0; i < args.Length; i++) - { - types[i] = args[i].GetType(); - } - return types; - } - - public static MethodInfo GetMethodInfo(string name, params object[] args) - { - Type[] types = TypesFromArgs(args); - MethodInfo method = typeof (string).GetMethod(name, types); - return method; - } - - #endregion - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using MbUnit.Framework; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Tests.Utilities +{ + [TestFixture] + public class MethodCallTests + { + [Test] + public void MethodCallToString() + { + string actual = MethodCallUtil.StringPresentation(null, GetMethodInfo("StartsWith", ""), new object[] {"abcd"}); + Assert.AreEqual("String.StartsWith(\"abcd\");", actual); + } + + [Test] + public void MethodCallToStringWithSeveralArguments() + { + string actual = MethodCallUtil.StringPresentation(null,GetMethodInfo("IndexOf", "abcd", 4), new object[] {"abcd", 4}); + Assert.AreEqual("String.IndexOf(\"abcd\", 4);", actual); + } + + [Test] + [ExpectedException(typeof (ArgumentNullException), "Value cannot be null.\r\nParameter name: method")] + public void MethodCallCtorWontAcceptNullMethod() + { + MethodCallUtil.StringPresentation(null,null, null); + } + + [Test] + [ExpectedException(typeof (ArgumentNullException), "Value cannot be null.\r\nParameter name: args")] + public void MethodCallCtorWontAcceptNullArgs() + { + MethodInfo method = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }); + MethodCallUtil.StringPresentation(null,method, null); + } + + [Test] + public void MethodCallWithArgumentsMissing() + { + MethodInfo method = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }); + Assert.AreEqual("String.StartsWith(missing parameter);", MethodCallUtil.StringPresentation(null,method, new object[0])); + + } + + #region Implementation + + private static Type[] TypesFromArgs(object[] args) + { + Type[] types = new Type[args.Length]; + for (int i = 0; i < args.Length; i++) + { + types[i] = args[i].GetType(); + } + return types; + } + + public static MethodInfo GetMethodInfo(string name, params object[] args) + { + Type[] types = TypesFromArgs(args); + MethodInfo method = typeof (string).GetMethod(name, types); + return method; + } + + #endregion + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/Utilities/ReturnValueUtilTests.cs b/Rhino.Mocks.Tests/Utilities/ReturnValueUtilTests.cs index 60c42e73..aad5f46c 100644 --- a/Rhino.Mocks.Tests/Utilities/ReturnValueUtilTests.cs +++ b/Rhino.Mocks.Tests/Utilities/ReturnValueUtilTests.cs @@ -1,57 +1,57 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using MbUnit.Framework; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Tests.Utilities -{ - [TestFixture] - public class ReturnValueUtilTests - { - [Test] - public void DefaultReturnValue() - { - Assert.IsNull(ReturnValueUtil.DefaultValue(typeof (string),null)); - Assert.AreEqual(0, ReturnValueUtil.DefaultValue(typeof (int),null)); - Assert.AreEqual((short) 0, ReturnValueUtil.DefaultValue(typeof (short),null)); - Assert.AreEqual((char) 0, ReturnValueUtil.DefaultValue(typeof (char),null)); - Assert.AreEqual(0L, ReturnValueUtil.DefaultValue(typeof (long),null)); - Assert.AreEqual(0f, ReturnValueUtil.DefaultValue(typeof (float),null)); - Assert.AreEqual(0d, ReturnValueUtil.DefaultValue(typeof (double),null)); - Assert.AreEqual(TestEnum.DefaultValue, ReturnValueUtil.DefaultValue(typeof (TestEnum),null)); - } - - private enum TestEnum - { - DefaultValue, - NonDefaultValue - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using MbUnit.Framework; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Tests.Utilities +{ + [TestFixture] + public class ReturnValueUtilTests + { + [Test] + public void DefaultReturnValue() + { + Assert.IsNull(ReturnValueUtil.DefaultValue(typeof (string),null)); + Assert.AreEqual(0, ReturnValueUtil.DefaultValue(typeof (int),null)); + Assert.AreEqual((short) 0, ReturnValueUtil.DefaultValue(typeof (short),null)); + Assert.AreEqual((char) 0, ReturnValueUtil.DefaultValue(typeof (char),null)); + Assert.AreEqual(0L, ReturnValueUtil.DefaultValue(typeof (long),null)); + Assert.AreEqual(0f, ReturnValueUtil.DefaultValue(typeof (float),null)); + Assert.AreEqual(0d, ReturnValueUtil.DefaultValue(typeof (double),null)); + Assert.AreEqual(TestEnum.DefaultValue, ReturnValueUtil.DefaultValue(typeof (TestEnum),null)); + } + + private enum TestEnum + { + DefaultValue, + NonDefaultValue + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/VerifyTests.cs b/Rhino.Mocks.Tests/VerifyTests.cs index 23c666f4..5c010c2e 100644 --- a/Rhino.Mocks.Tests/VerifyTests.cs +++ b/Rhino.Mocks.Tests/VerifyTests.cs @@ -1,67 +1,67 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - using System; - using MbUnit.Framework; - - [TestFixture] - public class VerifyTests - { - private MockRepository mocks; - private ConcreteDemo demoParam; - private IDemo demo; - - [SetUp] - public void SetUp() - { - mocks = new MockRepository(); - demoParam = mocks.StrictMock(typeof(ConcreteDemo)) as ConcreteDemo; - demo = mocks.StrictMock(typeof(IDemo)) as IDemo; - } - - [TearDown] - public void Teardown() - { - mocks.VerifyAll(); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException))] - public void MockParameterToStringShouldBeIgnoredIfItIsInVerifyState() - { - demo.VoidConcreteDemo(demoParam); - mocks.ReplayAll(); - mocks.Verify(demoParam); - mocks.Verify(demo); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + using System; + using MbUnit.Framework; + + [TestFixture] + public class VerifyTests + { + private MockRepository mocks; + private ConcreteDemo demoParam; + private IDemo demo; + + [SetUp] + public void SetUp() + { + mocks = new MockRepository(); + demoParam = mocks.StrictMock(typeof(ConcreteDemo)) as ConcreteDemo; + demo = mocks.StrictMock(typeof(IDemo)) as IDemo; + } + + [TearDown] + public void Teardown() + { + mocks.VerifyAll(); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException))] + public void MockParameterToStringShouldBeIgnoredIfItIsInVerifyState() + { + demo.VoidConcreteDemo(demoParam); + mocks.ReplayAll(); + mocks.Verify(demoParam); + mocks.Verify(demo); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks.Tests/WhenCalledTests.cs b/Rhino.Mocks.Tests/WhenCalledTests.cs index 6691b063..5d55d297 100644 --- a/Rhino.Mocks.Tests/WhenCalledTests.cs +++ b/Rhino.Mocks.Tests/WhenCalledTests.cs @@ -1,54 +1,54 @@ -#if DOTNET35 -using MbUnit.Framework; - - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class WhenCalledTests - { - [Test] - public void Shortcut_to_arg_is_equal() - { - // minor hack to get this to work reliably, we reset the arg manager, - // and restore on in the MockRepository ctor, so we do it this way - new MockRepository(); - Assert.AreEqual(Arg.Is(1), Arg.Is.Equal(1)); - } - - [Test] - public void Can_use_when_called_to_exceute_code_when_exceptation_is_matched_without_stupid_delegate_sig_overhead() - { - var wasCalled = false; - var stub = MockRepository.GenerateStub(); - stub.Stub(x => x.StringArgString(Arg.Is(""))) - .Return("blah") - .WhenCalled(delegate { wasCalled = true; }); - Assert.AreEqual("blah", stub.StringArgString("")); - Assert.IsTrue(wasCalled); - } - - [Test] - public void Can_modify_return_value() - { - var stub = MockRepository.GenerateStub(); - stub.Stub(x => x.StringArgString(Arg.Is(""))) - .Return("blah") - .WhenCalled(invocation => invocation.ReturnValue = "arg"); - Assert.AreEqual("arg", stub.StringArgString("")); - } - - [Test] - public void Can_inspect_method_arguments() - { - var stub = MockRepository.GenerateStub(); - stub.Stub(x => x.StringArgString(null)) - .IgnoreArguments() - .Return("blah") - .WhenCalled(invocation => Assert.AreEqual("foo", invocation.Arguments[0])); - Assert.AreEqual("blah", stub.StringArgString("foo")); - } - - } -} +#if DOTNET35 +using MbUnit.Framework; + + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class WhenCalledTests + { + [Test] + public void Shortcut_to_arg_is_equal() + { + // minor hack to get this to work reliably, we reset the arg manager, + // and restore on in the MockRepository ctor, so we do it this way + new MockRepository(); + Assert.AreEqual(Arg.Is(1), Arg.Is.Equal(1)); + } + + [Test] + public void Can_use_when_called_to_exceute_code_when_exceptation_is_matched_without_stupid_delegate_sig_overhead() + { + var wasCalled = false; + var stub = MockRepository.GenerateStub(); + stub.Stub(x => x.StringArgString(Arg.Is(""))) + .Return("blah") + .WhenCalled(delegate { wasCalled = true; }); + Assert.AreEqual("blah", stub.StringArgString("")); + Assert.IsTrue(wasCalled); + } + + [Test] + public void Can_modify_return_value() + { + var stub = MockRepository.GenerateStub(); + stub.Stub(x => x.StringArgString(Arg.Is(""))) + .Return("blah") + .WhenCalled(invocation => invocation.ReturnValue = "arg"); + Assert.AreEqual("arg", stub.StringArgString("")); + } + + [Test] + public void Can_inspect_method_arguments() + { + var stub = MockRepository.GenerateStub(); + stub.Stub(x => x.StringArgString(null)) + .IgnoreArguments() + .Return("blah") + .WhenCalled(invocation => Assert.AreEqual("foo", invocation.Arguments[0])); + Assert.AreEqual("blah", stub.StringArgString("foo")); + } + + } +} #endif \ No newline at end of file diff --git a/Rhino.Mocks.Tests/WithTestFixture.cs b/Rhino.Mocks.Tests/WithTestFixture.cs index 9368c747..d4d49845 100644 --- a/Rhino.Mocks.Tests/WithTestFixture.cs +++ b/Rhino.Mocks.Tests/WithTestFixture.cs @@ -1,203 +1,203 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using MbUnit.Framework; -using Rhino.Mocks.Exceptions; - -namespace Rhino.Mocks.Tests -{ - [TestFixture] - public class WithTestFixture - { - [Test] - public void SetupMyOwnRepository() - { - MockRepository mocks = new MockRepository(); - IDemo demo = mocks.StrictMock(); - With.Mocks(mocks,delegate - { - Expect.Call(demo.ReturnStringNoArgs()).Return("Hi"); - Mocker.Current.ReplayAll(); - Assert.AreEqual("Hi", demo.ReturnStringNoArgs()); - }); - } - [Test] - public void UsingTheWithMocksConstruct() - { - With.Mocks(new MockRepository(),delegate - { - IDemo demo = Mocker.Current.StrictMock(); - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - Mocker.Current.ReplayAll(); - Assert.AreEqual(5, demo.ReturnIntNoArgs()); - }); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException),"You cannot use Mocker.Current outside of a With.Mocks block")] - public void CannotUseMockerOutsideOfWithMocks() - { - MockRepository dummy = Mocker.Current; - - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IDemo.ReturnIntNoArgs(); Expected #1, Actual #0.")] - public void UsingTheWithMocksConstruct_ThrowsIfExpectationIsMissed() - { - With.Mocks(delegate - { - IDemo demo = Mocker.Current.StrictMock(); - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - Mocker.Current.ReplayAll(); - }); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException), "This action is invalid when the mock object {Rhino.Mocks.Tests.IDemo} is in record state.")] - public void UsingTheWithMocksConstruct_ThrowsIfReplayAllNotCalled() - { - With.Mocks(delegate - { - IDemo demo = Mocker.Current.StrictMock(); - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - }); - } - - - [Test] - [ExpectedException(typeof(IndexOutOfRangeException), "foo")] - public void UsingTheWithMocksConstruct_GiveCorrectExceptionWhenMocking() - { - With.Mocks(delegate - { - IDemo demo = Mocker.Current.StrictMock(); - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - Mocker.Current.ReplayAll(); - throw new IndexOutOfRangeException("foo"); - }); - } - - - [Test] - [ExpectedException(typeof(IndexOutOfRangeException), "foo")] - public void UsingTheWithMocksConstruct_GiveCorrectExceptionWhenMockingEvenIfReplayAllNotCalled() - { - With.Mocks(delegate - { - IDemo demo = Mocker.Current.StrictMock(); - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - throw new IndexOutOfRangeException("foo"); - }); - } - - [Test] - public void UsingTheWithMocksExceptingVerifyConstruct() - { - MockRepository mocks = new MockRepository(); - IDemo demo = mocks.StrictMock(); - - With.Mocks(mocks) - .Expecting(delegate - { - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - }) - .Verify(delegate - { - Assert.AreEqual(5, demo.ReturnIntNoArgs()); - }); - } - - [Test] - [ExpectedException(typeof(ExpectationViolationException), "IDemo.ReturnIntNoArgs(); Expected #1, Actual #0.")] - public void UsingTheWithMocksExceptingVerifyConstruct_ThrowsIfExpectationIsMissed() - { - MockRepository mocks = new MockRepository(); - IDemo demo = mocks.StrictMock(); - - With.Mocks(mocks) - .Expecting(delegate - { - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - }) - .Verify(delegate - { - }); - } - - [Test] - [ExpectedException(typeof(IndexOutOfRangeException), "foo")] - public void UsingTheWithMocksExceptingVerifyConstruct_GiveCorrectExceptionWhenMocking() - { - MockRepository mocks = new MockRepository(); - IDemo demo = mocks.StrictMock(); - - With.Mocks(mocks) - .Expecting(delegate - { - Expect.Call(demo.ReturnIntNoArgs()).Return(5); - }) - .Verify(delegate - { - throw new IndexOutOfRangeException("foo"); - }); - } - - [Test] - public void UsingTheWithMocksExceptingInSameOrderVerifyConstruct_ShouldTakeCareOfOrder() - { - MockRepository mocks = new MockRepository(); - IDemo demo = mocks.StrictMock(); - bool verificationFailed; - - try - { - With.Mocks(mocks).ExpectingInSameOrder(delegate - { - Expect.Call(demo.ReturnIntNoArgs()).Return(1); - Expect.Call(demo.ReturnStringNoArgs()).Return("2"); - }) - .Verify(delegate - { - demo.ReturnStringNoArgs(); - demo.ReturnIntNoArgs(); - }); - verificationFailed = false; - } - catch (ExpectationViolationException) - { - verificationFailed = true; - } - - Assert.IsTrue(verificationFailed, - "Verification was supposed to fail, because the mocks are called in the wrong order"); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using MbUnit.Framework; +using Rhino.Mocks.Exceptions; + +namespace Rhino.Mocks.Tests +{ + [TestFixture] + public class WithTestFixture + { + [Test] + public void SetupMyOwnRepository() + { + MockRepository mocks = new MockRepository(); + IDemo demo = mocks.StrictMock(); + With.Mocks(mocks,delegate + { + Expect.Call(demo.ReturnStringNoArgs()).Return("Hi"); + Mocker.Current.ReplayAll(); + Assert.AreEqual("Hi", demo.ReturnStringNoArgs()); + }); + } + [Test] + public void UsingTheWithMocksConstruct() + { + With.Mocks(new MockRepository(),delegate + { + IDemo demo = Mocker.Current.StrictMock(); + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + Mocker.Current.ReplayAll(); + Assert.AreEqual(5, demo.ReturnIntNoArgs()); + }); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException),"You cannot use Mocker.Current outside of a With.Mocks block")] + public void CannotUseMockerOutsideOfWithMocks() + { + MockRepository dummy = Mocker.Current; + + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IDemo.ReturnIntNoArgs(); Expected #1, Actual #0.")] + public void UsingTheWithMocksConstruct_ThrowsIfExpectationIsMissed() + { + With.Mocks(delegate + { + IDemo demo = Mocker.Current.StrictMock(); + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + Mocker.Current.ReplayAll(); + }); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException), "This action is invalid when the mock object {Rhino.Mocks.Tests.IDemo} is in record state.")] + public void UsingTheWithMocksConstruct_ThrowsIfReplayAllNotCalled() + { + With.Mocks(delegate + { + IDemo demo = Mocker.Current.StrictMock(); + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + }); + } + + + [Test] + [ExpectedException(typeof(IndexOutOfRangeException), "foo")] + public void UsingTheWithMocksConstruct_GiveCorrectExceptionWhenMocking() + { + With.Mocks(delegate + { + IDemo demo = Mocker.Current.StrictMock(); + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + Mocker.Current.ReplayAll(); + throw new IndexOutOfRangeException("foo"); + }); + } + + + [Test] + [ExpectedException(typeof(IndexOutOfRangeException), "foo")] + public void UsingTheWithMocksConstruct_GiveCorrectExceptionWhenMockingEvenIfReplayAllNotCalled() + { + With.Mocks(delegate + { + IDemo demo = Mocker.Current.StrictMock(); + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + throw new IndexOutOfRangeException("foo"); + }); + } + + [Test] + public void UsingTheWithMocksExceptingVerifyConstruct() + { + MockRepository mocks = new MockRepository(); + IDemo demo = mocks.StrictMock(); + + With.Mocks(mocks) + .Expecting(delegate + { + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + }) + .Verify(delegate + { + Assert.AreEqual(5, demo.ReturnIntNoArgs()); + }); + } + + [Test] + [ExpectedException(typeof(ExpectationViolationException), "IDemo.ReturnIntNoArgs(); Expected #1, Actual #0.")] + public void UsingTheWithMocksExceptingVerifyConstruct_ThrowsIfExpectationIsMissed() + { + MockRepository mocks = new MockRepository(); + IDemo demo = mocks.StrictMock(); + + With.Mocks(mocks) + .Expecting(delegate + { + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + }) + .Verify(delegate + { + }); + } + + [Test] + [ExpectedException(typeof(IndexOutOfRangeException), "foo")] + public void UsingTheWithMocksExceptingVerifyConstruct_GiveCorrectExceptionWhenMocking() + { + MockRepository mocks = new MockRepository(); + IDemo demo = mocks.StrictMock(); + + With.Mocks(mocks) + .Expecting(delegate + { + Expect.Call(demo.ReturnIntNoArgs()).Return(5); + }) + .Verify(delegate + { + throw new IndexOutOfRangeException("foo"); + }); + } + + [Test] + public void UsingTheWithMocksExceptingInSameOrderVerifyConstruct_ShouldTakeCareOfOrder() + { + MockRepository mocks = new MockRepository(); + IDemo demo = mocks.StrictMock(); + bool verificationFailed; + + try + { + With.Mocks(mocks).ExpectingInSameOrder(delegate + { + Expect.Call(demo.ReturnIntNoArgs()).Return(1); + Expect.Call(demo.ReturnStringNoArgs()).Return("2"); + }) + .Verify(delegate + { + demo.ReturnStringNoArgs(); + demo.ReturnIntNoArgs(); + }); + verificationFailed = false; + } + catch (ExpectationViolationException) + { + verificationFailed = true; + } + + Assert.IsTrue(verificationFailed, + "Verification was supposed to fail, because the mocks are called in the wrong order"); + } + } +} diff --git a/Rhino.Mocks.sln b/Rhino.Mocks.sln index 427807a5..7bd6d7ed 100644 --- a/Rhino.Mocks.sln +++ b/Rhino.Mocks.sln @@ -1,56 +1,56 @@ -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rhino.Mocks.Tests 3.5", "Rhino.Mocks.Tests\Rhino.Mocks.Tests.csproj", "{C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rhino.Mocks 3.5", "Rhino.Mocks\Rhino.Mocks.csproj", "{1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rhino.Mocks.Tests.Model", "Rhino.Mocks.Tests.Model\Rhino.Mocks.Tests.Model.csproj", "{3078B943-10A5-41FA-A68A-7C4FC98506A0}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|Mixed Platforms = Debug|Mixed Platforms - Debug|Win32 = Debug|Win32 - Release|Any CPU = Release|Any CPU - Release|Mixed Platforms = Release|Mixed Platforms - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Win32.ActiveCfg = Debug|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Any CPU.Build.0 = Release|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Win32.ActiveCfg = Release|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Win32.ActiveCfg = Debug|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Any CPU.Build.0 = Release|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Win32.ActiveCfg = Release|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Win32.ActiveCfg = Debug|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Any CPU.Build.0 = Release|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Win32.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(TextTemplating) = postSolution - TextTemplating = 1 - EndGlobalSection -EndGlobal +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rhino.Mocks.Tests 3.5", "Rhino.Mocks.Tests\Rhino.Mocks.Tests.csproj", "{C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rhino.Mocks 3.5", "Rhino.Mocks\Rhino.Mocks.csproj", "{1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Rhino.Mocks.Tests.Model", "Rhino.Mocks.Tests.Model\Rhino.Mocks.Tests.Model.csproj", "{3078B943-10A5-41FA-A68A-7C4FC98506A0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|Mixed Platforms = Debug|Mixed Platforms + Debug|Win32 = Debug|Win32 + Release|Any CPU = Release|Any CPU + Release|Mixed Platforms = Release|Mixed Platforms + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Debug|Win32.ActiveCfg = Debug|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Any CPU.Build.0 = Release|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {C63839EC-BEF3-4DCD-BE23-B6DA21E8BE20}.Release|Win32.ActiveCfg = Release|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Debug|Win32.ActiveCfg = Debug|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Any CPU.Build.0 = Release|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8}.Release|Win32.ActiveCfg = Release|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Debug|Win32.ActiveCfg = Debug|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Any CPU.Build.0 = Release|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {3078B943-10A5-41FA-A68A-7C4FC98506A0}.Release|Win32.ActiveCfg = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(TextTemplating) = postSolution + TextTemplating = 1 + EndGlobalSection +EndGlobal diff --git a/Rhino.Mocks/Arg.cs b/Rhino.Mocks/Arg.cs index ea374d17..9a4a00cd 100644 --- a/Rhino.Mocks/Arg.cs +++ b/Rhino.Mocks/Arg.cs @@ -1,141 +1,141 @@ -using System; -#if DOTNET35 -using System.Linq.Expressions; -#endif -using Rhino.Mocks.Constraints; - -namespace 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 - /// - /// - public static class Arg - { - -#if DOTNET35 - - /// - /// 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")))); - /// - /// - public static T Matches(Expression> predicate) - { - ArgManager.AddInArgument(new LambdaConstraint(predicate)); - return default(T); - } -#else - /// - /// 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")))); - /// - /// - public static T Matches(Predicate predicate) - { - ArgManager.AddInArgument(Rhino.Mocks.Constraints.Is.Matching(predicate)); - return default(T); - } -#endif - - /// - /// Define a simple constraint for this argument. (Use Matches in simple cases.) - /// Example: - /// Arg<int>.Is.Anthing - /// Arg<string>.Is.Equal("hello") - /// - public static IsArg Is { get { return new IsArg(); } } - - /// - /// 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 - public static T Matches(AbstractConstraint constraint) - { - ArgManager.AddInArgument(constraint); - return default(T); - } - - /// - /// Define a Ref argument. - /// - /// Constraints for this argument - /// value returned by the mock - /// - public static OutRefArgDummy Ref(AbstractConstraint constraint, T returnValue) - { - ArgManager.AddRefArgument(constraint, returnValue); - return new OutRefArgDummy(); - } - - /// - /// 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 ); - /// - /// - /// - public static OutRefArgDummy Out(T returnValue) - { - ArgManager.AddOutArgument(returnValue); - return new OutRefArgDummy(); - } - - /// - /// Define Constraints on list arguments. - /// - public static ListArg List - { - get - { - return new ListArg(); - } - } - - } - - /// - /// Use the Arg class (without generic) to define Text constraints - /// - public static class Arg - { - /// - /// Define constraints on text arguments. - /// - public static TextArg Text { get { return new TextArg(); } } - - /// - /// Evaluate an equal constraint for . - /// - /// The object the parameter should equal to - public static T Is(T arg) - { - return Arg.Is.Equal(arg); - } - } -} - +using System; +#if DOTNET35 +using System.Linq.Expressions; +#endif +using Rhino.Mocks.Constraints; + +namespace 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 + /// + /// + public static class Arg + { + +#if DOTNET35 + + /// + /// 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")))); + /// + /// + public static T Matches(Expression> predicate) + { + ArgManager.AddInArgument(new LambdaConstraint(predicate)); + return default(T); + } +#else + /// + /// 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")))); + /// + /// + public static T Matches(Predicate predicate) + { + ArgManager.AddInArgument(Rhino.Mocks.Constraints.Is.Matching(predicate)); + return default(T); + } +#endif + + /// + /// Define a simple constraint for this argument. (Use Matches in simple cases.) + /// Example: + /// Arg<int>.Is.Anthing + /// Arg<string>.Is.Equal("hello") + /// + public static IsArg Is { get { return new IsArg(); } } + + /// + /// 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 + public static T Matches(AbstractConstraint constraint) + { + ArgManager.AddInArgument(constraint); + return default(T); + } + + /// + /// Define a Ref argument. + /// + /// Constraints for this argument + /// value returned by the mock + /// + public static OutRefArgDummy Ref(AbstractConstraint constraint, T returnValue) + { + ArgManager.AddRefArgument(constraint, returnValue); + return new OutRefArgDummy(); + } + + /// + /// 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 ); + /// + /// + /// + public static OutRefArgDummy Out(T returnValue) + { + ArgManager.AddOutArgument(returnValue); + return new OutRefArgDummy(); + } + + /// + /// Define Constraints on list arguments. + /// + public static ListArg List + { + get + { + return new ListArg(); + } + } + + } + + /// + /// Use the Arg class (without generic) to define Text constraints + /// + public static class Arg + { + /// + /// Define constraints on text arguments. + /// + public static TextArg Text { get { return new TextArg(); } } + + /// + /// Evaluate an equal constraint for . + /// + /// The object the parameter should equal to + public static T Is(T arg) + { + return Arg.Is.Equal(arg); + } + } +} + diff --git a/Rhino.Mocks/ArgManager.cs b/Rhino.Mocks/ArgManager.cs index d20cfcd9..2c329858 100644 --- a/Rhino.Mocks/ArgManager.cs +++ b/Rhino.Mocks/ArgManager.cs @@ -1,211 +1,211 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -//using System.Linq; -using System.Text; -using System.Collections; -using Rhino.Mocks.Constraints; -using System.Reflection; - -namespace Rhino.Mocks -{ - - /// - /// Used to manage the static state of the Arg<T> class"/> - /// - internal class ArgManager - { - [ThreadStatic] - private static List args; - - - internal static bool HasBeenUsed - { - get - { - if (args == null) return false; - return args.Count > 0; - } - } - - /// - /// Resets the static state - /// - internal static void Clear() - { - args = new List(); - } - - internal static void AddInArgument(AbstractConstraint constraint) - { - InitializeThreadStatic(); - args.Add(new ArgumentDefinition(constraint)); - } - - internal static void AddOutArgument(object returnValue) - { - InitializeThreadStatic(); - args.Add(new ArgumentDefinition(returnValue)); - } - - internal static void AddRefArgument(AbstractConstraint constraint, object returnValue) - { - InitializeThreadStatic(); - args.Add(new ArgumentDefinition(constraint, returnValue)); - } - - - /// - /// 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 - /// - /// - internal static object[] GetAllReturnValues() - { - InitializeThreadStatic(); - List returnValues = new List(); - foreach (ArgumentDefinition arg in args) - { - if (arg.InOutRef == InOutRefArgument.OutArg || arg.InOutRef == InOutRefArgument.RefArg) - { - returnValues.Add(arg.returnValue); - } - } - return returnValues.ToArray(); - } - - /// - /// Returns the constraints for all arguments. - /// Out arguments have an Is.Anything constraint and are also in the list. - /// - /// - internal static AbstractConstraint[] GetAllConstraints() - { - InitializeThreadStatic(); - List constraints = new List(); - foreach (ArgumentDefinition arg in args) - { - constraints.Add(arg.constraint); - } - return constraints.ToArray(); - } - - internal static void CheckMethodSignature(MethodInfo method) - { - InitializeThreadStatic(); - ParameterInfo[] parameters = method.GetParameters(); - AbstractConstraint[] constraints = new AbstractConstraint[parameters.Length]; - - if (args.Count < parameters.Length) - { - throw new InvalidOperationException( - string.Format("When using Arg, all arguments must be defined using Arg.Is, Arg.Text, Arg.List, Arg.Ref or Arg.Out. {0} arguments expected, {1} have been defined.", - parameters.Length, args.Count)); - } - if (args.Count > parameters.Length) - { - throw new InvalidOperationException( - string.Format("Use Arg ONLY within a mock method call while recording. {0} arguments expected, {1} have been defined.", - parameters.Length, args.Count)); - } - - for (int i = 0; i < parameters.Length; i++) - { - if (parameters[i].IsOut) - { - if (args[i].InOutRef != InOutRefArgument.OutArg) - { - throw new InvalidOperationException( - string.Format("Argument {0} must be defined as: out Arg.Out(returnvalue).Dummy", - i)); - } - } - else if (parameters[i].ParameterType.IsByRef) - { - if (args[i].InOutRef != InOutRefArgument.RefArg) - { - throw new InvalidOperationException( - string.Format("Argument {0} must be defined as: ref Arg.Ref(constraint, returnvalue).Dummy", - i)); - } - } - else if (args[i].InOutRef != InOutRefArgument.InArg) - { - throw new InvalidOperationException( - string.Format("Argument {0} must be defined using: Arg.Is, Arg.Text or Arg.List", - i)); - } - } - } - - private static void InitializeThreadStatic() - { - if (args == null) - { - args = new List(); - } - } - - private struct ArgumentDefinition - { - public InOutRefArgument InOutRef; - public AbstractConstraint constraint; - public object returnValue; - public ArgumentDefinition(AbstractConstraint constraint) - { - this.InOutRef = InOutRefArgument.InArg; - this.constraint = constraint; - this.returnValue = null; - } - public ArgumentDefinition(AbstractConstraint constraint, object returnValue) - { - this.InOutRef = InOutRefArgument.RefArg; - this.constraint = constraint; - this.returnValue = returnValue; - } - public ArgumentDefinition(object returnValue) - { - this.InOutRef = InOutRefArgument.OutArg; - this.returnValue = returnValue; - this.constraint = Is.Anything(); - } - - } - - private enum InOutRefArgument - { - InArg, - OutArg, - RefArg - } - - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.Collections.Generic; +//using System.Linq; +using System.Text; +using System.Collections; +using Rhino.Mocks.Constraints; +using System.Reflection; + +namespace Rhino.Mocks +{ + + /// + /// Used to manage the static state of the Arg<T> class"/> + /// + internal class ArgManager + { + [ThreadStatic] + private static List args; + + + internal static bool HasBeenUsed + { + get + { + if (args == null) return false; + return args.Count > 0; + } + } + + /// + /// Resets the static state + /// + internal static void Clear() + { + args = new List(); + } + + internal static void AddInArgument(AbstractConstraint constraint) + { + InitializeThreadStatic(); + args.Add(new ArgumentDefinition(constraint)); + } + + internal static void AddOutArgument(object returnValue) + { + InitializeThreadStatic(); + args.Add(new ArgumentDefinition(returnValue)); + } + + internal static void AddRefArgument(AbstractConstraint constraint, object returnValue) + { + InitializeThreadStatic(); + args.Add(new ArgumentDefinition(constraint, returnValue)); + } + + + /// + /// 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 + /// + /// + internal static object[] GetAllReturnValues() + { + InitializeThreadStatic(); + List returnValues = new List(); + foreach (ArgumentDefinition arg in args) + { + if (arg.InOutRef == InOutRefArgument.OutArg || arg.InOutRef == InOutRefArgument.RefArg) + { + returnValues.Add(arg.returnValue); + } + } + return returnValues.ToArray(); + } + + /// + /// Returns the constraints for all arguments. + /// Out arguments have an Is.Anything constraint and are also in the list. + /// + /// + internal static AbstractConstraint[] GetAllConstraints() + { + InitializeThreadStatic(); + List constraints = new List(); + foreach (ArgumentDefinition arg in args) + { + constraints.Add(arg.constraint); + } + return constraints.ToArray(); + } + + internal static void CheckMethodSignature(MethodInfo method) + { + InitializeThreadStatic(); + ParameterInfo[] parameters = method.GetParameters(); + AbstractConstraint[] constraints = new AbstractConstraint[parameters.Length]; + + if (args.Count < parameters.Length) + { + throw new InvalidOperationException( + string.Format("When using Arg, all arguments must be defined using Arg.Is, Arg.Text, Arg.List, Arg.Ref or Arg.Out. {0} arguments expected, {1} have been defined.", + parameters.Length, args.Count)); + } + if (args.Count > parameters.Length) + { + throw new InvalidOperationException( + string.Format("Use Arg ONLY within a mock method call while recording. {0} arguments expected, {1} have been defined.", + parameters.Length, args.Count)); + } + + for (int i = 0; i < parameters.Length; i++) + { + if (parameters[i].IsOut) + { + if (args[i].InOutRef != InOutRefArgument.OutArg) + { + throw new InvalidOperationException( + string.Format("Argument {0} must be defined as: out Arg.Out(returnvalue).Dummy", + i)); + } + } + else if (parameters[i].ParameterType.IsByRef) + { + if (args[i].InOutRef != InOutRefArgument.RefArg) + { + throw new InvalidOperationException( + string.Format("Argument {0} must be defined as: ref Arg.Ref(constraint, returnvalue).Dummy", + i)); + } + } + else if (args[i].InOutRef != InOutRefArgument.InArg) + { + throw new InvalidOperationException( + string.Format("Argument {0} must be defined using: Arg.Is, Arg.Text or Arg.List", + i)); + } + } + } + + private static void InitializeThreadStatic() + { + if (args == null) + { + args = new List(); + } + } + + private struct ArgumentDefinition + { + public InOutRefArgument InOutRef; + public AbstractConstraint constraint; + public object returnValue; + public ArgumentDefinition(AbstractConstraint constraint) + { + this.InOutRef = InOutRefArgument.InArg; + this.constraint = constraint; + this.returnValue = null; + } + public ArgumentDefinition(AbstractConstraint constraint, object returnValue) + { + this.InOutRef = InOutRefArgument.RefArg; + this.constraint = constraint; + this.returnValue = returnValue; + } + public ArgumentDefinition(object returnValue) + { + this.InOutRef = InOutRefArgument.OutArg; + this.returnValue = returnValue; + this.constraint = Is.Anything(); + } + + } + + private enum InOutRefArgument + { + InArg, + OutArg, + RefArg + } + + } +} diff --git a/Rhino.Mocks/BackToRecordOptions.cs b/Rhino.Mocks/BackToRecordOptions.cs index 2b9a4860..cdde657e 100644 --- a/Rhino.Mocks/BackToRecordOptions.cs +++ b/Rhino.Mocks/BackToRecordOptions.cs @@ -1,36 +1,36 @@ -using System; - -namespace Rhino.Mocks -{ - /// - /// What should BackToRecord clear - /// - [Flags] - public enum BackToRecordOptions - { - /// - /// Retain all expectations and behaviors and return to mock - /// - None = 0, - /// - /// All expectations - /// - Expectations = 1, - /// - /// Event subscribers for this instance - /// - EventSubscribers = 2, - /// - /// Methods that should be forwarded to the base class implementation - /// - OriginalMethodsToCall = 4, - /// - /// Properties that should behave like properties - /// - PropertyBehavior = 8, - /// - /// Remove all the behavior of the object - /// - All = Expectations | EventSubscribers | OriginalMethodsToCall | PropertyBehavior - } +using System; + +namespace Rhino.Mocks +{ + /// + /// What should BackToRecord clear + /// + [Flags] + public enum BackToRecordOptions + { + /// + /// Retain all expectations and behaviors and return to mock + /// + None = 0, + /// + /// All expectations + /// + Expectations = 1, + /// + /// Event subscribers for this instance + /// + EventSubscribers = 2, + /// + /// Methods that should be forwarded to the base class implementation + /// + OriginalMethodsToCall = 4, + /// + /// Properties that should behave like properties + /// + PropertyBehavior = 8, + /// + /// Remove all the behavior of the object + /// + All = Expectations | EventSubscribers | OriginalMethodsToCall | PropertyBehavior + } } \ No newline at end of file diff --git a/Rhino.Mocks/CompatabilityWith2.0.cs b/Rhino.Mocks/CompatabilityWith2.0.cs index 87f433e3..238dd39e 100644 --- a/Rhino.Mocks/CompatabilityWith2.0.cs +++ b/Rhino.Mocks/CompatabilityWith2.0.cs @@ -1,20 +1,20 @@ -namespace Rhino.Mocks -{ - using System; - /// - /// This delegate is compatible with the System.Func{T,R} signature - /// We have to define our own to get compatability with 2.0 - /// - public delegate R Function(T t); - -#if FOR_NET_2_0 - /// - /// This is here to allow compiling on the 2.0 platform with extension methods - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] - public class ExtensionAttribute : Attribute - { - } - -#endif +namespace Rhino.Mocks +{ + using System; + /// + /// This delegate is compatible with the System.Func{T,R} signature + /// We have to define our own to get compatability with 2.0 + /// + public delegate R Function(T t); + +#if FOR_NET_2_0 + /// + /// This is here to allow compiling on the 2.0 platform with extension methods + /// + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] + public class ExtensionAttribute : Attribute + { + } + +#endif } \ No newline at end of file diff --git a/Rhino.Mocks/Constraints/AbstractConstraint.cs b/Rhino.Mocks/Constraints/AbstractConstraint.cs index d74238b2..4f925a5c 100644 --- a/Rhino.Mocks/Constraints/AbstractConstraint.cs +++ b/Rhino.Mocks/Constraints/AbstractConstraint.cs @@ -1,92 +1,92 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -namespace Rhino.Mocks.Constraints -{ - /// - /// Interface for constraints - /// - public abstract class AbstractConstraint - { - /// - /// Determines if the object pass the constraints - /// - public abstract bool Eval(object obj); - - /// - /// Gets the message for this constraint - /// - /// - public abstract string Message { get; } - - /// - /// And operator for constraints - /// - public static AbstractConstraint operator &(AbstractConstraint c1, AbstractConstraint c2) - { - return new And(c1, c2); - } - - /// - /// Not operator for constraints - /// - public static AbstractConstraint operator !(AbstractConstraint c1) - { - return new Not(c1); - } - - - /// - /// Or operator for constraints - /// - public static AbstractConstraint operator |(AbstractConstraint c1, AbstractConstraint c2) - { - return new Or(c1, c2); - } - - /// - /// Allow overriding of || or && - /// - /// - /// - public static bool operator false(AbstractConstraint c) - { - return false; - } - /// - /// Allow overriding of || or && - /// - /// - /// - public static bool operator true(AbstractConstraint c) - { - return false; - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +namespace Rhino.Mocks.Constraints +{ + /// + /// Interface for constraints + /// + public abstract class AbstractConstraint + { + /// + /// Determines if the object pass the constraints + /// + public abstract bool Eval(object obj); + + /// + /// Gets the message for this constraint + /// + /// + public abstract string Message { get; } + + /// + /// And operator for constraints + /// + public static AbstractConstraint operator &(AbstractConstraint c1, AbstractConstraint c2) + { + return new And(c1, c2); + } + + /// + /// Not operator for constraints + /// + public static AbstractConstraint operator !(AbstractConstraint c1) + { + return new Not(c1); + } + + + /// + /// Or operator for constraints + /// + public static AbstractConstraint operator |(AbstractConstraint c1, AbstractConstraint c2) + { + return new Or(c1, c2); + } + + /// + /// Allow overriding of || or && + /// + /// + /// + public static bool operator false(AbstractConstraint c) + { + return false; + } + /// + /// Allow overriding of || or && + /// + /// + /// + public static bool operator true(AbstractConstraint c) + { + return false; + } + } +} diff --git a/Rhino.Mocks/Constraints/AllPropertiesMatchConstraint.cs b/Rhino.Mocks/Constraints/AllPropertiesMatchConstraint.cs index 3afa46da..92f09926 100644 --- a/Rhino.Mocks/Constraints/AllPropertiesMatchConstraint.cs +++ b/Rhino.Mocks/Constraints/AllPropertiesMatchConstraint.cs @@ -1,286 +1,286 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using System.Reflection; - -namespace Rhino.Mocks.Constraints -{ - internal class AllPropertiesMatchConstraint : AbstractConstraint - { - private object _expected; //object holding the expected property values. - private string _message; //the message that Rhino Mocks will show. - private Stack _properties; //used to build the property name like Order.Product.Price for the message. - private List _checkedObjects; //every object that is matched goes in this list to prevent recursive loops. - - /// - /// Initializes a new constraint object. - /// - /// The expected object, The actual object is passed in as a parameter to the method - public AllPropertiesMatchConstraint(object expected) - { - _expected = expected; - _properties = new Stack(); - _checkedObjects = new List(); - } - - /// - /// Evaluate this constraint. - /// - /// The actual object that was passed in the method call to the mock. - /// True when the constraint is met, else false. - public override bool Eval(object obj) - { - _properties.Clear(); - _checkedObjects.Clear(); - _properties.Push(obj.GetType().Name); - bool result = CheckReferenceType(_expected, obj); - _properties.Pop(); - _checkedObjects.Clear(); - return result; - } - - /// - /// Rhino.Mocks uses this property to generate an error message. - /// - /// - /// A message telling the tester why the constraint failed. - /// - public override string Message - { - get { return _message; } - } - - - /// - /// 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. - protected virtual bool CheckReferenceType(object expected, object actual) - { - Type tExpected = expected.GetType(); - Type tActual = actual.GetType(); - - - if (tExpected != tActual) - { - _message = string.Format("Expected type '{0}' doesn't match with actual type '{1}'", tExpected.Name, tActual.Name); - return false; - } - - return CheckValue(expected, actual); - } - - /// - /// - /// - /// - /// - /// - /// This is the real heart of the beast. - protected virtual bool CheckValue(object expected, object actual) - { - if (actual == null && expected != null) - { - _message = string.Format("Expected value of {0} is '{1}', actual value is null", BuildPropertyName(), expected); - return false; - } - - if (expected == null) - { - if (actual != null) - { - _message = string.Format("Expected value of {0} is null, actual value is '{1}'", BuildPropertyName(), actual); - return false; - } - } - else - { - //if both objects are comparable Equals can be used to determine equality. (value types implement IComparable too when boxed) - if (expected is IComparable) - { - if (!expected.Equals(actual)) - { - _message = string.Format("Expected value of {0} is '{1}', actual value is '{2}'", BuildPropertyName(), expected.ToString(), actual.ToString()); - return false; - } - } - else if (expected is IEnumerable) //if both objects are lists we should tread them as such. - { - if (!CheckCollection((IEnumerable)expected, (IEnumerable)actual)) - { - return false; - } - } - else if (!_checkedObjects.Contains(expected)) //prevent endless recursive loops. - { - _checkedObjects.Add(expected); - if (!CheckProperties(expected, actual)) - { - return false; - } - if (!CheckFields(expected, actual)) - { - return false; - } - } - } - return true; - } - - - /// - /// 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. - protected virtual bool CheckProperties(object expected, object actual) - { - Type tExpected = expected.GetType(); - Type tActual = actual.GetType(); - - PropertyInfo[] properties = tExpected.GetProperties(BindingFlags.Instance | BindingFlags.Public); - foreach (PropertyInfo property in properties) - { - //TODO: deal with indexed properties - ParameterInfo[] indexParameters = property.GetIndexParameters(); - if (indexParameters.Length == 0) //It's not an indexed property - { - _properties.Push(property.Name); - - try - { - object expectedValue = property.GetValue(expected, null); - object actualValue = property.GetValue(actual, null); - - //if (!CheckValue(expectedValue, actualValue)) return false; - if (!CheckValue(expectedValue, actualValue)) return false; - } - catch (System.Reflection.TargetInvocationException) - { - //the inner exception should give you a clou about why we couldn't invoke GetValue... - //do nothing - } - - _properties.Pop(); - } - } - return true; - } - - - /// - /// 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. - protected virtual bool CheckFields(object expected, object actual) - { - Type tExpected = expected.GetType(); - Type tActual = actual.GetType(); - - _checkedObjects.Add(actual); - - FieldInfo[] fields = tExpected.GetFields(BindingFlags.Instance | BindingFlags.Public); - foreach (FieldInfo field in fields) - { - _properties.Push(field.Name); - - object expectedValue = field.GetValue(expected); - object actualValue = field.GetValue(actual); - - bool result = CheckValue(expectedValue, actualValue); - _properties.Pop(); - if (!result) return false; - } - - return true; - } - - - /// - /// Checks the items of both collections - /// - /// The expected collection - /// - /// True if both collections contain the same items in the same order. - private bool CheckCollection(IEnumerable expectedCollection, IEnumerable actualCollection) - { - if (expectedCollection != null) //only check the list if there is something in there. - { - IEnumerator expectedEnumerator = expectedCollection.GetEnumerator(); - IEnumerator actualEnumerator = actualCollection.GetEnumerator(); - bool expectedHasMore = expectedEnumerator.MoveNext(); - bool actualHasMore = actualEnumerator.MoveNext(); - int expectedCount = 0; - int actualCount = 0; - string name = _properties.Pop(); //pop the propertyname from the stack to be replaced by the same name with an index. - - while (expectedHasMore && actualHasMore) - { - object expectedValue = expectedEnumerator.Current; - object actualValue = actualEnumerator.Current; - - _properties.Push(name + string.Format("[{0}]", expectedCount)); //replace the earlier popped property name - - expectedCount++; - actualCount++; - - if (!CheckReferenceType(expectedValue, actualValue)) - { - return false; - } - - _properties.Pop(); //pop the old indexed property name to make place for a new one - - expectedHasMore = expectedEnumerator.MoveNext(); - actualHasMore = actualEnumerator.MoveNext(); - } - _properties.Push(name); //push the original property name back on the stack. - - //examine the expectedMoveNextResult and the actualMoveNextResult to see if one collection was bigger than the other. - if (expectedHasMore & !actualHasMore) //actual has less items than expected. - { - //find out how much items there are in the expected collection. - do expectedCount++; while (expectedEnumerator.MoveNext()); - } - if (!expectedHasMore & actualHasMore) //actual has more items than expected. - { - //find out how much items there are in the actual collection. - do actualCount++; while (actualEnumerator.MoveNext()); - } - if (expectedCount != actualCount) - { - _message = string.Format("expected number of items in collection {0} is '{1}', actual is '{2}'", BuildPropertyName(), expectedCount, actualCount); - return false; - } - } - return true; - } - - /// - /// Builds a propertyname from the Stack _properties like 'Order.Product.Price' - /// to be used in the error message. - /// - /// A nested property name. - private string BuildPropertyName() - { - StringBuilder result = new StringBuilder(); - string[] names = _properties.ToArray(); - foreach(string name in names) - { - if (result.Length > 0) - { - result.Insert(0, '.'); - } - result.Insert(0, name); - } - return result.ToString(); - } - } -} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Reflection; + +namespace Rhino.Mocks.Constraints +{ + internal class AllPropertiesMatchConstraint : AbstractConstraint + { + private object _expected; //object holding the expected property values. + private string _message; //the message that Rhino Mocks will show. + private Stack _properties; //used to build the property name like Order.Product.Price for the message. + private List _checkedObjects; //every object that is matched goes in this list to prevent recursive loops. + + /// + /// Initializes a new constraint object. + /// + /// The expected object, The actual object is passed in as a parameter to the method + public AllPropertiesMatchConstraint(object expected) + { + _expected = expected; + _properties = new Stack(); + _checkedObjects = new List(); + } + + /// + /// Evaluate this constraint. + /// + /// The actual object that was passed in the method call to the mock. + /// True when the constraint is met, else false. + public override bool Eval(object obj) + { + _properties.Clear(); + _checkedObjects.Clear(); + _properties.Push(obj.GetType().Name); + bool result = CheckReferenceType(_expected, obj); + _properties.Pop(); + _checkedObjects.Clear(); + return result; + } + + /// + /// Rhino.Mocks uses this property to generate an error message. + /// + /// + /// A message telling the tester why the constraint failed. + /// + public override string Message + { + get { return _message; } + } + + + /// + /// 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. + protected virtual bool CheckReferenceType(object expected, object actual) + { + Type tExpected = expected.GetType(); + Type tActual = actual.GetType(); + + + if (tExpected != tActual) + { + _message = string.Format("Expected type '{0}' doesn't match with actual type '{1}'", tExpected.Name, tActual.Name); + return false; + } + + return CheckValue(expected, actual); + } + + /// + /// + /// + /// + /// + /// + /// This is the real heart of the beast. + protected virtual bool CheckValue(object expected, object actual) + { + if (actual == null && expected != null) + { + _message = string.Format("Expected value of {0} is '{1}', actual value is null", BuildPropertyName(), expected); + return false; + } + + if (expected == null) + { + if (actual != null) + { + _message = string.Format("Expected value of {0} is null, actual value is '{1}'", BuildPropertyName(), actual); + return false; + } + } + else + { + //if both objects are comparable Equals can be used to determine equality. (value types implement IComparable too when boxed) + if (expected is IComparable) + { + if (!expected.Equals(actual)) + { + _message = string.Format("Expected value of {0} is '{1}', actual value is '{2}'", BuildPropertyName(), expected.ToString(), actual.ToString()); + return false; + } + } + else if (expected is IEnumerable) //if both objects are lists we should tread them as such. + { + if (!CheckCollection((IEnumerable)expected, (IEnumerable)actual)) + { + return false; + } + } + else if (!_checkedObjects.Contains(expected)) //prevent endless recursive loops. + { + _checkedObjects.Add(expected); + if (!CheckProperties(expected, actual)) + { + return false; + } + if (!CheckFields(expected, actual)) + { + return false; + } + } + } + return true; + } + + + /// + /// 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. + protected virtual bool CheckProperties(object expected, object actual) + { + Type tExpected = expected.GetType(); + Type tActual = actual.GetType(); + + PropertyInfo[] properties = tExpected.GetProperties(BindingFlags.Instance | BindingFlags.Public); + foreach (PropertyInfo property in properties) + { + //TODO: deal with indexed properties + ParameterInfo[] indexParameters = property.GetIndexParameters(); + if (indexParameters.Length == 0) //It's not an indexed property + { + _properties.Push(property.Name); + + try + { + object expectedValue = property.GetValue(expected, null); + object actualValue = property.GetValue(actual, null); + + //if (!CheckValue(expectedValue, actualValue)) return false; + if (!CheckValue(expectedValue, actualValue)) return false; + } + catch (System.Reflection.TargetInvocationException) + { + //the inner exception should give you a clou about why we couldn't invoke GetValue... + //do nothing + } + + _properties.Pop(); + } + } + return true; + } + + + /// + /// 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. + protected virtual bool CheckFields(object expected, object actual) + { + Type tExpected = expected.GetType(); + Type tActual = actual.GetType(); + + _checkedObjects.Add(actual); + + FieldInfo[] fields = tExpected.GetFields(BindingFlags.Instance | BindingFlags.Public); + foreach (FieldInfo field in fields) + { + _properties.Push(field.Name); + + object expectedValue = field.GetValue(expected); + object actualValue = field.GetValue(actual); + + bool result = CheckValue(expectedValue, actualValue); + _properties.Pop(); + if (!result) return false; + } + + return true; + } + + + /// + /// Checks the items of both collections + /// + /// The expected collection + /// + /// True if both collections contain the same items in the same order. + private bool CheckCollection(IEnumerable expectedCollection, IEnumerable actualCollection) + { + if (expectedCollection != null) //only check the list if there is something in there. + { + IEnumerator expectedEnumerator = expectedCollection.GetEnumerator(); + IEnumerator actualEnumerator = actualCollection.GetEnumerator(); + bool expectedHasMore = expectedEnumerator.MoveNext(); + bool actualHasMore = actualEnumerator.MoveNext(); + int expectedCount = 0; + int actualCount = 0; + string name = _properties.Pop(); //pop the propertyname from the stack to be replaced by the same name with an index. + + while (expectedHasMore && actualHasMore) + { + object expectedValue = expectedEnumerator.Current; + object actualValue = actualEnumerator.Current; + + _properties.Push(name + string.Format("[{0}]", expectedCount)); //replace the earlier popped property name + + expectedCount++; + actualCount++; + + if (!CheckReferenceType(expectedValue, actualValue)) + { + return false; + } + + _properties.Pop(); //pop the old indexed property name to make place for a new one + + expectedHasMore = expectedEnumerator.MoveNext(); + actualHasMore = actualEnumerator.MoveNext(); + } + _properties.Push(name); //push the original property name back on the stack. + + //examine the expectedMoveNextResult and the actualMoveNextResult to see if one collection was bigger than the other. + if (expectedHasMore & !actualHasMore) //actual has less items than expected. + { + //find out how much items there are in the expected collection. + do expectedCount++; while (expectedEnumerator.MoveNext()); + } + if (!expectedHasMore & actualHasMore) //actual has more items than expected. + { + //find out how much items there are in the actual collection. + do actualCount++; while (actualEnumerator.MoveNext()); + } + if (expectedCount != actualCount) + { + _message = string.Format("expected number of items in collection {0} is '{1}', actual is '{2}'", BuildPropertyName(), expectedCount, actualCount); + return false; + } + } + return true; + } + + /// + /// Builds a propertyname from the Stack _properties like 'Order.Product.Price' + /// to be used in the error message. + /// + /// A nested property name. + private string BuildPropertyName() + { + StringBuilder result = new StringBuilder(); + string[] names = _properties.ToArray(); + foreach(string name in names) + { + if (result.Length > 0) + { + result.Insert(0, '.'); + } + result.Insert(0, name); + } + return result.ToString(); + } + } +} diff --git a/Rhino.Mocks/Constraints/Constraints.cs b/Rhino.Mocks/Constraints/Constraints.cs index 2476cfd7..5cbda749 100644 --- a/Rhino.Mocks/Constraints/Constraints.cs +++ b/Rhino.Mocks/Constraints/Constraints.cs @@ -1,1272 +1,1272 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections; -#if DOTNET35 -using System.Linq.Expressions; -#endif -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Constraints -{ - #region PublicFieldIs - - /// - /// Constrain that the public field has a specified value - /// - public class PublicFieldIs : PublicFieldConstraint - { - /// - /// Creates a new instance. - /// - /// Name of the public field. - /// Expected value. - public PublicFieldIs(string publicFieldName, object expectedValue) - : base(publicFieldName, Is.Equal(expectedValue)) - { - } - - /// - /// 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. - public PublicFieldIs(Type declaringType, string publicFieldName, object expectedValue) - : base(declaringType, publicFieldName, Is.Equal(expectedValue)) - { - } - } - - #endregion - - #region PublicFieldConstraint - - /// - /// Constrain that the public field matches another constraint. - /// - public class PublicFieldConstraint : AbstractConstraint - { - private readonly Type declaringType; - private readonly string publicFieldName; - private readonly AbstractConstraint constraint; - - /// - /// Creates a new instance. - /// - /// Name of the public field. - /// Constraint to place on the public field value. - public PublicFieldConstraint(string publicFieldName, AbstractConstraint constraint) - : this(null, publicFieldName, constraint) {} - - /// - /// 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. - public PublicFieldConstraint(Type declaringType, string publicFieldName, AbstractConstraint constraint) - { - this.declaringType = declaringType; - this.publicFieldName = publicFieldName; - this.constraint = constraint; - } - - /// - /// Determines if the object passes the constraint. - /// - public override bool Eval(object obj) - { - if (obj == null) - return false; - FieldInfo field; - - if (declaringType == null) - { - field = obj.GetType().GetField(publicFieldName); - } - else - { - field = declaringType.GetField(publicFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); - } - if (field == null) - return false; - object fieldValue = field.GetValue(obj); - return constraint.Eval(fieldValue); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "public field '" + publicFieldName + "' " + constraint.Message; } - } - } - - #endregion - - #region PropertyIs - - /// - /// Constrain that the property has a specified value - /// - public class PropertyIs : PropertyConstraint - { - /// - /// Creates a new instance. - /// - /// Name of the property. - /// Expected value. - public PropertyIs(string propertyName, object expectedValue) - : base(propertyName, Is.Equal(expectedValue)) - { - } - - /// - /// 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. - public PropertyIs(Type declaringType, string propertyName, object expectedValue) - : base(declaringType, propertyName, Is.Equal(expectedValue)) - { - } - } - - #endregion - - #region PropertyConstraint - - /// - /// Constrain that the property matches another constraint. - /// - public class PropertyConstraint : AbstractConstraint - { - private readonly Type declaringType; - private readonly string propertyName; - private readonly AbstractConstraint constraint; - - /// - /// Creates a new instance. - /// - /// Name of the property. - /// Constraint to place on the property value. - public PropertyConstraint(string propertyName, AbstractConstraint constraint) - : this(null, propertyName, constraint) - { - } - - /// - /// 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. - public PropertyConstraint(Type declaringType, string propertyName, AbstractConstraint constraint) - { - this.declaringType = declaringType; - this.propertyName = propertyName; - this.constraint = constraint; - } - - /// - /// Determines if the object passes the constraint. - /// - public override bool Eval(object obj) - { - if (obj == null) - return false; - PropertyInfo prop; - - if (declaringType == null) - { - prop = obj.GetType().GetProperty(propertyName); - } - else - { - prop = declaringType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); - } - if (prop == null || !prop.CanRead) - return false; - object propertyValue = prop.GetValue(obj, null); - return constraint.Eval(propertyValue); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "property '" + propertyName + "' " + constraint.Message; } - } - } - - #endregion - - #region TypeOf - - /// - /// Constrain that the parameter must be of the specified type - /// - public class TypeOf : AbstractConstraint - { - private Type type; - - /// - /// Creates a new instance. - /// - /// Type. - public TypeOf(Type type) - { - this.type = type; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - return type.IsInstanceOfType(obj); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "type of {" + type.FullName + "}"; } - } - } - - #endregion - - #region Same - /// - /// Constraint that determines whether an object is the same object as another. - /// - public class Same : AbstractConstraint - { - private readonly object same; - - /// - /// Creates a new instance. - /// - /// Obj. - public Same(object obj) - { - this.same = obj; - } - - /// - /// Determines if the object passes the constraints. - /// - public override bool Eval(object obj) - { - return Object.ReferenceEquals(same, obj); - } - - /// - /// Gets the message for this constraint. - /// - public override string Message - { - get - { - string sameAsString = (same == null) ? "null" : same.ToString(); - return "same as " + sameAsString; - } - } - } - #endregion - - #region Predicate Constraint - - /// - /// Evaluate a parameter using constraints - /// - public class PredicateConstraint : AbstractConstraint - { - Predicate predicate; - - /// - /// Create new instance - /// - /// - public PredicateConstraint(Predicate predicate) - { - Validate.IsNotNull(predicate, "predicate"); - this.predicate = predicate; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if(obj!=null && - typeof(T).IsAssignableFrom(obj.GetType()) == false) - { - throw new InvalidOperationException( - string.Format("Predicate accept {0} but parameter is {1} which is not compatible", - typeof (T).FullName, - obj.GetType().FullName)); - } - return predicate((T) obj); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - return string.Format("Predicate ({0})", MethodCallUtil.StringPresentation(null, FormatEmptyArgumnet,predicate.Method, new object[0])); - } - } - - private string FormatEmptyArgumnet(Array args, int i) - { - return "obj"; - } - } - -#if DOTNET35 - - /// - /// A constraint based on lambda expression, we are using Expression{T} - /// because we want to be able to get good error reporting on that. - /// - public class LambdaConstraint : AbstractConstraint - { - private readonly LambdaExpression expr; - - /// - /// Initializes a new instance of the class. - /// - /// The expr. - public LambdaConstraint(LambdaExpression expr) - { - this.expr = expr; - } - - /// - /// Determines if the object pass the constraints - /// - /// - /// - public override bool Eval(object obj) - { - if (!IsArgumentTypeIsAssignableFrom(expr, obj)) - return false; - - return (bool)expr.Compile().DynamicInvoke(obj); - } - - private bool IsArgumentTypeIsAssignableFrom(LambdaExpression predicate, object obj) - { - if(obj != null) - { - if (!predicate.Parameters[0].Type.IsAssignableFrom(obj.GetType())) - { - return false; - } - } - return true; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return expr.ToString(); } - } - } - - #endif - - #endregion - - #region List constraints - - #region Equal - - /// - /// Constrain that the list contains the same items as the parameter list - /// - public class CollectionEqual : AbstractConstraint - { - private IEnumerable collection; - - /// - /// Creates a new instance. - /// - /// In list. - public CollectionEqual(IEnumerable collection) - { - this.collection = collection; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - IEnumerable arg = obj as IEnumerable; - if (arg != null) - { - if (arg is ICollection && collection is ICollection) - if (((ICollection)arg).Count != ((ICollection)collection).Count) - return false; - IEnumerator argEnumerator = arg.GetEnumerator(), - collectionEnumerator = collection.GetEnumerator(); - - bool argListHasMore = argEnumerator.MoveNext(); - bool constraintListHasMore = collectionEnumerator.MoveNext(); - while (argListHasMore && constraintListHasMore) - { - if (argEnumerator.Current.Equals(collectionEnumerator.Current) == false) - return false; - argListHasMore = argEnumerator.MoveNext(); - constraintListHasMore = collectionEnumerator.MoveNext(); - } - if (argListHasMore || constraintListHasMore) - return false; - return true; - } - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - StringBuilder sb = new StringBuilder(); - sb.Append("equal to collection ["); - int i = 0; - foreach (object o in collection) - { - if (i != 0) - sb.Append(", "); - sb.Append(o); - i++; - } - sb.Append("]"); - return sb.ToString(); - } - } - } - - #endregion - - #region OneOf - - /// - /// Constrain that the parameter is one of the items in the list - /// - public class OneOf : AbstractConstraint - { - private IEnumerable collection; - - /// - /// Creates a new instance. - /// - /// In list. - public OneOf(IEnumerable collection) - { - this.collection = collection; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - foreach (object o in collection) - { - if (obj.Equals(o)) - return true; - } - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - StringBuilder sb = new StringBuilder(); - sb.Append("one of ["); - int i = 0; - foreach (object o in collection) - { - if (i != 0) - sb.Append(", "); - sb.Append(o); - i++; - } - sb.Append("]"); - return sb.ToString(); - } - } - } - - #endregion - - #region IsIn - - /// - /// Constrain that the object is inside the parameter list - /// - public class IsIn : AbstractConstraint - { - private object inList; - - /// - /// Creates a new instance. - /// - /// In list. - public IsIn(object inList) - { - this.inList = inList; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj is IEnumerable) - { - foreach (object o in (IEnumerable)obj) - { - if (inList.Equals(o)) - return true; - } - } - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "list contains [" + inList + "]"; } - } - } - - #endregion - - #region Count - - /// - /// Applies another AbstractConstraint to the collection count. - /// - public class CollectionCount : AbstractConstraint - { - private AbstractConstraint _constraint; - - /// - /// Creates a new instance. - /// - /// The constraint that should be applied to the collection count. - public CollectionCount(AbstractConstraint constraint) - { - _constraint = constraint; - } - - /// - /// Determines if the parameter conforms to this constraint. - /// - public override bool Eval(object obj) - { - ICollection arg = obj as ICollection; - - if (arg != null) - { - return _constraint.Eval(arg.Count); - } - - return false; - } - - /// - /// Gets the message for this constraint. - /// - public override string Message - { - get { return "collection count " + _constraint.Message; } - } - } - - #endregion - - #region Element - - /// - /// Applies another AbstractConstraint to a specific list element. - /// - public class ListElement : AbstractConstraint - { - private int _index; - private AbstractConstraint _constraint; - - /// - /// Creates a new instance. - /// - /// The zero-based index of the list element. - /// The constraint that should be applied to the list element. - public ListElement(int index, AbstractConstraint constraint) - { - _index = index; - _constraint = constraint; - } - - /// - /// Determines if the parameter conforms to this constraint. - /// - public override bool Eval(object obj) - { - IList arg = obj as IList; - - if (arg != null) - { - if (_index >= 0 && _index < arg.Count) - return _constraint.Eval(arg[_index]); - } - - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - return "element at index " + _index + " " + _constraint.Message; - } - } - } - - /// - /// Applies another AbstractConstraint to a specific generic keyed list element. - /// - public class KeyedListElement : AbstractConstraint - { - private T _key; - private AbstractConstraint _constraint; - - /// - /// Creates a new instance. - /// - /// The key of the list element. - /// The constraint that should be applied to the list element. - public KeyedListElement(T key, AbstractConstraint constraint) - { - _key = key; - _constraint = constraint; - } - - /// - /// Determines if the parameter conforms to this constraint. - /// - public override bool Eval(object obj) - { - MethodInfo methodInfo = obj.GetType().GetMethod("get_Item", - BindingFlags.Public | BindingFlags.GetProperty | - BindingFlags.DeclaredOnly | BindingFlags.Instance, - null, new Type[] { typeof(T) }, null); - - if (methodInfo != null) - { - object value; - - try - { - value = methodInfo.Invoke(obj, new object[] { _key }); - } - catch (TargetInvocationException) - { - return false; - } - - return _constraint.Eval(value); - } - - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - return "element at key " + _key.ToString() + " " + _constraint.Message; - } - } - } - - #endregion - - #region ContainsAll Constraint - - /// - /// Constrains that all elements are in the parameter list - /// - public class ContainsAll : AbstractConstraint - { - private IEnumerable these; - private ArrayList missing = new ArrayList(); - - /// - /// Initializes a new instance of the class. - /// - /// The these. - public ContainsAll(IEnumerable these) - { - this.these = these; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - StringBuilder sb = new StringBuilder(); - sb.Append("list missing ["); - int i = 0; - foreach (object o in missing) - { - if (i != 0) - sb.Append(", "); - sb.Append(o); - i++; - } - sb.Append("]"); - return sb.ToString(); - } - } - - /// - /// Determines if the object pass the constraints - /// - /// - /// - public override bool Eval(object obj) - { - if (obj is IEnumerable) - { - foreach (object outer in these) - { - bool foundThis = false; - foreach (object inner in (IEnumerable) obj) - { - if (inner.Equals(outer)) - { - foundThis = true; - break; - } - } - if (!foundThis && !missing.Contains(outer)) - { - missing.Add(outer); - } - } - - return missing.Count == 0; - } - return false; - } - } - #endregion - - #endregion - - #region Logic Operator - - #region Or - - /// - /// Combines two constraints, constraint pass if either is fine. - /// - public class Or : AbstractConstraint - { - private AbstractConstraint c1, c2; - - /// - /// Creates a new instance. - /// - /// C1. - /// C2. - public Or(AbstractConstraint c1, AbstractConstraint c2) - { - this.c1 = c1; - this.c2 = c2; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - return c1.Eval(obj) || c2.Eval(obj); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return c1.Message + " or " + c2.Message; } - } - } - - #endregion - - #region Not - - /// - /// Negate a constraint - /// - public class Not : AbstractConstraint - { - private AbstractConstraint c1; - - /// - /// Creates a new instance. - /// - /// C1. - public Not(AbstractConstraint c1) - { - this.c1 = c1; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - return !c1.Eval(obj); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "not " + c1.Message; } - } - } - - #endregion - - #region And - - /// - /// Combines two constraints - /// - /// - public class And : AbstractConstraint - { - private AbstractConstraint c1, c2; - - /// - /// Creates a new instance. - /// - /// C1. - /// C2. - public And(AbstractConstraint c1, AbstractConstraint c2) - { - this.c1 = c1; - this.c2 = c2; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - return c1.Eval(obj) && c2.Eval(obj); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return c1.Message + " and " + c2.Message; } - } - } - - #endregion - - #endregion - - #region String Constraints - - #region Like - - /// - /// Constrain the argument to validate according to regex pattern - /// - public class Like : AbstractConstraint - { - private string pattern; - private Regex regex; - - /// - /// Creates a new instance. - /// - /// Pattern. - public Like(string pattern) - { - regex = new Regex(pattern); - this.pattern = pattern; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj !=null) - { - return regex.IsMatch(obj.ToString()); - } - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "like \"" + pattern + "\""; } - } - } - - #endregion - - #region Contains - - /// - /// Constraint that evaluate whatever an argument contains the specified string. - /// - public class Contains : AbstractConstraint - { - private string innerString; - - /// - /// Creates a new instance. - /// - /// Inner string. - public Contains(string innerString) - { - this.innerString = innerString; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj != null) - return obj.ToString().IndexOf(innerString) > -1; - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "contains \"" + innerString + "\""; } - } - } - - #endregion - - #region Ends With - - /// - /// Constraint that evaluate whatever an argument ends with the specified string - /// - public class EndsWith : AbstractConstraint - { - private string end; - - /// - /// Creates a new instance. - /// - /// End. - public EndsWith(string end) - { - this.end = end; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj != null) - return obj.ToString().EndsWith(end); - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "ends with \"" + end + "\""; } - } - } - - #endregion - - #region Starts With - - /// - /// Constraint that evaluate whatever an argument start with the specified string - /// - public class StartsWith : AbstractConstraint - { - private string start; - - /// - /// Creates a new instance. - /// - /// Start. - public StartsWith(string start) - { - this.start = start; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj != null) - return obj.ToString().StartsWith(start); - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "starts with \"" + start + "\""; } - } - } - - #endregion - - #endregion - - #region Object Constraints - - #region Equals - - /// - /// Constraint that evaluate whatever an object equals another - /// - public class Equal : AbstractConstraint - { - private object equal; - - /// - /// Creates a new instance. - /// - /// Obj. - public Equal(object obj) - { - this.equal = obj; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj == null) - return equal == null; - return Validate.AreEqual(equal, obj); - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - string equalAsString = equal == null ? "null" : equal.ToString(); - return "equal to " + equalAsString; - } - } - } - - #endregion - - #region Anything - - /// - /// Constraint that always returns true - /// - public class Anything : AbstractConstraint - { - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - return true; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get { return "anything"; } - } - } - - #endregion - - #endregion - - #region Math Constraints - - /// - /// Constraint that evaluate whatever a comparable is greater than another - /// - public class ComparingConstraint : AbstractConstraint - { - private IComparable compareTo; - private readonly bool largerThan; - private readonly bool andEqual; - - /// - /// Creates a new instance. - /// - public ComparingConstraint(IComparable compareTo, bool largerThan, bool andEqual) - { - this.compareTo = compareTo; - this.largerThan = largerThan; - this.andEqual = andEqual; - } - - /// - /// Determines if the object pass the constraints - /// - public override bool Eval(object obj) - { - if (obj is IComparable) - { - int result = ((IComparable)obj).CompareTo(compareTo); - if (result == 0 && andEqual) - return true; - if (largerThan) - return result > 0; - else - return result < 0; - } - return false; - } - - /// - /// Gets the message for this constraint - /// - /// - public override string Message - { - get - { - string result; - if (largerThan) - result = "greater than "; - else - result = "less than "; - if (andEqual) - result += "or equal to "; - return result + compareTo; - } - } - } - - #endregion -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections; +#if DOTNET35 +using System.Linq.Expressions; +#endif +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Constraints +{ + #region PublicFieldIs + + /// + /// Constrain that the public field has a specified value + /// + public class PublicFieldIs : PublicFieldConstraint + { + /// + /// Creates a new instance. + /// + /// Name of the public field. + /// Expected value. + public PublicFieldIs(string publicFieldName, object expectedValue) + : base(publicFieldName, Is.Equal(expectedValue)) + { + } + + /// + /// 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. + public PublicFieldIs(Type declaringType, string publicFieldName, object expectedValue) + : base(declaringType, publicFieldName, Is.Equal(expectedValue)) + { + } + } + + #endregion + + #region PublicFieldConstraint + + /// + /// Constrain that the public field matches another constraint. + /// + public class PublicFieldConstraint : AbstractConstraint + { + private readonly Type declaringType; + private readonly string publicFieldName; + private readonly AbstractConstraint constraint; + + /// + /// Creates a new instance. + /// + /// Name of the public field. + /// Constraint to place on the public field value. + public PublicFieldConstraint(string publicFieldName, AbstractConstraint constraint) + : this(null, publicFieldName, constraint) {} + + /// + /// 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. + public PublicFieldConstraint(Type declaringType, string publicFieldName, AbstractConstraint constraint) + { + this.declaringType = declaringType; + this.publicFieldName = publicFieldName; + this.constraint = constraint; + } + + /// + /// Determines if the object passes the constraint. + /// + public override bool Eval(object obj) + { + if (obj == null) + return false; + FieldInfo field; + + if (declaringType == null) + { + field = obj.GetType().GetField(publicFieldName); + } + else + { + field = declaringType.GetField(publicFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); + } + if (field == null) + return false; + object fieldValue = field.GetValue(obj); + return constraint.Eval(fieldValue); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "public field '" + publicFieldName + "' " + constraint.Message; } + } + } + + #endregion + + #region PropertyIs + + /// + /// Constrain that the property has a specified value + /// + public class PropertyIs : PropertyConstraint + { + /// + /// Creates a new instance. + /// + /// Name of the property. + /// Expected value. + public PropertyIs(string propertyName, object expectedValue) + : base(propertyName, Is.Equal(expectedValue)) + { + } + + /// + /// 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. + public PropertyIs(Type declaringType, string propertyName, object expectedValue) + : base(declaringType, propertyName, Is.Equal(expectedValue)) + { + } + } + + #endregion + + #region PropertyConstraint + + /// + /// Constrain that the property matches another constraint. + /// + public class PropertyConstraint : AbstractConstraint + { + private readonly Type declaringType; + private readonly string propertyName; + private readonly AbstractConstraint constraint; + + /// + /// Creates a new instance. + /// + /// Name of the property. + /// Constraint to place on the property value. + public PropertyConstraint(string propertyName, AbstractConstraint constraint) + : this(null, propertyName, constraint) + { + } + + /// + /// 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. + public PropertyConstraint(Type declaringType, string propertyName, AbstractConstraint constraint) + { + this.declaringType = declaringType; + this.propertyName = propertyName; + this.constraint = constraint; + } + + /// + /// Determines if the object passes the constraint. + /// + public override bool Eval(object obj) + { + if (obj == null) + return false; + PropertyInfo prop; + + if (declaringType == null) + { + prop = obj.GetType().GetProperty(propertyName); + } + else + { + prop = declaringType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); + } + if (prop == null || !prop.CanRead) + return false; + object propertyValue = prop.GetValue(obj, null); + return constraint.Eval(propertyValue); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "property '" + propertyName + "' " + constraint.Message; } + } + } + + #endregion + + #region TypeOf + + /// + /// Constrain that the parameter must be of the specified type + /// + public class TypeOf : AbstractConstraint + { + private Type type; + + /// + /// Creates a new instance. + /// + /// Type. + public TypeOf(Type type) + { + this.type = type; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + return type.IsInstanceOfType(obj); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "type of {" + type.FullName + "}"; } + } + } + + #endregion + + #region Same + /// + /// Constraint that determines whether an object is the same object as another. + /// + public class Same : AbstractConstraint + { + private readonly object same; + + /// + /// Creates a new instance. + /// + /// Obj. + public Same(object obj) + { + this.same = obj; + } + + /// + /// Determines if the object passes the constraints. + /// + public override bool Eval(object obj) + { + return Object.ReferenceEquals(same, obj); + } + + /// + /// Gets the message for this constraint. + /// + public override string Message + { + get + { + string sameAsString = (same == null) ? "null" : same.ToString(); + return "same as " + sameAsString; + } + } + } + #endregion + + #region Predicate Constraint + + /// + /// Evaluate a parameter using constraints + /// + public class PredicateConstraint : AbstractConstraint + { + Predicate predicate; + + /// + /// Create new instance + /// + /// + public PredicateConstraint(Predicate predicate) + { + Validate.IsNotNull(predicate, "predicate"); + this.predicate = predicate; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if(obj!=null && + typeof(T).IsAssignableFrom(obj.GetType()) == false) + { + throw new InvalidOperationException( + string.Format("Predicate accept {0} but parameter is {1} which is not compatible", + typeof (T).FullName, + obj.GetType().FullName)); + } + return predicate((T) obj); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + return string.Format("Predicate ({0})", MethodCallUtil.StringPresentation(null, FormatEmptyArgumnet,predicate.Method, new object[0])); + } + } + + private string FormatEmptyArgumnet(Array args, int i) + { + return "obj"; + } + } + +#if DOTNET35 + + /// + /// A constraint based on lambda expression, we are using Expression{T} + /// because we want to be able to get good error reporting on that. + /// + public class LambdaConstraint : AbstractConstraint + { + private readonly LambdaExpression expr; + + /// + /// Initializes a new instance of the class. + /// + /// The expr. + public LambdaConstraint(LambdaExpression expr) + { + this.expr = expr; + } + + /// + /// Determines if the object pass the constraints + /// + /// + /// + public override bool Eval(object obj) + { + if (!IsArgumentTypeIsAssignableFrom(expr, obj)) + return false; + + return (bool)expr.Compile().DynamicInvoke(obj); + } + + private bool IsArgumentTypeIsAssignableFrom(LambdaExpression predicate, object obj) + { + if(obj != null) + { + if (!predicate.Parameters[0].Type.IsAssignableFrom(obj.GetType())) + { + return false; + } + } + return true; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return expr.ToString(); } + } + } + + #endif + + #endregion + + #region List constraints + + #region Equal + + /// + /// Constrain that the list contains the same items as the parameter list + /// + public class CollectionEqual : AbstractConstraint + { + private IEnumerable collection; + + /// + /// Creates a new instance. + /// + /// In list. + public CollectionEqual(IEnumerable collection) + { + this.collection = collection; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + IEnumerable arg = obj as IEnumerable; + if (arg != null) + { + if (arg is ICollection && collection is ICollection) + if (((ICollection)arg).Count != ((ICollection)collection).Count) + return false; + IEnumerator argEnumerator = arg.GetEnumerator(), + collectionEnumerator = collection.GetEnumerator(); + + bool argListHasMore = argEnumerator.MoveNext(); + bool constraintListHasMore = collectionEnumerator.MoveNext(); + while (argListHasMore && constraintListHasMore) + { + if (argEnumerator.Current.Equals(collectionEnumerator.Current) == false) + return false; + argListHasMore = argEnumerator.MoveNext(); + constraintListHasMore = collectionEnumerator.MoveNext(); + } + if (argListHasMore || constraintListHasMore) + return false; + return true; + } + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + StringBuilder sb = new StringBuilder(); + sb.Append("equal to collection ["); + int i = 0; + foreach (object o in collection) + { + if (i != 0) + sb.Append(", "); + sb.Append(o); + i++; + } + sb.Append("]"); + return sb.ToString(); + } + } + } + + #endregion + + #region OneOf + + /// + /// Constrain that the parameter is one of the items in the list + /// + public class OneOf : AbstractConstraint + { + private IEnumerable collection; + + /// + /// Creates a new instance. + /// + /// In list. + public OneOf(IEnumerable collection) + { + this.collection = collection; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + foreach (object o in collection) + { + if (obj.Equals(o)) + return true; + } + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + StringBuilder sb = new StringBuilder(); + sb.Append("one of ["); + int i = 0; + foreach (object o in collection) + { + if (i != 0) + sb.Append(", "); + sb.Append(o); + i++; + } + sb.Append("]"); + return sb.ToString(); + } + } + } + + #endregion + + #region IsIn + + /// + /// Constrain that the object is inside the parameter list + /// + public class IsIn : AbstractConstraint + { + private object inList; + + /// + /// Creates a new instance. + /// + /// In list. + public IsIn(object inList) + { + this.inList = inList; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj is IEnumerable) + { + foreach (object o in (IEnumerable)obj) + { + if (inList.Equals(o)) + return true; + } + } + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "list contains [" + inList + "]"; } + } + } + + #endregion + + #region Count + + /// + /// Applies another AbstractConstraint to the collection count. + /// + public class CollectionCount : AbstractConstraint + { + private AbstractConstraint _constraint; + + /// + /// Creates a new instance. + /// + /// The constraint that should be applied to the collection count. + public CollectionCount(AbstractConstraint constraint) + { + _constraint = constraint; + } + + /// + /// Determines if the parameter conforms to this constraint. + /// + public override bool Eval(object obj) + { + ICollection arg = obj as ICollection; + + if (arg != null) + { + return _constraint.Eval(arg.Count); + } + + return false; + } + + /// + /// Gets the message for this constraint. + /// + public override string Message + { + get { return "collection count " + _constraint.Message; } + } + } + + #endregion + + #region Element + + /// + /// Applies another AbstractConstraint to a specific list element. + /// + public class ListElement : AbstractConstraint + { + private int _index; + private AbstractConstraint _constraint; + + /// + /// Creates a new instance. + /// + /// The zero-based index of the list element. + /// The constraint that should be applied to the list element. + public ListElement(int index, AbstractConstraint constraint) + { + _index = index; + _constraint = constraint; + } + + /// + /// Determines if the parameter conforms to this constraint. + /// + public override bool Eval(object obj) + { + IList arg = obj as IList; + + if (arg != null) + { + if (_index >= 0 && _index < arg.Count) + return _constraint.Eval(arg[_index]); + } + + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + return "element at index " + _index + " " + _constraint.Message; + } + } + } + + /// + /// Applies another AbstractConstraint to a specific generic keyed list element. + /// + public class KeyedListElement : AbstractConstraint + { + private T _key; + private AbstractConstraint _constraint; + + /// + /// Creates a new instance. + /// + /// The key of the list element. + /// The constraint that should be applied to the list element. + public KeyedListElement(T key, AbstractConstraint constraint) + { + _key = key; + _constraint = constraint; + } + + /// + /// Determines if the parameter conforms to this constraint. + /// + public override bool Eval(object obj) + { + MethodInfo methodInfo = obj.GetType().GetMethod("get_Item", + BindingFlags.Public | BindingFlags.GetProperty | + BindingFlags.DeclaredOnly | BindingFlags.Instance, + null, new Type[] { typeof(T) }, null); + + if (methodInfo != null) + { + object value; + + try + { + value = methodInfo.Invoke(obj, new object[] { _key }); + } + catch (TargetInvocationException) + { + return false; + } + + return _constraint.Eval(value); + } + + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + return "element at key " + _key.ToString() + " " + _constraint.Message; + } + } + } + + #endregion + + #region ContainsAll Constraint + + /// + /// Constrains that all elements are in the parameter list + /// + public class ContainsAll : AbstractConstraint + { + private IEnumerable these; + private ArrayList missing = new ArrayList(); + + /// + /// Initializes a new instance of the class. + /// + /// The these. + public ContainsAll(IEnumerable these) + { + this.these = these; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + StringBuilder sb = new StringBuilder(); + sb.Append("list missing ["); + int i = 0; + foreach (object o in missing) + { + if (i != 0) + sb.Append(", "); + sb.Append(o); + i++; + } + sb.Append("]"); + return sb.ToString(); + } + } + + /// + /// Determines if the object pass the constraints + /// + /// + /// + public override bool Eval(object obj) + { + if (obj is IEnumerable) + { + foreach (object outer in these) + { + bool foundThis = false; + foreach (object inner in (IEnumerable) obj) + { + if (inner.Equals(outer)) + { + foundThis = true; + break; + } + } + if (!foundThis && !missing.Contains(outer)) + { + missing.Add(outer); + } + } + + return missing.Count == 0; + } + return false; + } + } + #endregion + + #endregion + + #region Logic Operator + + #region Or + + /// + /// Combines two constraints, constraint pass if either is fine. + /// + public class Or : AbstractConstraint + { + private AbstractConstraint c1, c2; + + /// + /// Creates a new instance. + /// + /// C1. + /// C2. + public Or(AbstractConstraint c1, AbstractConstraint c2) + { + this.c1 = c1; + this.c2 = c2; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + return c1.Eval(obj) || c2.Eval(obj); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return c1.Message + " or " + c2.Message; } + } + } + + #endregion + + #region Not + + /// + /// Negate a constraint + /// + public class Not : AbstractConstraint + { + private AbstractConstraint c1; + + /// + /// Creates a new instance. + /// + /// C1. + public Not(AbstractConstraint c1) + { + this.c1 = c1; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + return !c1.Eval(obj); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "not " + c1.Message; } + } + } + + #endregion + + #region And + + /// + /// Combines two constraints + /// + /// + public class And : AbstractConstraint + { + private AbstractConstraint c1, c2; + + /// + /// Creates a new instance. + /// + /// C1. + /// C2. + public And(AbstractConstraint c1, AbstractConstraint c2) + { + this.c1 = c1; + this.c2 = c2; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + return c1.Eval(obj) && c2.Eval(obj); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return c1.Message + " and " + c2.Message; } + } + } + + #endregion + + #endregion + + #region String Constraints + + #region Like + + /// + /// Constrain the argument to validate according to regex pattern + /// + public class Like : AbstractConstraint + { + private string pattern; + private Regex regex; + + /// + /// Creates a new instance. + /// + /// Pattern. + public Like(string pattern) + { + regex = new Regex(pattern); + this.pattern = pattern; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj !=null) + { + return regex.IsMatch(obj.ToString()); + } + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "like \"" + pattern + "\""; } + } + } + + #endregion + + #region Contains + + /// + /// Constraint that evaluate whatever an argument contains the specified string. + /// + public class Contains : AbstractConstraint + { + private string innerString; + + /// + /// Creates a new instance. + /// + /// Inner string. + public Contains(string innerString) + { + this.innerString = innerString; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj != null) + return obj.ToString().IndexOf(innerString) > -1; + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "contains \"" + innerString + "\""; } + } + } + + #endregion + + #region Ends With + + /// + /// Constraint that evaluate whatever an argument ends with the specified string + /// + public class EndsWith : AbstractConstraint + { + private string end; + + /// + /// Creates a new instance. + /// + /// End. + public EndsWith(string end) + { + this.end = end; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj != null) + return obj.ToString().EndsWith(end); + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "ends with \"" + end + "\""; } + } + } + + #endregion + + #region Starts With + + /// + /// Constraint that evaluate whatever an argument start with the specified string + /// + public class StartsWith : AbstractConstraint + { + private string start; + + /// + /// Creates a new instance. + /// + /// Start. + public StartsWith(string start) + { + this.start = start; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj != null) + return obj.ToString().StartsWith(start); + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "starts with \"" + start + "\""; } + } + } + + #endregion + + #endregion + + #region Object Constraints + + #region Equals + + /// + /// Constraint that evaluate whatever an object equals another + /// + public class Equal : AbstractConstraint + { + private object equal; + + /// + /// Creates a new instance. + /// + /// Obj. + public Equal(object obj) + { + this.equal = obj; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj == null) + return equal == null; + return Validate.AreEqual(equal, obj); + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + string equalAsString = equal == null ? "null" : equal.ToString(); + return "equal to " + equalAsString; + } + } + } + + #endregion + + #region Anything + + /// + /// Constraint that always returns true + /// + public class Anything : AbstractConstraint + { + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + return true; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get { return "anything"; } + } + } + + #endregion + + #endregion + + #region Math Constraints + + /// + /// Constraint that evaluate whatever a comparable is greater than another + /// + public class ComparingConstraint : AbstractConstraint + { + private IComparable compareTo; + private readonly bool largerThan; + private readonly bool andEqual; + + /// + /// Creates a new instance. + /// + public ComparingConstraint(IComparable compareTo, bool largerThan, bool andEqual) + { + this.compareTo = compareTo; + this.largerThan = largerThan; + this.andEqual = andEqual; + } + + /// + /// Determines if the object pass the constraints + /// + public override bool Eval(object obj) + { + if (obj is IComparable) + { + int result = ((IComparable)obj).CompareTo(compareTo); + if (result == 0 && andEqual) + return true; + if (largerThan) + return result > 0; + else + return result < 0; + } + return false; + } + + /// + /// Gets the message for this constraint + /// + /// + public override string Message + { + get + { + string result; + if (largerThan) + result = "greater than "; + else + result = "less than "; + if (andEqual) + result += "or equal to "; + return result + compareTo; + } + } + } + + #endregion +} diff --git a/Rhino.Mocks/Constraints/Is.cs b/Rhino.Mocks/Constraints/Is.cs index 65da07df..3818bce0 100644 --- a/Rhino.Mocks/Constraints/Is.cs +++ b/Rhino.Mocks/Constraints/Is.cs @@ -1,233 +1,233 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Constraints; - -namespace Rhino.Mocks.Constraints -{ - /* - * Class: Is - * - * Common constraints. - */ - /// - /// Central location for constraints - /// - public static class Is - { - /* - * method: GreaterThan - * - * Determines whatever the parameter is greater than objToCompare. - * The parameter must implement IComparable - */ - /// - /// Evaluate a greater than constraint for . - /// - /// The object the parameter should be greater than - public static AbstractConstraint GreaterThan(IComparable objToCompare) - { - return new ComparingConstraint(objToCompare, true, false); - } - - /* - * method: LessThan - * - * Determines whatever the parameter is less than objToCompare. - * The parameter must implement IComparable - */ - /// - /// Evaluate a less than constraint for . - /// - /// The object the parameter should be less than - public static AbstractConstraint LessThan(IComparable objToCompare) - { - return new ComparingConstraint(objToCompare, false, false); - } - - /* - * method: LessThanOrEqual - * - * Determines whatever the parameter is less than or equal to objToCompare. - * The parameter must implement IComparable - */ - /// - /// Evaluate a less than or equal constraint for . - /// - /// The object the parameter should be less than or equal to - public static AbstractConstraint LessThanOrEqual(IComparable objToCompare) - { - return new ComparingConstraint(objToCompare, false, true); - } - - /* - * method: GreaterThanOrEqual - * - * Determines whatever the parameter is greater than or equal to objToCompare. - * The parameter must implement IComparable - */ - /// - /// Evaluate a greater than or equal constraint for . - /// - /// The object the parameter should be greater than or equal to - public static AbstractConstraint GreaterThanOrEqual(IComparable objToCompare) - { - return new ComparingConstraint(objToCompare, true, true); - } - - /* - * method: Equal - * - * Determines whatever the parameter equal to obj. - */ - /// - /// Evaluate an equal constraint for . - /// - /// The object the parameter should equal to - public static AbstractConstraint Equal(object obj) - { - return new Equal(obj); - } - - - /* - * method: NotEqual - * - * Determines whatever the parameter does not equal to obj. - */ - /// - /// Evaluate a not equal constraint for . - /// - /// The object the parameter should not equal to - public static AbstractConstraint NotEqual(object obj) - { - return !new Equal(obj); - } - - /// - /// Evaluate a same as constraint. - /// - /// The object the parameter should the same as. - public static AbstractConstraint Same(object obj) - { - return new Same(obj); - } - - /// - /// Evaluate a not same as constraint. - /// - /// The object the parameter should not be the same as. - public static AbstractConstraint NotSame(object obj) - { - return !new Same(obj); - } - - /* - * method: Anything - * - * This constraint always succeeds - */ - /// - /// A constraints that accept anything - /// - /// - public static AbstractConstraint Anything() - { - return new Anything(); - } - - /* - * Method: Null - * - * Determines whatever the parameter is null - * - */ - /// - /// A constraint that accept only nulls - /// - /// - public static AbstractConstraint Null() - { - return new Equal(null); - } - - /* - * Method: NotNull - * - * Determines whatever the parameter is not null - * - */ - /// - /// A constraint that accept only non null values - /// - /// - public static AbstractConstraint NotNull() - { - return !new Equal(null); - } - - /* - * Method: TypeOf - * - * Determines whatever the parameter if of the specified type. - * - */ - /// - /// A constraint that accept only value of the specified type - /// - public static AbstractConstraint TypeOf(Type type) - { - return new TypeOf(type); - } - - /* - * Method: TypeOf - * - * Determines whatever the parameter if of the specified type. - * - */ - /// - /// A constraint that accept only value of the specified type - /// - public static AbstractConstraint TypeOf() - { - return new TypeOf(typeof(T)); - } - - /// - /// Evaluate a parameter using a predicate - /// - /// The predicate to use - public static AbstractConstraint Matching(Predicate predicate) - { - return new PredicateConstraint(predicate); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Constraints; + +namespace Rhino.Mocks.Constraints +{ + /* + * Class: Is + * + * Common constraints. + */ + /// + /// Central location for constraints + /// + public static class Is + { + /* + * method: GreaterThan + * + * Determines whatever the parameter is greater than objToCompare. + * The parameter must implement IComparable + */ + /// + /// Evaluate a greater than constraint for . + /// + /// The object the parameter should be greater than + public static AbstractConstraint GreaterThan(IComparable objToCompare) + { + return new ComparingConstraint(objToCompare, true, false); + } + + /* + * method: LessThan + * + * Determines whatever the parameter is less than objToCompare. + * The parameter must implement IComparable + */ + /// + /// Evaluate a less than constraint for . + /// + /// The object the parameter should be less than + public static AbstractConstraint LessThan(IComparable objToCompare) + { + return new ComparingConstraint(objToCompare, false, false); + } + + /* + * method: LessThanOrEqual + * + * Determines whatever the parameter is less than or equal to objToCompare. + * The parameter must implement IComparable + */ + /// + /// Evaluate a less than or equal constraint for . + /// + /// The object the parameter should be less than or equal to + public static AbstractConstraint LessThanOrEqual(IComparable objToCompare) + { + return new ComparingConstraint(objToCompare, false, true); + } + + /* + * method: GreaterThanOrEqual + * + * Determines whatever the parameter is greater than or equal to objToCompare. + * The parameter must implement IComparable + */ + /// + /// Evaluate a greater than or equal constraint for . + /// + /// The object the parameter should be greater than or equal to + public static AbstractConstraint GreaterThanOrEqual(IComparable objToCompare) + { + return new ComparingConstraint(objToCompare, true, true); + } + + /* + * method: Equal + * + * Determines whatever the parameter equal to obj. + */ + /// + /// Evaluate an equal constraint for . + /// + /// The object the parameter should equal to + public static AbstractConstraint Equal(object obj) + { + return new Equal(obj); + } + + + /* + * method: NotEqual + * + * Determines whatever the parameter does not equal to obj. + */ + /// + /// Evaluate a not equal constraint for . + /// + /// The object the parameter should not equal to + public static AbstractConstraint NotEqual(object obj) + { + return !new Equal(obj); + } + + /// + /// Evaluate a same as constraint. + /// + /// The object the parameter should the same as. + public static AbstractConstraint Same(object obj) + { + return new Same(obj); + } + + /// + /// Evaluate a not same as constraint. + /// + /// The object the parameter should not be the same as. + public static AbstractConstraint NotSame(object obj) + { + return !new Same(obj); + } + + /* + * method: Anything + * + * This constraint always succeeds + */ + /// + /// A constraints that accept anything + /// + /// + public static AbstractConstraint Anything() + { + return new Anything(); + } + + /* + * Method: Null + * + * Determines whatever the parameter is null + * + */ + /// + /// A constraint that accept only nulls + /// + /// + public static AbstractConstraint Null() + { + return new Equal(null); + } + + /* + * Method: NotNull + * + * Determines whatever the parameter is not null + * + */ + /// + /// A constraint that accept only non null values + /// + /// + public static AbstractConstraint NotNull() + { + return !new Equal(null); + } + + /* + * Method: TypeOf + * + * Determines whatever the parameter if of the specified type. + * + */ + /// + /// A constraint that accept only value of the specified type + /// + public static AbstractConstraint TypeOf(Type type) + { + return new TypeOf(type); + } + + /* + * Method: TypeOf + * + * Determines whatever the parameter if of the specified type. + * + */ + /// + /// A constraint that accept only value of the specified type + /// + public static AbstractConstraint TypeOf() + { + return new TypeOf(typeof(T)); + } + + /// + /// Evaluate a parameter using a predicate + /// + /// The predicate to use + public static AbstractConstraint Matching(Predicate predicate) + { + return new PredicateConstraint(predicate); + } + } +} diff --git a/Rhino.Mocks/Constraints/IsArg.cs b/Rhino.Mocks/Constraints/IsArg.cs index 5b4982db..5c801a21 100644 --- a/Rhino.Mocks/Constraints/IsArg.cs +++ b/Rhino.Mocks/Constraints/IsArg.cs @@ -1,262 +1,262 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.ComponentModel; -using System.Text; - -namespace Rhino.Mocks.Constraints -{ - - /// - /// Provides access to the constraintes defined in the class to be used in context - /// with the syntax. - /// - /// The type of the argument - public class IsArg - { - - internal IsArg() { } - - - /// - /// Evaluate a greater than constraint for . - /// - /// The object the parameter should be greater than - public T GreaterThan(IComparable objToCompare) - { - objToCompare = ConvertObjectTypeToMatch(objToCompare); - ArgManager.AddInArgument(Is.GreaterThan(objToCompare)); - return default(T); - } - - /// - /// Evaluate a less than constraint for . - /// - /// The object the parameter should be less than - public T LessThan(IComparable objToCompare) - { - objToCompare = ConvertObjectTypeToMatch(objToCompare); - ArgManager.AddInArgument(Is.LessThan(objToCompare)); - return default(T); - } - - /// - /// Evaluate a less than or equal constraint for . - /// - /// The object the parameter should be less than or equal to - public T LessThanOrEqual(IComparable objToCompare) - { - objToCompare = ConvertObjectTypeToMatch(objToCompare); - ArgManager.AddInArgument(Is.LessThanOrEqual(objToCompare)); - return default(T); - } - - /// - /// Evaluate a greater than or equal constraint for . - /// - /// The object the parameter should be greater than or equal to - public T GreaterThanOrEqual(IComparable objToCompare) - { - objToCompare = ConvertObjectTypeToMatch(objToCompare); - ArgManager.AddInArgument(Is.GreaterThanOrEqual(objToCompare)); - return default(T); - } - - /// - /// Evaluate an equal constraint for . - /// - /// The object the parameter should equal to - public T Equal(object obj) - { - obj = ConvertObjectTypeToMatch(obj); - ArgManager.AddInArgument(Is.Equal(obj)); - return default(T); - } - - /// - /// Converts the object type to a better match if this is a primitive type. - /// - /// The obj. - /// - private IComparable ConvertObjectTypeToMatch(IComparable obj) - { - var obj2 = ConvertObjectTypeToMatch(obj as object); - if (obj2 is IComparable) - { - obj = obj2 as IComparable; - } - - return 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. - /// - private object ConvertObjectTypeToMatch(object obj) - { - if (typeof(T).IsPrimitive && typeof(T) != obj.GetType()) - { - try - { - obj = Convert.ChangeType(obj, typeof(T)); - } - catch (Exception ex) - { - if (ex is InvalidCastException || ex is FormatException) - { - - } - else - { - throw; - } - } - - } - return obj; - } - - - /// - /// Evaluate a not equal constraint for . - /// - /// The object the parameter should not equal to - public T NotEqual(object obj) - { - obj = ConvertObjectTypeToMatch(obj); - ArgManager.AddInArgument(Is.NotEqual(obj)); - return default(T); - } - - - /// - /// Evaluate a same as constraint. - /// - /// The object the parameter should the same as. - public T Same(object obj) - { - obj = ConvertObjectTypeToMatch(obj); - ArgManager.AddInArgument(Is.Same(obj)); - return default(T); - } - - /// - /// Evaluate a not same as constraint. - /// - /// The object the parameter should not be the same as. - public T NotSame(object obj) - { - ArgManager.AddInArgument(Is.NotSame(obj)); - return default(T); - } - - /// - /// A constraints that accept anything - /// - /// - public T Anything - { - get - { - ArgManager.AddInArgument(Is.Anything()); - return default(T); - } - } - - /// - /// A constraint that accept only nulls - /// - /// - public T Null - { - get - { - ArgManager.AddInArgument(Is.Null()); - return default(T); - } - } - - /// - /// A constraint that accept only non null values - /// - /// - public T NotNull - { - get - { - ArgManager.AddInArgument(Is.NotNull()); - return default(T); - } - } - - /// - /// 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. - /// - public T TypeOf - { - get - { - ArgManager.AddInArgument(Is.TypeOf()); - return default(T); - } - } - - /// - /// Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. - /// - /// - /// - public override bool Equals(object obj) - { - throw new InvalidOperationException("Don't use Equals() to define constraints, use Equal() instead"); - } - - /* implement GetHashCode to avoid compiler warning */ - /// - /// Serves as a hash function for a particular type. - /// - /// - /// A hash code for the current . - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - } - -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.ComponentModel; +using System.Text; + +namespace Rhino.Mocks.Constraints +{ + + /// + /// Provides access to the constraintes defined in the class to be used in context + /// with the syntax. + /// + /// The type of the argument + public class IsArg + { + + internal IsArg() { } + + + /// + /// Evaluate a greater than constraint for . + /// + /// The object the parameter should be greater than + public T GreaterThan(IComparable objToCompare) + { + objToCompare = ConvertObjectTypeToMatch(objToCompare); + ArgManager.AddInArgument(Is.GreaterThan(objToCompare)); + return default(T); + } + + /// + /// Evaluate a less than constraint for . + /// + /// The object the parameter should be less than + public T LessThan(IComparable objToCompare) + { + objToCompare = ConvertObjectTypeToMatch(objToCompare); + ArgManager.AddInArgument(Is.LessThan(objToCompare)); + return default(T); + } + + /// + /// Evaluate a less than or equal constraint for . + /// + /// The object the parameter should be less than or equal to + public T LessThanOrEqual(IComparable objToCompare) + { + objToCompare = ConvertObjectTypeToMatch(objToCompare); + ArgManager.AddInArgument(Is.LessThanOrEqual(objToCompare)); + return default(T); + } + + /// + /// Evaluate a greater than or equal constraint for . + /// + /// The object the parameter should be greater than or equal to + public T GreaterThanOrEqual(IComparable objToCompare) + { + objToCompare = ConvertObjectTypeToMatch(objToCompare); + ArgManager.AddInArgument(Is.GreaterThanOrEqual(objToCompare)); + return default(T); + } + + /// + /// Evaluate an equal constraint for . + /// + /// The object the parameter should equal to + public T Equal(object obj) + { + obj = ConvertObjectTypeToMatch(obj); + ArgManager.AddInArgument(Is.Equal(obj)); + return default(T); + } + + /// + /// Converts the object type to a better match if this is a primitive type. + /// + /// The obj. + /// + private IComparable ConvertObjectTypeToMatch(IComparable obj) + { + var obj2 = ConvertObjectTypeToMatch(obj as object); + if (obj2 is IComparable) + { + obj = obj2 as IComparable; + } + + return 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. + /// + private object ConvertObjectTypeToMatch(object obj) + { + if (typeof(T).IsPrimitive && typeof(T) != obj.GetType()) + { + try + { + obj = Convert.ChangeType(obj, typeof(T)); + } + catch (Exception ex) + { + if (ex is InvalidCastException || ex is FormatException) + { + + } + else + { + throw; + } + } + + } + return obj; + } + + + /// + /// Evaluate a not equal constraint for . + /// + /// The object the parameter should not equal to + public T NotEqual(object obj) + { + obj = ConvertObjectTypeToMatch(obj); + ArgManager.AddInArgument(Is.NotEqual(obj)); + return default(T); + } + + + /// + /// Evaluate a same as constraint. + /// + /// The object the parameter should the same as. + public T Same(object obj) + { + obj = ConvertObjectTypeToMatch(obj); + ArgManager.AddInArgument(Is.Same(obj)); + return default(T); + } + + /// + /// Evaluate a not same as constraint. + /// + /// The object the parameter should not be the same as. + public T NotSame(object obj) + { + ArgManager.AddInArgument(Is.NotSame(obj)); + return default(T); + } + + /// + /// A constraints that accept anything + /// + /// + public T Anything + { + get + { + ArgManager.AddInArgument(Is.Anything()); + return default(T); + } + } + + /// + /// A constraint that accept only nulls + /// + /// + public T Null + { + get + { + ArgManager.AddInArgument(Is.Null()); + return default(T); + } + } + + /// + /// A constraint that accept only non null values + /// + /// + public T NotNull + { + get + { + ArgManager.AddInArgument(Is.NotNull()); + return default(T); + } + } + + /// + /// 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. + /// + public T TypeOf + { + get + { + ArgManager.AddInArgument(Is.TypeOf()); + return default(T); + } + } + + /// + /// Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. + /// + /// + /// + public override bool Equals(object obj) + { + throw new InvalidOperationException("Don't use Equals() to define constraints, use Equal() instead"); + } + + /* implement GetHashCode to avoid compiler warning */ + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + } + +} diff --git a/Rhino.Mocks/Constraints/List.cs b/Rhino.Mocks/Constraints/List.cs index 9ba068bc..1a23a45f 100644 --- a/Rhino.Mocks/Constraints/List.cs +++ b/Rhino.Mocks/Constraints/List.cs @@ -1,133 +1,133 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Collections; -using Rhino.Mocks.Constraints; - -namespace Rhino.Mocks.Constraints -{ - /* - * class: List - * - * Constraints for dealing with lists. - * - */ - /// - /// Central location for constraints about lists and collections - /// - public static class List - { - - /* - * Method: IsIn - * - * Determines whether the specified obj is in the parameter. - * The parameter must be IEnumerable. - */ - /// - /// Determines whether the specified obj is in the parameter. - /// The parameter must be IEnumerable. - /// - /// Obj. - /// - public static AbstractConstraint IsIn(object obj) - { - return new IsIn(obj); - } - - /* - * Method: OneOf - * - * Determines whatever the parameter is in the collection. - */ - /// - /// Determines whatever the parameter is in the collection. - /// - public static AbstractConstraint OneOf(IEnumerable collection) - { - return new OneOf(collection); - } - - /* - * Method Equal - * Determines that the parameter collection is identical to the specified collection - * This is done by iterating the collections and comparing each element. - */ - /// - /// Determines that the parameter collection is identical to the specified collection - /// - public static AbstractConstraint Equal(IEnumerable collection) - { - return new CollectionEqual(collection); - } - - /// - /// Determines that the parameter collection has the specified number of elements. - /// - /// The constraint that should be applied to the collection count. - public static AbstractConstraint Count(AbstractConstraint constraint) - { - return new CollectionCount(constraint); - } - - /// - /// 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. - public static AbstractConstraint Element(int index, AbstractConstraint constraint) - { - return new ListElement(index, constraint); - } - - /// - /// 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. - public static AbstractConstraint Element(T key, AbstractConstraint constraint) - { - return new KeyedListElement(key, constraint); - } - - /* - * Method ContainsAll - * Determines that all elements of the specified collection are in the the parameter collection - */ - /// - /// 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. - public static AbstractConstraint ContainsAll(IEnumerable collection) - { - return new ContainsAll(collection); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Collections; +using Rhino.Mocks.Constraints; + +namespace Rhino.Mocks.Constraints +{ + /* + * class: List + * + * Constraints for dealing with lists. + * + */ + /// + /// Central location for constraints about lists and collections + /// + public static class List + { + + /* + * Method: IsIn + * + * Determines whether the specified obj is in the parameter. + * The parameter must be IEnumerable. + */ + /// + /// Determines whether the specified obj is in the parameter. + /// The parameter must be IEnumerable. + /// + /// Obj. + /// + public static AbstractConstraint IsIn(object obj) + { + return new IsIn(obj); + } + + /* + * Method: OneOf + * + * Determines whatever the parameter is in the collection. + */ + /// + /// Determines whatever the parameter is in the collection. + /// + public static AbstractConstraint OneOf(IEnumerable collection) + { + return new OneOf(collection); + } + + /* + * Method Equal + * Determines that the parameter collection is identical to the specified collection + * This is done by iterating the collections and comparing each element. + */ + /// + /// Determines that the parameter collection is identical to the specified collection + /// + public static AbstractConstraint Equal(IEnumerable collection) + { + return new CollectionEqual(collection); + } + + /// + /// Determines that the parameter collection has the specified number of elements. + /// + /// The constraint that should be applied to the collection count. + public static AbstractConstraint Count(AbstractConstraint constraint) + { + return new CollectionCount(constraint); + } + + /// + /// 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. + public static AbstractConstraint Element(int index, AbstractConstraint constraint) + { + return new ListElement(index, constraint); + } + + /// + /// 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. + public static AbstractConstraint Element(T key, AbstractConstraint constraint) + { + return new KeyedListElement(key, constraint); + } + + /* + * Method ContainsAll + * Determines that all elements of the specified collection are in the the parameter collection + */ + /// + /// 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. + public static AbstractConstraint ContainsAll(IEnumerable collection) + { + return new ContainsAll(collection); + } + } +} diff --git a/Rhino.Mocks/Constraints/ListArg.cs b/Rhino.Mocks/Constraints/ListArg.cs index 6dd66886..ce41cd31 100644 --- a/Rhino.Mocks/Constraints/ListArg.cs +++ b/Rhino.Mocks/Constraints/ListArg.cs @@ -1,101 +1,101 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Collections; - -namespace Rhino.Mocks.Constraints -{ - /// - /// Provides access to the constraints defined in the class to be used in context - /// with the syntax. - /// - public class ListArg // where T : IEnumerable - { - internal ListArg() { ;} - - /// - /// Determines whether the specified object is in the parameter. - /// The parameter must be IEnumerable. - /// - /// Obj. - /// - public T IsIn(object obj) - { - ArgManager.AddInArgument(List.IsIn(obj)); - return default(T); - } - - /// - /// Determines whatever the parameter is in the collection. - /// - public T OneOf(IEnumerable collection) - { - ArgManager.AddInArgument(List.OneOf(collection)); - return default(T); - } - - /// - /// Determines that the parameter collection is identical to the specified collection - /// - public T Equal(IEnumerable collection) - { - ArgManager.AddInArgument(List.Equal(collection)); - return default(T); - } - - /// - /// Determines that the parameter collection has the specified number of elements. - /// - /// The constraint that should be applied to the collection count. - public T Count(AbstractConstraint constraint) - { - ArgManager.AddInArgument(List.Count(constraint)); - return default(T); - } - - /// - /// 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. - public T Element(int index, AbstractConstraint constraint) - { - ArgManager.AddInArgument(List.Element(index, constraint)); - return default(T); - } - - /// - /// 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. - public T ContainsAll(IEnumerable collection) - { - ArgManager.AddInArgument(List.ContainsAll(collection)); - return default(T); - } - - /// - /// Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. - /// - /// - /// - public override bool Equals(object obj) - { - throw new InvalidOperationException("Don't use Equals() to define constraints, use Equal() instead"); - } - - - /* implement GetHashCode to avoid compiler warning */ - /// - /// Serves as a hash function for a particular type. - /// - /// - /// A hash code for the current . - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - } -} +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections; + +namespace Rhino.Mocks.Constraints +{ + /// + /// Provides access to the constraints defined in the class to be used in context + /// with the syntax. + /// + public class ListArg // where T : IEnumerable + { + internal ListArg() { ;} + + /// + /// Determines whether the specified object is in the parameter. + /// The parameter must be IEnumerable. + /// + /// Obj. + /// + public T IsIn(object obj) + { + ArgManager.AddInArgument(List.IsIn(obj)); + return default(T); + } + + /// + /// Determines whatever the parameter is in the collection. + /// + public T OneOf(IEnumerable collection) + { + ArgManager.AddInArgument(List.OneOf(collection)); + return default(T); + } + + /// + /// Determines that the parameter collection is identical to the specified collection + /// + public T Equal(IEnumerable collection) + { + ArgManager.AddInArgument(List.Equal(collection)); + return default(T); + } + + /// + /// Determines that the parameter collection has the specified number of elements. + /// + /// The constraint that should be applied to the collection count. + public T Count(AbstractConstraint constraint) + { + ArgManager.AddInArgument(List.Count(constraint)); + return default(T); + } + + /// + /// 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. + public T Element(int index, AbstractConstraint constraint) + { + ArgManager.AddInArgument(List.Element(index, constraint)); + return default(T); + } + + /// + /// 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. + public T ContainsAll(IEnumerable collection) + { + ArgManager.AddInArgument(List.ContainsAll(collection)); + return default(T); + } + + /// + /// Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. + /// + /// + /// + public override bool Equals(object obj) + { + throw new InvalidOperationException("Don't use Equals() to define constraints, use Equal() instead"); + } + + + /* implement GetHashCode to avoid compiler warning */ + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + } +} diff --git a/Rhino.Mocks/Constraints/OutRefArgDummy.cs b/Rhino.Mocks/Constraints/OutRefArgDummy.cs index 2e2e8607..0961170e 100644 --- a/Rhino.Mocks/Constraints/OutRefArgDummy.cs +++ b/Rhino.Mocks/Constraints/OutRefArgDummy.cs @@ -1,19 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Rhino.Mocks.Constraints -{ - /// - /// Provides a dummy field to pass as out or ref argument. - /// - /// - public class OutRefArgDummy - { - /// - /// Dummy field to satisfy the compiler. Used for out and ref arguments. - /// - public T Dummy; - } - -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rhino.Mocks.Constraints +{ + /// + /// Provides a dummy field to pass as out or ref argument. + /// + /// + public class OutRefArgDummy + { + /// + /// Dummy field to satisfy the compiler. Used for out and ref arguments. + /// + public T Dummy; + } + +} diff --git a/Rhino.Mocks/Constraints/Property.cs b/Rhino.Mocks/Constraints/Property.cs index 65f7d510..248f4f87 100644 --- a/Rhino.Mocks/Constraints/Property.cs +++ b/Rhino.Mocks/Constraints/Property.cs @@ -1,168 +1,168 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Constraints; - -namespace Rhino.Mocks.Constraints -{ - /* - * Class: Property - * - * Constraints for dealing with object's properties - */ - /// - /// Central location for constraints for object's properties - /// - public static class Property - { - /* - * Method: Value - * - * Determines that the parameter has property with the specified value - * - */ - - /// - /// Constrains the parameter to have property with the specified value - /// - /// Name of the property. - /// Expected value. - /// - public static AbstractConstraint Value(string propertyName, object expectedValue) - { - return new PropertyIs(propertyName, expectedValue); - } - - /// - /// 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. - /// - public static AbstractConstraint Value(Type declaringType, string propertyName, object expectedValue) - { - return new PropertyIs(declaringType, propertyName, expectedValue); - } - - /// - /// Constrains the parameter to have a property satisfying a specified constraint. - /// - /// Name of the property. - /// Constraint for the property. - public static AbstractConstraint ValueConstraint(string propertyName, AbstractConstraint propertyConstraint) - { - return new PropertyConstraint(propertyName, propertyConstraint); - } - - /// - /// 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. - public static AbstractConstraint ValueConstraint(Type declaringType, string propertyName, AbstractConstraint propertyConstraint) - { - return new PropertyConstraint(declaringType, propertyName, propertyConstraint); - } - - /* - * Method: IsNull - * - * Determines that the parameter has property with null value - * - */ - /// - /// Determines whether the parameter has the specified property and that it is null. - /// - /// Name of the property. - /// - public static AbstractConstraint IsNull(string propertyName) - { - return new PropertyIs(propertyName, null); - } - - /// - /// 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. - /// - public static AbstractConstraint IsNull(Type declaringType, string propertyName) - { - return new PropertyIs(declaringType, propertyName, null); - } - - /* - * Method: IsNotNull - * - * Determines that the parameter has property with non-null value - * - */ - /// - /// Determines whether the parameter has the specified property and that it is not null. - /// - /// Name of the property. - /// - public static AbstractConstraint IsNotNull(string propertyName) - { - return !new PropertyIs(propertyName, null); - } - - /// - /// 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. - /// - public static AbstractConstraint IsNotNull(Type declaringType, string propertyName) - { - return !new PropertyIs(declaringType, propertyName, null); - } - - /// - /// 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. - /// - public static AbstractConstraint AllPropertiesMatch(object expected) - { - return new AllPropertiesMatchConstraint(expected); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Constraints; + +namespace Rhino.Mocks.Constraints +{ + /* + * Class: Property + * + * Constraints for dealing with object's properties + */ + /// + /// Central location for constraints for object's properties + /// + public static class Property + { + /* + * Method: Value + * + * Determines that the parameter has property with the specified value + * + */ + + /// + /// Constrains the parameter to have property with the specified value + /// + /// Name of the property. + /// Expected value. + /// + public static AbstractConstraint Value(string propertyName, object expectedValue) + { + return new PropertyIs(propertyName, expectedValue); + } + + /// + /// 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. + /// + public static AbstractConstraint Value(Type declaringType, string propertyName, object expectedValue) + { + return new PropertyIs(declaringType, propertyName, expectedValue); + } + + /// + /// Constrains the parameter to have a property satisfying a specified constraint. + /// + /// Name of the property. + /// Constraint for the property. + public static AbstractConstraint ValueConstraint(string propertyName, AbstractConstraint propertyConstraint) + { + return new PropertyConstraint(propertyName, propertyConstraint); + } + + /// + /// 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. + public static AbstractConstraint ValueConstraint(Type declaringType, string propertyName, AbstractConstraint propertyConstraint) + { + return new PropertyConstraint(declaringType, propertyName, propertyConstraint); + } + + /* + * Method: IsNull + * + * Determines that the parameter has property with null value + * + */ + /// + /// Determines whether the parameter has the specified property and that it is null. + /// + /// Name of the property. + /// + public static AbstractConstraint IsNull(string propertyName) + { + return new PropertyIs(propertyName, null); + } + + /// + /// 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. + /// + public static AbstractConstraint IsNull(Type declaringType, string propertyName) + { + return new PropertyIs(declaringType, propertyName, null); + } + + /* + * Method: IsNotNull + * + * Determines that the parameter has property with non-null value + * + */ + /// + /// Determines whether the parameter has the specified property and that it is not null. + /// + /// Name of the property. + /// + public static AbstractConstraint IsNotNull(string propertyName) + { + return !new PropertyIs(propertyName, null); + } + + /// + /// 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. + /// + public static AbstractConstraint IsNotNull(Type declaringType, string propertyName) + { + return !new PropertyIs(declaringType, propertyName, null); + } + + /// + /// 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. + /// + public static AbstractConstraint AllPropertiesMatch(object expected) + { + return new AllPropertiesMatchConstraint(expected); + } + } +} diff --git a/Rhino.Mocks/Constraints/PublicField.cs b/Rhino.Mocks/Constraints/PublicField.cs index 939d9e91..ff2477ca 100644 --- a/Rhino.Mocks/Constraints/PublicField.cs +++ b/Rhino.Mocks/Constraints/PublicField.cs @@ -1,121 +1,121 @@ -using System; -using Rhino.Mocks.Constraints; - -namespace Rhino.Mocks.Constraints -{ - /* - * Class: PublicField - * - * Constraints for dealing with object's public fields - */ - /// - /// Central location for constraints for object's public fields - /// - public static class PublicField - { - /* - * Method: Value - * - * Determines that the parameter has a public field with the specified value - * - */ - - /// - /// Constrains the parameter to have a public field with the specified value - /// - /// Name of the public field. - /// Expected value. - /// - public static AbstractConstraint Value(string publicFieldName, object expectedValue) - { - return new PublicFieldIs(publicFieldName, expectedValue); - } - - /// - /// 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. - /// - public static AbstractConstraint Value(Type declaringType, string publicFieldName, object expectedValue) - { - return new PublicFieldIs(declaringType, publicFieldName, expectedValue); - } - - /// - /// Constrains the parameter to have a public field satisfying a specified constraint. - /// - /// Name of the public field. - /// Constraint for the public field. - public static AbstractConstraint ValueConstraint(string publicFieldName, AbstractConstraint publicFieldConstraint) - { - return new PublicFieldConstraint(publicFieldName, publicFieldConstraint); - } - - /// - /// 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. - public static AbstractConstraint ValueConstraint(Type declaringType, string publicFieldName, AbstractConstraint publicFieldConstraint) - { - return new PublicFieldConstraint(declaringType, publicFieldName, publicFieldConstraint); - } - - /* - * Method: IsNull - * - * Determines that the parameter has a public field with null value - * - */ - /// - /// Determines whether the parameter has the specified public field and that it is null. - /// - /// Name of the public field. - /// - public static AbstractConstraint IsNull(string publicFieldName) - { - return new PublicFieldIs(publicFieldName, null); - } - - /// - /// 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. - /// - public static AbstractConstraint IsNull(Type declaringType, string publicFieldName) - { - return new PublicFieldIs(declaringType, publicFieldName, null); - } - - /* - * Method: IsNotNull - * - * Determines that the parameter has a public field with non-null value - * - */ - /// - /// Determines whether the parameter has the specified public field and that it is not null. - /// - /// Name of the public field. - /// - public static AbstractConstraint IsNotNull(string publicFieldName) - { - return !new PublicFieldIs(publicFieldName, null); - } - - /// - /// 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. - /// - public static AbstractConstraint IsNotNull(Type declaringType, string publicFieldName) - { - return !new PublicFieldIs(declaringType, publicFieldName, null); - } - } -} +using System; +using Rhino.Mocks.Constraints; + +namespace Rhino.Mocks.Constraints +{ + /* + * Class: PublicField + * + * Constraints for dealing with object's public fields + */ + /// + /// Central location for constraints for object's public fields + /// + public static class PublicField + { + /* + * Method: Value + * + * Determines that the parameter has a public field with the specified value + * + */ + + /// + /// Constrains the parameter to have a public field with the specified value + /// + /// Name of the public field. + /// Expected value. + /// + public static AbstractConstraint Value(string publicFieldName, object expectedValue) + { + return new PublicFieldIs(publicFieldName, expectedValue); + } + + /// + /// 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. + /// + public static AbstractConstraint Value(Type declaringType, string publicFieldName, object expectedValue) + { + return new PublicFieldIs(declaringType, publicFieldName, expectedValue); + } + + /// + /// Constrains the parameter to have a public field satisfying a specified constraint. + /// + /// Name of the public field. + /// Constraint for the public field. + public static AbstractConstraint ValueConstraint(string publicFieldName, AbstractConstraint publicFieldConstraint) + { + return new PublicFieldConstraint(publicFieldName, publicFieldConstraint); + } + + /// + /// 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. + public static AbstractConstraint ValueConstraint(Type declaringType, string publicFieldName, AbstractConstraint publicFieldConstraint) + { + return new PublicFieldConstraint(declaringType, publicFieldName, publicFieldConstraint); + } + + /* + * Method: IsNull + * + * Determines that the parameter has a public field with null value + * + */ + /// + /// Determines whether the parameter has the specified public field and that it is null. + /// + /// Name of the public field. + /// + public static AbstractConstraint IsNull(string publicFieldName) + { + return new PublicFieldIs(publicFieldName, null); + } + + /// + /// 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. + /// + public static AbstractConstraint IsNull(Type declaringType, string publicFieldName) + { + return new PublicFieldIs(declaringType, publicFieldName, null); + } + + /* + * Method: IsNotNull + * + * Determines that the parameter has a public field with non-null value + * + */ + /// + /// Determines whether the parameter has the specified public field and that it is not null. + /// + /// Name of the public field. + /// + public static AbstractConstraint IsNotNull(string publicFieldName) + { + return !new PublicFieldIs(publicFieldName, null); + } + + /// + /// 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. + /// + public static AbstractConstraint IsNotNull(Type declaringType, string publicFieldName) + { + return !new PublicFieldIs(declaringType, publicFieldName, null); + } + } +} diff --git a/Rhino.Mocks/Constraints/Text.cs b/Rhino.Mocks/Constraints/Text.cs index 21e424bc..118ca45c 100644 --- a/Rhino.Mocks/Constraints/Text.cs +++ b/Rhino.Mocks/Constraints/Text.cs @@ -1,98 +1,98 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using Rhino.Mocks.Constraints; - -namespace Rhino.Mocks.Constraints -{ - /* - * class: Text - * - * Contraints to deal with text and strings - * - */ - /// - /// Central location for all text related constraints - /// - public static class Text - { - /* - * Method: StartsWith - * - * The parameter starts with the specified string - */ - /// - /// Constrain the argument to starts with the specified string - /// - public static AbstractConstraint StartsWith(string start) - { - return new StartsWith(start); - } - - /* - * Method: EndsWith - * - * The parameter ends with the specified string - */ - /// - /// Constrain the argument to end with the specified string - /// - public static AbstractConstraint EndsWith(string end) - { - return new EndsWith(end); - } - - - /* - * Method: Contains - * - * The parameter contains the specified string - */ - /// - /// Constrain the argument to contain the specified string - /// - public static AbstractConstraint Contains(string innerString) - { - return new Contains(innerString); - } - - /* - * Method: Like - * - * The parameter must satisfied the specified regular expression. - */ - /// - /// Constrain the argument to validate according to regex pattern - /// - public static AbstractConstraint Like(string pattern) - { - return new Like(pattern); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using Rhino.Mocks.Constraints; + +namespace Rhino.Mocks.Constraints +{ + /* + * class: Text + * + * Contraints to deal with text and strings + * + */ + /// + /// Central location for all text related constraints + /// + public static class Text + { + /* + * Method: StartsWith + * + * The parameter starts with the specified string + */ + /// + /// Constrain the argument to starts with the specified string + /// + public static AbstractConstraint StartsWith(string start) + { + return new StartsWith(start); + } + + /* + * Method: EndsWith + * + * The parameter ends with the specified string + */ + /// + /// Constrain the argument to end with the specified string + /// + public static AbstractConstraint EndsWith(string end) + { + return new EndsWith(end); + } + + + /* + * Method: Contains + * + * The parameter contains the specified string + */ + /// + /// Constrain the argument to contain the specified string + /// + public static AbstractConstraint Contains(string innerString) + { + return new Contains(innerString); + } + + /* + * Method: Like + * + * The parameter must satisfied the specified regular expression. + */ + /// + /// Constrain the argument to validate according to regex pattern + /// + public static AbstractConstraint Like(string pattern) + { + return new Like(pattern); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Constraints/TextArg.cs b/Rhino.Mocks/Constraints/TextArg.cs index 0e631bf3..55ebb29d 100644 --- a/Rhino.Mocks/Constraints/TextArg.cs +++ b/Rhino.Mocks/Constraints/TextArg.cs @@ -1,73 +1,73 @@ -using System; -using System.Text; - -namespace Rhino.Mocks.Constraints -{ - /// - /// Provides access to the constraintes defined in the class to be used in context - /// with the syntax. - /// - public class TextArg - { - internal TextArg() { ;} - - /// - /// Constrain the argument to starts with the specified string - /// - /// - public string StartsWith(string start) - { - ArgManager.AddInArgument(Text.StartsWith(start)); - return null; - } - - /// - /// Constrain the argument to end with the specified string - /// - public string EndsWith(string end) - { - ArgManager.AddInArgument(Text.EndsWith(end)); - return null; - } - - /// - /// Constrain the argument to contain the specified string - /// - public string Contains(string innerString) - { - ArgManager.AddInArgument(Text.Contains(innerString)); - return null; - } - - /// - /// Constrain the argument to validate according to regex pattern - /// - public string Like(string pattern) - { - ArgManager.AddInArgument(Text.Like(pattern)); - return null; - } - - /// - /// Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. - /// - /// - /// - public override bool Equals(object obj) - { - throw new InvalidOperationException("Don't use Equals() to define constraints, use Equal() instead"); - } - - /* implement GetHashCode to avoid compiler warning */ - /// - /// Serves as a hash function for a particular type. - /// - /// - /// A hash code for the current . - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - } -} +using System; +using System.Text; + +namespace Rhino.Mocks.Constraints +{ + /// + /// Provides access to the constraintes defined in the class to be used in context + /// with the syntax. + /// + public class TextArg + { + internal TextArg() { ;} + + /// + /// Constrain the argument to starts with the specified string + /// + /// + public string StartsWith(string start) + { + ArgManager.AddInArgument(Text.StartsWith(start)); + return null; + } + + /// + /// Constrain the argument to end with the specified string + /// + public string EndsWith(string end) + { + ArgManager.AddInArgument(Text.EndsWith(end)); + return null; + } + + /// + /// Constrain the argument to contain the specified string + /// + public string Contains(string innerString) + { + ArgManager.AddInArgument(Text.Contains(innerString)); + return null; + } + + /// + /// Constrain the argument to validate according to regex pattern + /// + public string Like(string pattern) + { + ArgManager.AddInArgument(Text.Like(pattern)); + return null; + } + + /// + /// Throws NotSupportedException. Don't use Equals to define constraints. Use Equal instead. + /// + /// + /// + public override bool Equals(object obj) + { + throw new InvalidOperationException("Don't use Equals() to define constraints, use Equal() instead"); + } + + /* implement GetHashCode to avoid compiler warning */ + /// + /// Serves as a hash function for a particular type. + /// + /// + /// A hash code for the current . + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + } +} diff --git a/Rhino.Mocks/Delegates.cs b/Rhino.Mocks/Delegates.cs index 8a34c3f7..ea28b9ef 100644 --- a/Rhino.Mocks/Delegates.cs +++ b/Rhino.Mocks/Delegates.cs @@ -1,97 +1,97 @@ -namespace Rhino.Mocks -{ - /// - /// This class defines a lot of method signatures, which we will use - /// to allow compatability on net-2.0 - /// - public class Delegates - { - /// - /// dummy - /// - public delegate void Action(); - /// - /// dummy - /// - public delegate TReturnValue Function(); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4); - /// - /// dummy - /// - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8); - /// - /// dummy - /// - public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8, TArg9 args9); - /// - /// dummy - /// - public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8, TArg9 args9); - } +namespace Rhino.Mocks +{ + /// + /// This class defines a lot of method signatures, which we will use + /// to allow compatability on net-2.0 + /// + public class Delegates + { + /// + /// dummy + /// + public delegate void Action(); + /// + /// dummy + /// + public delegate TReturnValue Function(); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4); + /// + /// dummy + /// + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8); + /// + /// dummy + /// + public delegate void Action(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8, TArg9 args9); + /// + /// dummy + /// + public delegate TReturnValue Function(TArg0 args0, TArg1 args1, TArg2 args2, TArg3 args3, TArg4 args4, TArg5 args5, TArg6 args6, TArg7 args7, TArg8 args8, TArg9 args9); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Diagram.cd b/Rhino.Mocks/Diagram.cd index bad2dfb2..ed8c1020 100644 --- a/Rhino.Mocks/Diagram.cd +++ b/Rhino.Mocks/Diagram.cd @@ -1,578 +1,578 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Constraints\AbstractConstraint.cs - AAAAAAAAIAAAAAAAABACAAAAAAAAAIAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AEAAAAAAIAAAAAAAAAAAQAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAAAAAAAAAABAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAgAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAQAAAAAAAAAEAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAIAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIACAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - - - - - - Constraints\Constraints.cs - AAAAAAAAIAAAAAAAAAAEAAAAAIAAAAQAAAAAIAAAAAA= - - - - - - Constraints\Is.cs - ACAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAIEARRACCA= - - - - - - Constraints\List.cs - AAAAAAAAAAQAAAAAgAAAAAAAAQAAAAAAAAAAAAAAAAA= - - - - - - Constraints\Property.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAgEAAAAAA= - - - - - - Constraints\Text.cs - AACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAA= - - - - - - Expect.cs - AAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIA= - - - - - - LastCall.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAQIAEAFAQIA= - - - - - - MockRepository.cs - EAAAQBAgMDAAAUAAkAAYAAACAAkMEAQBCQABSAwAECQ= - - - - - - - - MockRepository.cs - - - - - - - - - SetupResult.cs - AAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAIA= - - - - - - Exceptions\ExpectationViolationException.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Exceptions\ObjectNotMockFromThisRepositoryException.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Expectations\AbstractExpectation.cs - BQAAAIAQAoIgAKBAgAAoQIAEAgIAEIAAAABQHBACJBA= - - - - - - - Expectations\AnyArgsExpectation.cs - AQAAAAAAAIAAAAAAgAAAAAAAAAAAEIAAAAAAAAAAAAA= - - - - - - Expectations\ArgsEqualExpectation.cs - AQAAAAAAAIAAAAAAgAAAAAAAAAAAAIAgAAAAIAAAAAA= - - - - - - Expectations\CallbackExpectation.cs - AQBAAAAAAIAAAAAAgAAAAAAAAAAAAIAAAEAAAAAAAAA= - - - - - - Expectations\ConstraintsExpectation.cs - AQAAAAAAAIAAAAAAgAAAAAAAAAAAAKAAAAAQAAAAAEA= - - - - - - Generated\ExpectationsListGenerated.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Generated\ProxyMethodExpectationsDictionaryGenerated.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Generated\ProxyStateDictionaryGenerated.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Impl\CreateMethodExpectation.cs - AAAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAEAAA= - - - - - - - Impl\CreateMethodExpectationForSetupResult.cs - AAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Impl\MethodOptions.cs - IAAEAAAAAAACACwAAAEAAAQACAwAARJABQMAkAEAQAA= - - - - - - - Impl\MockedObjectsEquality.cs - BAAAAAAAAAAAAAAAAAIAAAAAAARAAIAAQABAAAAAAAA= - - - - - - - Impl\ProxyInstance.cs - AAgAAAIJAAAKAAgAIAAAAAAAAAAQAAAAAAAICQABAAA= - - - - - - - Impl\Range.cs - AAAAEAAAABAQAAAEEAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Impl\RecordDynamicMockState.cs - AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= - - - - - - Impl\RecordMockState.cs - AAAAAAIAKAACgQAABAAAQAAQAEAwAAAAEQAAgAAAAQA= - - - - - - - Impl\RecordPartialMockState.cs - AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= - - - - - - Impl\ReplayDynamicMockState.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAA= - - - - - - Impl\ReplayMockState.cs - AAAAAAACIAACAQgAAAAAAAAAAAECAAAAIQAAAAAAAQA= - - - - - - - Impl\ReplayPartialMockState.cs - AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAA= - - - - - - Impl\RhinoInterceptor.cs - AAAAAAAAAAQCAAAAAAAAAAAAAAAAAAAAAgAAAgAAAAA= - - - - - - - Impl\Validate.cs - AAAAAAAAAAEAAAAAAAAAAAAAAAAAAACAAAAAEAAAAAA= - - - - - - Impl\VerifiedMockState.cs - AAAAAAAAIAAAAQAAAAAAAAAAAAAgBAAAAQAAAAAAAQA= - - - - - - - MethodRecorders\MethodRecorderBase.cs - EACIEAAAAAAAAoMAACAIEAQCAgQGAAEBBACIEAgABQA= - - - - - - - MethodRecorders\OrderedMethodRecorder.cs - AAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAAAACAAAAAAAA= - - - - - - MethodRecorders\ProxyMethodExpectationTriplet.cs - AAAAAAAACAAAACgAgAAgAAAAAAAAAICAAAAAgAAAAAA= - - - - - - MethodRecorders\ProxyMethodPair.cs - AAAAAAAACAAAACgAgAAgAAAAAAAAAIAAAAAAAAAAAAA= - - - - - - MethodRecorders\RecorderChanger.cs - AAAAAAAAACACAAAAAAAAAAAAAAAAAAAACAAAAAAAAAA= - - - - - - - MethodRecorders\UnorderedMethodRecorder.cs - AACIAAAAAAAAAAAAAAAIBAQAEAAEAAgBAACIEAgAAAA= - - - - - - Utilities\MethodCallUtil.cs - AAAAAAAAAAAAAAAAAgAAAAAAAAAQAAAAAAAAAAAAAAA= - - - - - Utilities\MethodCallUtil.cs - - - - - - - - Utilities\ReturnValueUtil.cs - AAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA= - - - - - - Interfaces\ICreateMethodExpectation.cs - AAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - - - - - - Interfaces\IExpectation.cs - AQAAAIAQAAIAAABAAAAoAAAEAgAAAAAAAABADAACABA= - - - - - - Interfaces\IMethodOptions.cs - AAAAAAAAAAAAACAAAAAAAAQACAAAABAAAQIAEAEAQAA= - - - - - - Interfaces\IMethodRecorder.cs - EAAAEAAAAAAAAAEAACAAEAACAgQAAAEBBACAAAAABQA= - - - - - - Interfaces\IMockedObject.cs - AAAAAAIAAAAIAAgAAAAAAAAAAAAAAAAAAAAICQABAAA= - - - - - - Interfaces\IMockState.cs - AAAAAAAAIAAAAQAAAAAAAAAAAAAgAAAAAQAAAAAAAQA= - - - - - - Interfaces\IRepeat.cs - IAAAAAAAAAAAAAAAAAEAAAAAAAwAAAIAAAAAAAAAAAA= - - - - - - Impl\RepeatableOption.cs - IAAAAAAAAAAAAAAAAAEAAAwAAAAIAAAAAAAAAAAAAAA= - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Constraints\AbstractConstraint.cs + AAAAAAAAIAAAAAAAABACAAAAAAAAAIAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AEAAAAAAIAAAAAAAAAAAQAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAAAAAAAAAABAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAgAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAQAAAAAAAAAEAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAIAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIACAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + + + + + + Constraints\Constraints.cs + AAAAAAAAIAAAAAAAAAAEAAAAAIAAAAQAAAAAIAAAAAA= + + + + + + Constraints\Is.cs + ACAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAIEARRACCA= + + + + + + Constraints\List.cs + AAAAAAAAAAQAAAAAgAAAAAAAAQAAAAAAAAAAAAAAAAA= + + + + + + Constraints\Property.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAgEAAAAAA= + + + + + + Constraints\Text.cs + AACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAA= + + + + + + Expect.cs + AAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIA= + + + + + + LastCall.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAQIAEAFAQIA= + + + + + + MockRepository.cs + EAAAQBAgMDAAAUAAkAAYAAACAAkMEAQBCQABSAwAECQ= + + + + + + + + MockRepository.cs + + + + + + + + + SetupResult.cs + AAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAIA= + + + + + + Exceptions\ExpectationViolationException.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Exceptions\ObjectNotMockFromThisRepositoryException.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Expectations\AbstractExpectation.cs + BQAAAIAQAoIgAKBAgAAoQIAEAgIAEIAAAABQHBACJBA= + + + + + + + Expectations\AnyArgsExpectation.cs + AQAAAAAAAIAAAAAAgAAAAAAAAAAAEIAAAAAAAAAAAAA= + + + + + + Expectations\ArgsEqualExpectation.cs + AQAAAAAAAIAAAAAAgAAAAAAAAAAAAIAgAAAAIAAAAAA= + + + + + + Expectations\CallbackExpectation.cs + AQBAAAAAAIAAAAAAgAAAAAAAAAAAAIAAAEAAAAAAAAA= + + + + + + Expectations\ConstraintsExpectation.cs + AQAAAAAAAIAAAAAAgAAAAAAAAAAAAKAAAAAQAAAAAEA= + + + + + + Generated\ExpectationsListGenerated.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Generated\ProxyMethodExpectationsDictionaryGenerated.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Generated\ProxyStateDictionaryGenerated.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Impl\CreateMethodExpectation.cs + AAAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAEAAA= + + + + + + + Impl\CreateMethodExpectationForSetupResult.cs + AAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Impl\MethodOptions.cs + IAAEAAAAAAACACwAAAEAAAQACAwAARJABQMAkAEAQAA= + + + + + + + Impl\MockedObjectsEquality.cs + BAAAAAAAAAAAAAAAAAIAAAAAAARAAIAAQABAAAAAAAA= + + + + + + + Impl\ProxyInstance.cs + AAgAAAIJAAAKAAgAIAAAAAAAAAAQAAAAAAAICQABAAA= + + + + + + + Impl\Range.cs + AAAAEAAAABAQAAAEEAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Impl\RecordDynamicMockState.cs + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + + + + + + Impl\RecordMockState.cs + AAAAAAIAKAACgQAABAAAQAAQAEAwAAAAEQAAgAAAAQA= + + + + + + + Impl\RecordPartialMockState.cs + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA= + + + + + + Impl\ReplayDynamicMockState.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAA= + + + + + + Impl\ReplayMockState.cs + AAAAAAACIAACAQgAAAAAAAAAAAECAAAAIQAAAAAAAQA= + + + + + + + Impl\ReplayPartialMockState.cs + AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAA= + + + + + + Impl\RhinoInterceptor.cs + AAAAAAAAAAQCAAAAAAAAAAAAAAAAAAAAAgAAAgAAAAA= + + + + + + + Impl\Validate.cs + AAAAAAAAAAEAAAAAAAAAAAAAAAAAAACAAAAAEAAAAAA= + + + + + + Impl\VerifiedMockState.cs + AAAAAAAAIAAAAQAAAAAAAAAAAAAgBAAAAQAAAAAAAQA= + + + + + + + MethodRecorders\MethodRecorderBase.cs + EACIEAAAAAAAAoMAACAIEAQCAgQGAAEBBACIEAgABQA= + + + + + + + MethodRecorders\OrderedMethodRecorder.cs + AAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAAAACAAAAAAAA= + + + + + + MethodRecorders\ProxyMethodExpectationTriplet.cs + AAAAAAAACAAAACgAgAAgAAAAAAAAAICAAAAAgAAAAAA= + + + + + + MethodRecorders\ProxyMethodPair.cs + AAAAAAAACAAAACgAgAAgAAAAAAAAAIAAAAAAAAAAAAA= + + + + + + MethodRecorders\RecorderChanger.cs + AAAAAAAAACACAAAAAAAAAAAAAAAAAAAACAAAAAAAAAA= + + + + + + + MethodRecorders\UnorderedMethodRecorder.cs + AACIAAAAAAAAAAAAAAAIBAQAEAAEAAgBAACIEAgAAAA= + + + + + + Utilities\MethodCallUtil.cs + AAAAAAAAAAAAAAAAAgAAAAAAAAAQAAAAAAAAAAAAAAA= + + + + + Utilities\MethodCallUtil.cs + + + + + + + + Utilities\ReturnValueUtil.cs + AAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA= + + + + + + Interfaces\ICreateMethodExpectation.cs + AAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + + + + Interfaces\IExpectation.cs + AQAAAIAQAAIAAABAAAAoAAAEAgAAAAAAAABADAACABA= + + + + + + Interfaces\IMethodOptions.cs + AAAAAAAAAAAAACAAAAAAAAQACAAAABAAAQIAEAEAQAA= + + + + + + Interfaces\IMethodRecorder.cs + EAAAEAAAAAAAAAEAACAAEAACAgQAAAEBBACAAAAABQA= + + + + + + Interfaces\IMockedObject.cs + AAAAAAIAAAAIAAgAAAAAAAAAAAAAAAAAAAAICQABAAA= + + + + + + Interfaces\IMockState.cs + AAAAAAAAIAAAAQAAAAAAAAAAAAAgAAAAAQAAAAAAAQA= + + + + + + Interfaces\IRepeat.cs + IAAAAAAAAAAAAAAAAAEAAAAAAAwAAAIAAAAAAAAAAAA= + + + + + + Impl\RepeatableOption.cs + IAAAAAAAAAAAAAAAAAEAAAwAAAAIAAAAAAAAAAAAAAA= + + \ No newline at end of file diff --git a/Rhino.Mocks/Diagrams/Constraints.cd b/Rhino.Mocks/Diagrams/Constraints.cd index 93d33ba2..f6e481ff 100644 --- a/Rhino.Mocks/Diagrams/Constraints.cd +++ b/Rhino.Mocks/Diagrams/Constraints.cd @@ -1,186 +1,186 @@ - - - - - - AAAAAAAAIAAAAAAAABACAAAAAAAAAJAAAABAIAAAAAA= - Constraints\AbstractConstraint.cs - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - Constraints\Constraints.cs - - - - - - CAAAAAAAIAAAAAAAAAAAAAAAAgAAIAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - Constraints\Constraints.cs - - - - - - CEAAAAAAIAAAAAAAAAAAAAAAAAAAIAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAAAAAAAAAABAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIACAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAQAAAIAAAAABAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAgAAAAAAAAAAAAAAAAAAAAAAAAAIAgAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAgAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAEAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAEAAAAAIAAAAAAAAAAgAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAEAAAAAIAAAAAAAAACAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAgAAAAIAAAAEAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAQAAAAAAAAAEAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAIAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIACAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= - Constraints\Constraints.cs - - - - - - AAAAAAAAIAAAAAAAAAAEAAAAAIAAAAQAAAAAIAAAAAA= - Constraints\Constraints.cs - - - + + + + + + AAAAAAAAIAAAAAAAABACAAAAAAAAAJAAAABAIAAAAAA= + Constraints\AbstractConstraint.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Constraints\Constraints.cs + + + + + + CAAAAAAAIAAAAAAAAAAAAAAAAgAAIAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Constraints\Constraints.cs + + + + + + CEAAAAAAIAAAAAAAAAAAAAAAAAAAIAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAAAAAAAAAABAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIACAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAQAAAIAAAAABAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAgAAAAAAAAAAAAAAAAAAAAAAAAAIAgAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAEAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAgAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAEAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAEAAAAAIAAAAAAAAAAgAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAEAAAAAIAAAAAAAAACAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAgAAAAIAAAAEAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAABAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAABAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAQAAAAAAAAAEAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAIAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAACIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIACAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + Constraints\Constraints.cs + + + + + + AAAAAAAAIAAAAAAAAAAEAAAAAIAAAAQAAAAAIAAAAAA= + Constraints\Constraints.cs + + + \ No newline at end of file diff --git a/Rhino.Mocks/Diagrams/Expectations.cd b/Rhino.Mocks/Diagrams/Expectations.cd index e0a5277f..9223bfc3 100644 --- a/Rhino.Mocks/Diagrams/Expectations.cd +++ b/Rhino.Mocks/Diagrams/Expectations.cd @@ -1,47 +1,47 @@ - - - - - - AQAAAAAAAIAAAAAAgAAAAAAAAAAAAKAAAAAQAAAAAEA= - Expectations\ConstraintsExpectation.cs - - - - - - BQAABAAYAoYgCLBAgAAoQCAEAgIAAIAAIABQPBQCJDQ= - Expectations\AbstractExpectation.cs - - - - - - - AQAAAAAAAIAAAAAAgAAAAAAAAIAAAIAAAAAAAAAAAAA= - Expectations\AnyArgsExpectation.cs - - - - - - AQAAAAAAAIAAAAAAgAAAAAAAAAAAEIAgAAAAIAAAAAA= - Expectations\ArgsEqualExpectation.cs - - - - - - AQBAAAAAAIAAAAAAgAAAAAAAAAAAAIAAAEAAAAAAAAA= - Expectations\CallbackExpectation.cs - - - - - - AQAABAAYAAIAAABAAAAoAAAEAgAAAAAAIABALAQCABA= - Interfaces\IExpectation.cs - - - + + + + + + AQAAAAAAAIAAAAAAgAAAAAAAAAAAAKAAAAAQAAAAAEA= + Expectations\ConstraintsExpectation.cs + + + + + + BQAABAAYAoYgCLBAgAAoQCAEAgIAAIAAIABQPBQCJDQ= + Expectations\AbstractExpectation.cs + + + + + + + AQAAAAAAAIAAAAAAgAAAAAAAAIAAAIAAAAAAAAAAAAA= + Expectations\AnyArgsExpectation.cs + + + + + + AQAAAAAAAIAAAAAAgAAAAAAAAAAAEIAgAAAAIAAAAAA= + Expectations\ArgsEqualExpectation.cs + + + + + + AQBAAAAAAIAAAAAAgAAAAAAAAAAAAIAAAEAAAAAAAAA= + Expectations\CallbackExpectation.cs + + + + + + AQAABAAYAAIAAABAAAAoAAAEAgAAAAAAIABALAQCABA= + Interfaces\IExpectation.cs + + + \ No newline at end of file diff --git a/Rhino.Mocks/Diagrams/MethodRecorders.cd b/Rhino.Mocks/Diagrams/MethodRecorders.cd index 795287cd..a7c9ba49 100644 --- a/Rhino.Mocks/Diagrams/MethodRecorders.cd +++ b/Rhino.Mocks/Diagrams/MethodRecorders.cd @@ -1,33 +1,33 @@ - - - - - - EACIEAIIAAAAAoMAACAIEAQCEgQGAAkBFACIEAgAJQA= - MethodRecorders\MethodRecorderBase.cs - - - - - - - AACIAQAAEAAAAAAAAAAIBAQAEAAEAAABAACIEAgAAAA= - MethodRecorders\UnorderedMethodRecorder.cs - - - - - - AAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAAAACAAAAAAAA= - MethodRecorders\OrderedMethodRecorder.cs - - - - - - EAAAEAIIAAAAAAEAACAAEAACEgQAAAEBBACAAAAABQA= - Interfaces\IMethodRecorder.cs - - - + + + + + + EACIEAIIAAAAAoMAACAIEAQCEgQGAAkBFACIEAgAJQA= + MethodRecorders\MethodRecorderBase.cs + + + + + + + AACIAQAAEAAAAAAAAAAIBAQAEAAEAAABAACIEAgAAAA= + MethodRecorders\UnorderedMethodRecorder.cs + + + + + + AAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAAAACAAAAAAAA= + MethodRecorders\OrderedMethodRecorder.cs + + + + + + EAAAEAIIAAAAAAEAACAAEAACEgQAAAEBBACAAAAABQA= + Interfaces\IMethodRecorder.cs + + + \ No newline at end of file diff --git a/Rhino.Mocks/Diagrams/MockStates.cd b/Rhino.Mocks/Diagrams/MockStates.cd index 006b34d8..dd016027 100644 --- a/Rhino.Mocks/Diagrams/MockStates.cd +++ b/Rhino.Mocks/Diagrams/MockStates.cd @@ -1,77 +1,77 @@ - - - - - - AhAAAAIAKAADgQAAhEAAQAAQAEAwAAAAMQAAAgAAEQQ= - Impl\RecordMockState.cs - - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAEAA= - Impl\ReplayDynamicMockState.cs - - - - - - AAAEAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAQ= - Impl\StubRecordMockState.cs - - - - - - AAAAAAAAAAAAAQAAAAAAAAAAAAEAAAAAAAAAAAAAEQA= - Impl\StubReplayMockState.cs - - - - - - AAAAAAAAIAAAAQAAgAIAAAAAAAAgBAAAIQAAAgAAEQA= - Impl\VerifiedMockState.cs - - - - - - - AAAAAAACIAACAQgAgAAAAAAAAAEgAAAAIQIAAgAAEQA= - Impl\ReplayMockState.cs - - - - - - - AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAEAA= - Impl\RecordPartialMockState.cs - - - - - - AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAEAQ= - Impl\RecordDynamicMockState.cs - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAEAA= - Impl\ReplayPartialMockState.cs - - - - - - AAAAAAAAIAAAAQAAgAAAAAAAAAAgAAAAIQAAAgAAEQA= - Interfaces\IMockState.cs - - - + + + + + + AhAAAAIAKAADgQAAhEAAQAAQAEAwAAAAMQAAAgAAEQQ= + Impl\RecordMockState.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAEAA= + Impl\ReplayDynamicMockState.cs + + + + + + AAAEAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAQ= + Impl\StubRecordMockState.cs + + + + + + AAAAAAAAAAAAAQAAAAAAAAAAAAEAAAAAAAAAAAAAEQA= + Impl\StubReplayMockState.cs + + + + + + AAAAAAAAIAAAAQAAgAIAAAAAAAAgBAAAIQAAAgAAEQA= + Impl\VerifiedMockState.cs + + + + + + + AAAAAAACIAACAQgAgAAAAAAAAAEgAAAAIQIAAgAAEQA= + Impl\ReplayMockState.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAEAA= + Impl\RecordPartialMockState.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAEAQ= + Impl\RecordDynamicMockState.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAEAA= + Impl\ReplayPartialMockState.cs + + + + + + AAAAAAAAIAAAAQAAgAAAAAAAAAAgAAAAIQAAAgAAEQA= + Interfaces\IMockState.cs + + + \ No newline at end of file diff --git a/Rhino.Mocks/DoNotExpect.cs b/Rhino.Mocks/DoNotExpect.cs index f3ad8bf3..f027a1cc 100644 --- a/Rhino.Mocks/DoNotExpect.cs +++ b/Rhino.Mocks/DoNotExpect.cs @@ -1,68 +1,68 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; - -namespace Rhino.Mocks -{ - /// - /// 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. - /// - public static class DoNotExpect - { - /// - /// Sets LastCall.Repeat.Never() on /any/ proxy on /any/ repository on the current thread. - /// This method if not safe for multi threading scenarios. - /// - public static void Call(object ignored) - { - LastCall.Repeat.Never(); - } - - /// - /// 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(); }); - /// ... - /// - public static void Call(Expect.Action actionToExecute) - { - if (actionToExecute == null) - throw new ArgumentNullException("actionToExecute", "The action to execute cannot be null"); - actionToExecute(); - LastCall.Repeat.Never(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; + +namespace Rhino.Mocks +{ + /// + /// 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. + /// + public static class DoNotExpect + { + /// + /// Sets LastCall.Repeat.Never() on /any/ proxy on /any/ repository on the current thread. + /// This method if not safe for multi threading scenarios. + /// + public static void Call(object ignored) + { + LastCall.Repeat.Never(); + } + + /// + /// 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(); }); + /// ... + /// + public static void Call(Expect.Action actionToExecute) + { + if (actionToExecute == null) + throw new ArgumentNullException("actionToExecute", "The action to execute cannot be null"); + actionToExecute(); + LastCall.Repeat.Never(); + } + } +} diff --git a/Rhino.Mocks/Exceptions/ExpectationViolationException.cs b/Rhino.Mocks/Exceptions/ExpectationViolationException.cs index a50dc215..3c06ba8a 100644 --- a/Rhino.Mocks/Exceptions/ExpectationViolationException.cs +++ b/Rhino.Mocks/Exceptions/ExpectationViolationException.cs @@ -1,64 +1,64 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Runtime.Serialization; - -namespace Rhino.Mocks.Exceptions -{ - /* - * Class: ExpectationViolationException - * This exception is thrown when there is a an expectation violation. - */ - /// - /// An expectaton violation was detected. - /// - [Serializable()] - public class ExpectationViolationException : Exception - { - #region Constructors - - /// - /// Creates a new instance. - /// - /// Message. - public ExpectationViolationException(string message) : base(message) - { - } - - - /// - /// Serialization constructor - /// - protected ExpectationViolationException(SerializationInfo info, StreamingContext context) - :base(info,context){} - - #endregion - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Runtime.Serialization; + +namespace Rhino.Mocks.Exceptions +{ + /* + * Class: ExpectationViolationException + * This exception is thrown when there is a an expectation violation. + */ + /// + /// An expectaton violation was detected. + /// + [Serializable()] + public class ExpectationViolationException : Exception + { + #region Constructors + + /// + /// Creates a new instance. + /// + /// Message. + public ExpectationViolationException(string message) : base(message) + { + } + + + /// + /// Serialization constructor + /// + protected ExpectationViolationException(SerializationInfo info, StreamingContext context) + :base(info,context){} + + #endregion + } } \ No newline at end of file diff --git a/Rhino.Mocks/Exceptions/ObjectNotMockFromThisRepositoryException.cs b/Rhino.Mocks/Exceptions/ObjectNotMockFromThisRepositoryException.cs index b9d945bc..3339f015 100644 --- a/Rhino.Mocks/Exceptions/ObjectNotMockFromThisRepositoryException.cs +++ b/Rhino.Mocks/Exceptions/ObjectNotMockFromThisRepositoryException.cs @@ -1,65 +1,65 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Runtime.Serialization; - -namespace Rhino.Mocks.Exceptions -{ - /* - * Class: ObjectNotMockFromThisRepositoryException - * Signals that an object was call on a mock repository which doesn't - * belong to this mock repository or not a mock - */ - /// - /// Signals that an object was call on a mock repository which doesn't - /// belong to this mock repository or not a mock - /// - [Serializable()] - public class ObjectNotMockFromThisRepositoryException : Exception - { - #region Constructors - - /// - /// Creates a new instance. - /// - /// Message. - public ObjectNotMockFromThisRepositoryException(string message) : base(message) - { - } - - /// - /// Serialization constructor - /// - protected ObjectNotMockFromThisRepositoryException(SerializationInfo info, StreamingContext context) - :base(info,context){} - - #endregion - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Runtime.Serialization; + +namespace Rhino.Mocks.Exceptions +{ + /* + * Class: ObjectNotMockFromThisRepositoryException + * Signals that an object was call on a mock repository which doesn't + * belong to this mock repository or not a mock + */ + /// + /// Signals that an object was call on a mock repository which doesn't + /// belong to this mock repository or not a mock + /// + [Serializable()] + public class ObjectNotMockFromThisRepositoryException : Exception + { + #region Constructors + + /// + /// Creates a new instance. + /// + /// Message. + public ObjectNotMockFromThisRepositoryException(string message) : base(message) + { + } + + /// + /// Serialization constructor + /// + protected ObjectNotMockFromThisRepositoryException(SerializationInfo info, StreamingContext context) + :base(info,context){} + + #endregion + } +} diff --git a/Rhino.Mocks/Expect.cs b/Rhino.Mocks/Expect.cs index d9eda332..64a1476b 100644 --- a/Rhino.Mocks/Expect.cs +++ b/Rhino.Mocks/Expect.cs @@ -1,120 +1,120 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks -{ - /* - * class: Expect - * Allows to set expectation on methods that has return values. - * - * note: - * For methods with void return value, you need to use - */ - /// - /// Allows to set expectation on methods that has return values. - /// For methods with void return value, you need to use LastCall - /// - public static class Expect - { - /// - ///A delegate that can be used to get better syntax on Expect.Call(delegate { foo.DoSomething(); }); - /// - public delegate void Action(); - - /* - * Method: Call - * Get the method options for the last method call, which usually will be a method call - * or property that is located inside the . - * See Expected Usage. - * - * Expected usage: - * (start code) - * Expect.Call(mockObject.SomeCall()).Return(new Something()); - * Expect.Call(mockList.Count).Return(50); - * (end) - * - * Thread safety: - * This method is *not* safe for multi threading scenarios! - * If you need to record in a multi threading environment, use the method, which _can_ - * handle multi threading scenarios. - */ - /// - /// 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 . - /// - public static IMethodOptions Call(T ignored) - { - return LastCall.GetOptions(); - } - - /// - /// 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()); - /// ... - /// - public static IMethodOptions Call(Action actionToExecute) - { - if (actionToExecute == null) - throw new ArgumentNullException("actionToExecute", "The action to execute cannot be null"); - actionToExecute(); - return LastCall.GetOptions(); - } - - /* - * Method: On - * Get the method options for the last method call on the mockInstance. - * Unless you're recording in multiply threads, you are probably better off - * using - * - * Expected usage: - * Expect.On(mockList).Call(mockList.Count).Return(50); - * - * Thread safety: - * This method can be used in mutli threading scenarios. - */ - /// - /// Get the method options for the last method call on the mockInstance. - /// - public static ICreateMethodExpectation On(object mockedInstace) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mockedInstace); - return new CreateMethodExpectation(mockedObject, mockedInstace); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks +{ + /* + * class: Expect + * Allows to set expectation on methods that has return values. + * + * note: + * For methods with void return value, you need to use + */ + /// + /// Allows to set expectation on methods that has return values. + /// For methods with void return value, you need to use LastCall + /// + public static class Expect + { + /// + ///A delegate that can be used to get better syntax on Expect.Call(delegate { foo.DoSomething(); }); + /// + public delegate void Action(); + + /* + * Method: Call + * Get the method options for the last method call, which usually will be a method call + * or property that is located inside the . + * See Expected Usage. + * + * Expected usage: + * (start code) + * Expect.Call(mockObject.SomeCall()).Return(new Something()); + * Expect.Call(mockList.Count).Return(50); + * (end) + * + * Thread safety: + * This method is *not* safe for multi threading scenarios! + * If you need to record in a multi threading environment, use the method, which _can_ + * handle multi threading scenarios. + */ + /// + /// 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 . + /// + public static IMethodOptions Call(T ignored) + { + return LastCall.GetOptions(); + } + + /// + /// 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()); + /// ... + /// + public static IMethodOptions Call(Action actionToExecute) + { + if (actionToExecute == null) + throw new ArgumentNullException("actionToExecute", "The action to execute cannot be null"); + actionToExecute(); + return LastCall.GetOptions(); + } + + /* + * Method: On + * Get the method options for the last method call on the mockInstance. + * Unless you're recording in multiply threads, you are probably better off + * using + * + * Expected usage: + * Expect.On(mockList).Call(mockList.Count).Return(50); + * + * Thread safety: + * This method can be used in mutli threading scenarios. + */ + /// + /// Get the method options for the last method call on the mockInstance. + /// + public static ICreateMethodExpectation On(object mockedInstace) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mockedInstace); + return new CreateMethodExpectation(mockedObject, mockedInstace); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/ExpectationVerificationInformation.cs b/Rhino.Mocks/ExpectationVerificationInformation.cs index 24a16bb7..fc4e42d0 100644 --- a/Rhino.Mocks/ExpectationVerificationInformation.cs +++ b/Rhino.Mocks/ExpectationVerificationInformation.cs @@ -1,15 +1,15 @@ -using System.Collections.Generic; -using Rhino.Mocks.Generated; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks -{ - internal class ExpectationVerificationInformation - { - private IExpectation expected; - private IList argumentsForAllCalls; - - public IExpectation Expected { get { return expected; } set { expected = value; } } - public IList ArgumentsForAllCalls { get { return argumentsForAllCalls; } set { argumentsForAllCalls = value; } } - } -} +using System.Collections.Generic; +using Rhino.Mocks.Generated; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks +{ + internal class ExpectationVerificationInformation + { + private IExpectation expected; + private IList argumentsForAllCalls; + + public IExpectation Expected { get { return expected; } set { expected = value; } } + public IList ArgumentsForAllCalls { get { return argumentsForAllCalls; } set { argumentsForAllCalls = value; } } + } +} diff --git a/Rhino.Mocks/Expectations/AbstractExpectation.cs b/Rhino.Mocks/Expectations/AbstractExpectation.cs index a4e9416f..df6b9bd0 100644 --- a/Rhino.Mocks/Expectations/AbstractExpectation.cs +++ b/Rhino.Mocks/Expectations/AbstractExpectation.cs @@ -1,573 +1,573 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Expectations -{ - /// - /// Abstract class that holds common information for - /// expectations. - /// - public abstract class AbstractExpectation : IExpectation - { - #region Variables - - /// - /// Number of actuall calls made that passed this expectation - /// - private int actualCallsCount; - - /// - /// Range of expected calls that should pass this expectation. - /// - private Range expected; - - /// - /// The return value for a method matching this expectation - /// - private object returnValue; - - /// - /// The exception to throw on a method matching this expectation. - /// - private Exception exceptionToThrow; - - /// - /// The method this expectation is for. - /// - private MethodInfo method; - - /// - /// The return value for this method was set - /// - private bool returnValueSet; - - /// - /// Whether this method will repeat - /// unlimited number of times. - /// - private RepeatableOption repeatableOption = RepeatableOption.Normal; - - /// - /// A delegate that will be run when the - /// expectation is matched. - /// - private Delegate actionToExecute; - - /// - /// The arguments that matched this expectation. - /// - private object[] matchingArgs; - - private object[] outRefParams; - - /// - /// Documentation message - /// - private string message; - - /// - /// The method originalInvocation - /// - private readonly IInvocation originalInvocation; - - private bool allowTentativeReturn = false; - - #endregion - - #region Properties - - /// - /// Setter for the outpur / ref parameters for this expecataion. - /// Can only be set once. - /// - public object[] OutRefParams - { - get - { - return outRefParams; - } - set - { - if (outRefParams != null) - throw new InvalidOperationException( - "Output and ref parameters has already been set for this expectation"); - outRefParams = value; - } - } - - /// - /// Specify whether this expectation has a return value set - /// You can't check ReturnValue for this because a valid return value include null. - /// - public bool HasReturnValue - { - get { return returnValueSet; } - } - - /// - /// Gets the method this expectation is for. - /// - public MethodInfo Method - { - get { return method; } - } - - - /// - /// Gets the originalInvocation for this expectation - /// - /// The originalInvocation. - public IInvocation Originalinvocation - { - get { return originalInvocation; } - } - - /// - /// Gets or sets what special condtions there are for this method - /// - public RepeatableOption RepeatableOption - { - get { return repeatableOption; } - set { repeatableOption = value; } - } - - /// - /// Range of expected calls - /// - public Range Expected - { - get { return expected; } - set { expected = value; } - } - - /// - /// Number of call actually made for this method - /// - public int ActualCallsCount - { - get { return actualCallsCount; } - } - - /// - /// If this expectation is still waiting for calls. - /// - public bool CanAcceptCalls - { - get - { - //I don't bother to check for RepeatableOption.Never because - //this is handled the method recorder - if (repeatableOption == RepeatableOption.Any) - return true; - return expected.Max == null || actualCallsCount < expected.Max.Value; - } - } - - /// - /// Gets a value indicating whether this expectation was satisfied - /// - public bool ExpectationSatisfied - { - get - { - if (repeatableOption != RepeatableOption.Normal && repeatableOption != RepeatableOption.OriginalCall) - return true; - if(expected.Min > actualCallsCount ) - return false; - if(Expected.Max==null) - return true; - return actualCallsCount <= expected.Max.Value; - } - } - - - /// - /// The return value for a method matching this expectation - /// - public object ReturnValue - { - get { return returnValue; } - set - { - ActionOnMethodNotSpesified(); - AssertTypesMatches(value); - returnValueSet = true; - returnValue = value; - } - } - - /// - /// An action to execute when the method is matched. - /// - public Delegate ActionToExecute - { - get { return actionToExecute; } - set - { - ActionOnMethodNotSpesified(); - AssertReturnTypeMatch(value); - AssertDelegateArgumentsMatchMethod(value); - actionToExecute = value; - } - } - - /// - /// Gets or sets the exception to throw on a method matching this expectation. - /// - public Exception ExceptionToThrow - { - get { return exceptionToThrow; } - set - { - ActionOnMethodNotSpesified(); - exceptionToThrow = value; - } - } - - /// - /// 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. - /// - public bool ActionsSatisfied - { - get - { - if (method.ReturnType == typeof(void) || - exceptionToThrow != null || - actionToExecute != null || - returnValueSet || - allowTentativeReturn || - repeatableOption == RepeatableOption.OriginalCall || - repeatableOption == RepeatableOption.OriginalCallBypassingMocking || - repeatableOption == RepeatableOption.PropertyBehavior) - return true; - return false; - } - } - - /// - /// Documentation message - /// - public string Message - { - get { return message; } - set { message = value; } - } - - #endregion - - #region Public Methods - - /// - /// Get the hash code - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - - /// - /// Add an actual actualMethodCall call to this expectation - /// - public void AddActualCall() - { - actualCallsCount++; - } - - /// - /// Builds the verification failure message. - /// - /// - public string BuildVerificationFailureMessage() - { - StringBuilder sb = new StringBuilder(); - string expectationMessege = ErrorMessage; - sb.Append(expectationMessege).Append(' '); - sb.Append("Expected #"); - sb.Append(Expected.ToString()).Append(", "); - sb.Append("Actual #").Append(ActualCallsCount).Append('.'); - return sb.ToString(); - } - - /// - /// Occurs when the exceptation is match on a method call - /// - public event Action WhenCalled =delegate { }; - - /// - /// Returns the return value or throw the exception and setup output / ref parameters - /// - public object ReturnOrThrow(IInvocation invocation, object[] args) - { - allowTentativeReturn = false; - - if (ActionsSatisfied == false) - throw new InvalidOperationException("Method '" + ErrorMessage + "' requires a return value or an exception to throw."); - - SetupOutputAndRefParameters(args); - if (actionToExecute != null) - { - object action = ExecuteAction(); - WhenCalled(new MethodInvocation(invocation)); - return action; - } - if (exceptionToThrow != null) - throw exceptionToThrow; - if (RepeatableOption == RepeatableOption.OriginalCall) - { - invocation.Proceed(); - WhenCalled(new MethodInvocation(invocation)); - return invocation.ReturnValue; - } - invocation.ReturnValue = returnValue; - WhenCalled(new MethodInvocation(invocation)); - return invocation.ReturnValue; - } - - /// - /// Validate the arguments for the method on the child methods - /// - /// The arguments with which the method was called - public bool IsExpected(object[] args) - { - if (DoIsExpected(args)) - { - matchingArgs = args; - return true; - } - matchingArgs = null; - return false; - } - - - #endregion - - #region C'tor - - /// - /// Creates a new instance. - /// - /// The originalInvocation for this method, required because it contains the generic type infromation - /// Number of method calls for this expectations - protected AbstractExpectation(IInvocation invocation, Range expectedRange) - { - Validate.IsNotNull(invocation, "originalInvocation"); - Validate.IsNotNull(invocation.Method, "method"); - this.originalInvocation = invocation; - this.method = invocation.Method; - this.expected = expectedRange; - } - - /// - /// Creates a new instance. - /// - /// Expectation. - protected AbstractExpectation(IExpectation expectation) - : this(expectation.Originalinvocation, new Range(1, 1)) - { - returnValue = expectation.ReturnValue; - returnValueSet = expectation.HasReturnValue; - expected = expectation.Expected; - actualCallsCount = expectation.ActualCallsCount; - repeatableOption = expectation.RepeatableOption; - exceptionToThrow = expectation.ExceptionToThrow; - message = expectation.Message; - actionToExecute = expectation.ActionToExecute; - outRefParams = expectation.OutRefParams; - allowTentativeReturn = expectation.AllowTentativeReturn; - } - - /// - /// Allow to set the return value in the future, if it was already set. - /// - public bool AllowTentativeReturn - { - get { return allowTentativeReturn; } - set { allowTentativeReturn = value; } - } - - #endregion - - #region Abstract Methods - - /// - /// Validate the arguments for the method on the child methods - /// - /// The arguments with which the method was called - protected abstract bool DoIsExpected(object[] args); - - /// - /// Gets the error message. - /// - /// - public abstract string ErrorMessage { get; } - - /// - /// Determines if this object equal to obj - /// - public abstract override bool Equals(object obj); - - #endregion - - #region Protected Methods - - /// - /// The error message for these arguments - /// - protected string CreateErrorMessage(string derivedMessage) - { - if (Message == null) - return derivedMessage; - string msg = string.Format("Message: {0}\n{1}", Message, derivedMessage); - return msg; - } - - #endregion - - #region Implementation - - private void SetupOutputAndRefParameters(object[] args) - { - if (outRefParams == null) - return; - int argIndex = 0, outputArgIndex = 0; - ParameterInfo[] parameters = method.GetParameters(); - foreach (ParameterInfo info in parameters) - { - if (outputArgIndex >= outRefParams.Length) - return; - - if (info.IsOut || info.ParameterType.IsByRef) - { - args[argIndex] = outRefParams[outputArgIndex]; - outputArgIndex += 1; - } - argIndex++; - } - } - - private void ActionOnMethodNotSpesified() - { - if(allowTentativeReturn) - return; - if (returnValueSet == false && exceptionToThrow == null && actionToExecute == null) - return; - if (this.Expected != null && this.Expected.Max == 0)// we have choosen Repeat.Never - { - throw new InvalidOperationException( - "After specifying Repeat.Never(), you cannot specify a return value, exception to throw or an action to execute"); - } - throw new InvalidOperationException("Can set only a single return value or exception to throw or delegate to execute on the same method call."); - } - - private object ExecuteAction() - { - try - { - if (matchingArgs == null) - throw new InvalidOperationException("Trying to run a Do() delegate when no arguments were matched to the expectation."); - try - { - return actionToExecute.DynamicInvoke(matchingArgs); - } - catch (TargetInvocationException e) - { - throw e.InnerException; - } - } - finally - { - matchingArgs = null; - } - } - - private void AssertTypesMatches(object value) - { - string type = null; - Type returnType = method.ReturnType; - if (value == null) - { - type = "null"; - if (returnType.IsValueType == false) - return; - if (returnType.IsGenericType && - returnType.GetGenericTypeDefinition() == typeof(Nullable<>)) - return; - } - else - { - //we reduce checking of generic types because of the complexity, - //we let the runtime catch those mistakes - returnType = GenericsUtil.GetRealType(returnType, originalInvocation); - Type valueType = value.GetType(); - if (returnType.IsInstanceOfType(value)) - return; - type = valueType.FullName; - } - throw new InvalidOperationException(string.Format("Type '{0}' doesn't match the return type '{1}' for method '{2}'", type, returnType, - MethodCallUtil.StringPresentation(Originalinvocation, method, new object[0]))); - } - - /// - /// Asserts that the delegate has the same parameters as the expectation's method call - /// - protected void AssertDelegateArgumentsMatchMethod(Delegate callback) - { - ParameterInfo[] callbackParams = callback.Method.GetParameters(), - methodParams = method.GetParameters(); - string argsDontMatch = "Callback arguments didn't match the method arguments"; - if (callbackParams.Length != methodParams.Length) - throw new InvalidOperationException(argsDontMatch); - for (int i = 0; i < methodParams.Length; i++) - { - Type methodParameter = GenericsUtil.GetRealType(methodParams[i].ParameterType, Originalinvocation); - if (methodParameter != callbackParams[i].ParameterType) - throw new InvalidOperationException(argsDontMatch); - } - } - private void AssertReturnTypeMatch(Delegate value) - { - if (GenericsUtil.GetRealType(method.ReturnType, Originalinvocation) - .IsAssignableFrom(value.Method.ReturnType) == false) - throw new InvalidOperationException("The delegate return value should be assignable from " + method.ReturnType.FullName); - } - #endregion - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Expectations +{ + /// + /// Abstract class that holds common information for + /// expectations. + /// + public abstract class AbstractExpectation : IExpectation + { + #region Variables + + /// + /// Number of actuall calls made that passed this expectation + /// + private int actualCallsCount; + + /// + /// Range of expected calls that should pass this expectation. + /// + private Range expected; + + /// + /// The return value for a method matching this expectation + /// + private object returnValue; + + /// + /// The exception to throw on a method matching this expectation. + /// + private Exception exceptionToThrow; + + /// + /// The method this expectation is for. + /// + private MethodInfo method; + + /// + /// The return value for this method was set + /// + private bool returnValueSet; + + /// + /// Whether this method will repeat + /// unlimited number of times. + /// + private RepeatableOption repeatableOption = RepeatableOption.Normal; + + /// + /// A delegate that will be run when the + /// expectation is matched. + /// + private Delegate actionToExecute; + + /// + /// The arguments that matched this expectation. + /// + private object[] matchingArgs; + + private object[] outRefParams; + + /// + /// Documentation message + /// + private string message; + + /// + /// The method originalInvocation + /// + private readonly IInvocation originalInvocation; + + private bool allowTentativeReturn = false; + + #endregion + + #region Properties + + /// + /// Setter for the outpur / ref parameters for this expecataion. + /// Can only be set once. + /// + public object[] OutRefParams + { + get + { + return outRefParams; + } + set + { + if (outRefParams != null) + throw new InvalidOperationException( + "Output and ref parameters has already been set for this expectation"); + outRefParams = value; + } + } + + /// + /// Specify whether this expectation has a return value set + /// You can't check ReturnValue for this because a valid return value include null. + /// + public bool HasReturnValue + { + get { return returnValueSet; } + } + + /// + /// Gets the method this expectation is for. + /// + public MethodInfo Method + { + get { return method; } + } + + + /// + /// Gets the originalInvocation for this expectation + /// + /// The originalInvocation. + public IInvocation Originalinvocation + { + get { return originalInvocation; } + } + + /// + /// Gets or sets what special condtions there are for this method + /// + public RepeatableOption RepeatableOption + { + get { return repeatableOption; } + set { repeatableOption = value; } + } + + /// + /// Range of expected calls + /// + public Range Expected + { + get { return expected; } + set { expected = value; } + } + + /// + /// Number of call actually made for this method + /// + public int ActualCallsCount + { + get { return actualCallsCount; } + } + + /// + /// If this expectation is still waiting for calls. + /// + public bool CanAcceptCalls + { + get + { + //I don't bother to check for RepeatableOption.Never because + //this is handled the method recorder + if (repeatableOption == RepeatableOption.Any) + return true; + return expected.Max == null || actualCallsCount < expected.Max.Value; + } + } + + /// + /// Gets a value indicating whether this expectation was satisfied + /// + public bool ExpectationSatisfied + { + get + { + if (repeatableOption != RepeatableOption.Normal && repeatableOption != RepeatableOption.OriginalCall) + return true; + if(expected.Min > actualCallsCount ) + return false; + if(Expected.Max==null) + return true; + return actualCallsCount <= expected.Max.Value; + } + } + + + /// + /// The return value for a method matching this expectation + /// + public object ReturnValue + { + get { return returnValue; } + set + { + ActionOnMethodNotSpesified(); + AssertTypesMatches(value); + returnValueSet = true; + returnValue = value; + } + } + + /// + /// An action to execute when the method is matched. + /// + public Delegate ActionToExecute + { + get { return actionToExecute; } + set + { + ActionOnMethodNotSpesified(); + AssertReturnTypeMatch(value); + AssertDelegateArgumentsMatchMethod(value); + actionToExecute = value; + } + } + + /// + /// Gets or sets the exception to throw on a method matching this expectation. + /// + public Exception ExceptionToThrow + { + get { return exceptionToThrow; } + set + { + ActionOnMethodNotSpesified(); + exceptionToThrow = value; + } + } + + /// + /// 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. + /// + public bool ActionsSatisfied + { + get + { + if (method.ReturnType == typeof(void) || + exceptionToThrow != null || + actionToExecute != null || + returnValueSet || + allowTentativeReturn || + repeatableOption == RepeatableOption.OriginalCall || + repeatableOption == RepeatableOption.OriginalCallBypassingMocking || + repeatableOption == RepeatableOption.PropertyBehavior) + return true; + return false; + } + } + + /// + /// Documentation message + /// + public string Message + { + get { return message; } + set { message = value; } + } + + #endregion + + #region Public Methods + + /// + /// Get the hash code + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + + /// + /// Add an actual actualMethodCall call to this expectation + /// + public void AddActualCall() + { + actualCallsCount++; + } + + /// + /// Builds the verification failure message. + /// + /// + public string BuildVerificationFailureMessage() + { + StringBuilder sb = new StringBuilder(); + string expectationMessege = ErrorMessage; + sb.Append(expectationMessege).Append(' '); + sb.Append("Expected #"); + sb.Append(Expected.ToString()).Append(", "); + sb.Append("Actual #").Append(ActualCallsCount).Append('.'); + return sb.ToString(); + } + + /// + /// Occurs when the exceptation is match on a method call + /// + public event Action WhenCalled =delegate { }; + + /// + /// Returns the return value or throw the exception and setup output / ref parameters + /// + public object ReturnOrThrow(IInvocation invocation, object[] args) + { + allowTentativeReturn = false; + + if (ActionsSatisfied == false) + throw new InvalidOperationException("Method '" + ErrorMessage + "' requires a return value or an exception to throw."); + + SetupOutputAndRefParameters(args); + if (actionToExecute != null) + { + object action = ExecuteAction(); + WhenCalled(new MethodInvocation(invocation)); + return action; + } + if (exceptionToThrow != null) + throw exceptionToThrow; + if (RepeatableOption == RepeatableOption.OriginalCall) + { + invocation.Proceed(); + WhenCalled(new MethodInvocation(invocation)); + return invocation.ReturnValue; + } + invocation.ReturnValue = returnValue; + WhenCalled(new MethodInvocation(invocation)); + return invocation.ReturnValue; + } + + /// + /// Validate the arguments for the method on the child methods + /// + /// The arguments with which the method was called + public bool IsExpected(object[] args) + { + if (DoIsExpected(args)) + { + matchingArgs = args; + return true; + } + matchingArgs = null; + return false; + } + + + #endregion + + #region C'tor + + /// + /// Creates a new instance. + /// + /// The originalInvocation for this method, required because it contains the generic type infromation + /// Number of method calls for this expectations + protected AbstractExpectation(IInvocation invocation, Range expectedRange) + { + Validate.IsNotNull(invocation, "originalInvocation"); + Validate.IsNotNull(invocation.Method, "method"); + this.originalInvocation = invocation; + this.method = invocation.Method; + this.expected = expectedRange; + } + + /// + /// Creates a new instance. + /// + /// Expectation. + protected AbstractExpectation(IExpectation expectation) + : this(expectation.Originalinvocation, new Range(1, 1)) + { + returnValue = expectation.ReturnValue; + returnValueSet = expectation.HasReturnValue; + expected = expectation.Expected; + actualCallsCount = expectation.ActualCallsCount; + repeatableOption = expectation.RepeatableOption; + exceptionToThrow = expectation.ExceptionToThrow; + message = expectation.Message; + actionToExecute = expectation.ActionToExecute; + outRefParams = expectation.OutRefParams; + allowTentativeReturn = expectation.AllowTentativeReturn; + } + + /// + /// Allow to set the return value in the future, if it was already set. + /// + public bool AllowTentativeReturn + { + get { return allowTentativeReturn; } + set { allowTentativeReturn = value; } + } + + #endregion + + #region Abstract Methods + + /// + /// Validate the arguments for the method on the child methods + /// + /// The arguments with which the method was called + protected abstract bool DoIsExpected(object[] args); + + /// + /// Gets the error message. + /// + /// + public abstract string ErrorMessage { get; } + + /// + /// Determines if this object equal to obj + /// + public abstract override bool Equals(object obj); + + #endregion + + #region Protected Methods + + /// + /// The error message for these arguments + /// + protected string CreateErrorMessage(string derivedMessage) + { + if (Message == null) + return derivedMessage; + string msg = string.Format("Message: {0}\n{1}", Message, derivedMessage); + return msg; + } + + #endregion + + #region Implementation + + private void SetupOutputAndRefParameters(object[] args) + { + if (outRefParams == null) + return; + int argIndex = 0, outputArgIndex = 0; + ParameterInfo[] parameters = method.GetParameters(); + foreach (ParameterInfo info in parameters) + { + if (outputArgIndex >= outRefParams.Length) + return; + + if (info.IsOut || info.ParameterType.IsByRef) + { + args[argIndex] = outRefParams[outputArgIndex]; + outputArgIndex += 1; + } + argIndex++; + } + } + + private void ActionOnMethodNotSpesified() + { + if(allowTentativeReturn) + return; + if (returnValueSet == false && exceptionToThrow == null && actionToExecute == null) + return; + if (this.Expected != null && this.Expected.Max == 0)// we have choosen Repeat.Never + { + throw new InvalidOperationException( + "After specifying Repeat.Never(), you cannot specify a return value, exception to throw or an action to execute"); + } + throw new InvalidOperationException("Can set only a single return value or exception to throw or delegate to execute on the same method call."); + } + + private object ExecuteAction() + { + try + { + if (matchingArgs == null) + throw new InvalidOperationException("Trying to run a Do() delegate when no arguments were matched to the expectation."); + try + { + return actionToExecute.DynamicInvoke(matchingArgs); + } + catch (TargetInvocationException e) + { + throw e.InnerException; + } + } + finally + { + matchingArgs = null; + } + } + + private void AssertTypesMatches(object value) + { + string type = null; + Type returnType = method.ReturnType; + if (value == null) + { + type = "null"; + if (returnType.IsValueType == false) + return; + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(Nullable<>)) + return; + } + else + { + //we reduce checking of generic types because of the complexity, + //we let the runtime catch those mistakes + returnType = GenericsUtil.GetRealType(returnType, originalInvocation); + Type valueType = value.GetType(); + if (returnType.IsInstanceOfType(value)) + return; + type = valueType.FullName; + } + throw new InvalidOperationException(string.Format("Type '{0}' doesn't match the return type '{1}' for method '{2}'", type, returnType, + MethodCallUtil.StringPresentation(Originalinvocation, method, new object[0]))); + } + + /// + /// Asserts that the delegate has the same parameters as the expectation's method call + /// + protected void AssertDelegateArgumentsMatchMethod(Delegate callback) + { + ParameterInfo[] callbackParams = callback.Method.GetParameters(), + methodParams = method.GetParameters(); + string argsDontMatch = "Callback arguments didn't match the method arguments"; + if (callbackParams.Length != methodParams.Length) + throw new InvalidOperationException(argsDontMatch); + for (int i = 0; i < methodParams.Length; i++) + { + Type methodParameter = GenericsUtil.GetRealType(methodParams[i].ParameterType, Originalinvocation); + if (methodParameter != callbackParams[i].ParameterType) + throw new InvalidOperationException(argsDontMatch); + } + } + private void AssertReturnTypeMatch(Delegate value) + { + if (GenericsUtil.GetRealType(method.ReturnType, Originalinvocation) + .IsAssignableFrom(value.Method.ReturnType) == false) + throw new InvalidOperationException("The delegate return value should be assignable from " + method.ReturnType.FullName); + } + #endregion + } +} diff --git a/Rhino.Mocks/Expectations/AnyArgsExpectation.cs b/Rhino.Mocks/Expectations/AnyArgsExpectation.cs index da702b7f..2eb3b77a 100644 --- a/Rhino.Mocks/Expectations/AnyArgsExpectation.cs +++ b/Rhino.Mocks/Expectations/AnyArgsExpectation.cs @@ -1,108 +1,108 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Expectations -{ - /// - /// Expectation that matches any arguments for the method. - /// - public class AnyArgsExpectation : AbstractExpectation - { - /// - /// Creates a new instance. - /// - /// Invocation for this expectation - /// Number of method calls for this expectations - public AnyArgsExpectation(IInvocation invocation, Range expectedRange) : base(invocation, expectedRange) - { - } - - /// - /// Creates a new instance. - /// - /// Expectation. - public AnyArgsExpectation(IExpectation expectation) : base(expectation) - { - } - - /// - /// Validate the arguments for the method. - /// - /// The arguments with which the method was called - protected override bool DoIsExpected(object[] args) - { - return true; - } - - /// - /// Gets the error message. - /// - /// - public override string ErrorMessage - { - get - { - MethodCallUtil.FormatArgumnet format = new MethodCallUtil.FormatArgumnet(AnyFormatArg); - string stringPresentation = MethodCallUtil.StringPresentation(Originalinvocation, format, Method, new object[0]); - return CreateErrorMessage(stringPresentation); - } - } - - /// - /// Determines if the object equal to expectation - /// - public override bool Equals(object obj) - { - AnyArgsExpectation other = obj as AnyArgsExpectation; - if (other == null) - return false; - return Method.Equals(other.Method); - } - - /// - /// Get the hash code - /// - public override int GetHashCode() - { - return Method.GetHashCode(); - } - - private static string AnyFormatArg(Array args, int i) - { - return "any"; - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Expectations +{ + /// + /// Expectation that matches any arguments for the method. + /// + public class AnyArgsExpectation : AbstractExpectation + { + /// + /// Creates a new instance. + /// + /// Invocation for this expectation + /// Number of method calls for this expectations + public AnyArgsExpectation(IInvocation invocation, Range expectedRange) : base(invocation, expectedRange) + { + } + + /// + /// Creates a new instance. + /// + /// Expectation. + public AnyArgsExpectation(IExpectation expectation) : base(expectation) + { + } + + /// + /// Validate the arguments for the method. + /// + /// The arguments with which the method was called + protected override bool DoIsExpected(object[] args) + { + return true; + } + + /// + /// Gets the error message. + /// + /// + public override string ErrorMessage + { + get + { + MethodCallUtil.FormatArgumnet format = new MethodCallUtil.FormatArgumnet(AnyFormatArg); + string stringPresentation = MethodCallUtil.StringPresentation(Originalinvocation, format, Method, new object[0]); + return CreateErrorMessage(stringPresentation); + } + } + + /// + /// Determines if the object equal to expectation + /// + public override bool Equals(object obj) + { + AnyArgsExpectation other = obj as AnyArgsExpectation; + if (other == null) + return false; + return Method.Equals(other.Method); + } + + /// + /// Get the hash code + /// + public override int GetHashCode() + { + return Method.GetHashCode(); + } + + private static string AnyFormatArg(Array args, int i) + { + return "any"; + } + } +} diff --git a/Rhino.Mocks/Expectations/ArgsEqualExpectation.cs b/Rhino.Mocks/Expectations/ArgsEqualExpectation.cs index c2baad8d..e7cdce22 100644 --- a/Rhino.Mocks/Expectations/ArgsEqualExpectation.cs +++ b/Rhino.Mocks/Expectations/ArgsEqualExpectation.cs @@ -1,146 +1,146 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Expectations -{ - /// - /// Summary description for ArgsEqualExpectation. - /// - public class ArgsEqualExpectation : AbstractExpectation - { - private readonly object[] expectedArgs; - - /// - /// Creates a new instance. - /// - /// Expected args. - /// The invocation for this expectation - /// Number of method calls for this expectations - public ArgsEqualExpectation(IInvocation invocation, object[] expectedArgs, Range expectedRange) : base(invocation, expectedRange) - { - this.expectedArgs = expectedArgs; - } - - /// - /// Validate the arguments for the method. - /// - /// The arguments with which the method was called - protected override bool DoIsExpected(object[] args) - { - return Validate.ArgsEqual(expectedArgs, args); - } - - /// - /// Gets the error message. - /// - /// - public override string ErrorMessage - { - get - { - MethodCallUtil.FormatArgumnet format = new MethodCallUtil.FormatArgumnet(FormatArg); - string methodCall = MethodCallUtil.StringPresentation(Originalinvocation,format, Method, ExpectedArgs); - return base.CreateErrorMessage(methodCall); - } - } - - /// - /// Get the expected args. - /// - public object[] ExpectedArgs - { - get { return expectedArgs; } - } - - /// - /// Determines if the object equal to expectation - /// - public override bool Equals(object obj) - { - ArgsEqualExpectation other = obj as ArgsEqualExpectation; - if (other == null) - return false; - return Method.Equals(other.Method) && Validate.ArgsEqual(expectedArgs, other.expectedArgs); - } - - /// - /// Get the hash code - /// - public override int GetHashCode() - { - return Method.GetHashCode(); - } - - - private static string FormatArg(Array args, int i) - { - if (args.Length <= i) - return "missing parameter"; - object arg = args.GetValue(i); - if (arg is Array) - { - Array arr = (Array)arg; - StringBuilder sb = new StringBuilder(); - sb.Append('['); - for (int j = 0; j < arr.Length; j++) - { - sb.Append(FormatArg(arr, j)); - if (j < arr.Length - 1) - sb.Append(", "); - } - sb.Append("]"); - return sb.ToString(); - } - else if (arg is string) - { - return '"' + arg.ToString() + '"'; - } - else if (arg == null) - { - return "null"; - } - else if (arg is IMockedObject) - { - return arg.GetType().ToString(); - } - else - { - return arg.ToString(); - } - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Expectations +{ + /// + /// Summary description for ArgsEqualExpectation. + /// + public class ArgsEqualExpectation : AbstractExpectation + { + private readonly object[] expectedArgs; + + /// + /// Creates a new instance. + /// + /// Expected args. + /// The invocation for this expectation + /// Number of method calls for this expectations + public ArgsEqualExpectation(IInvocation invocation, object[] expectedArgs, Range expectedRange) : base(invocation, expectedRange) + { + this.expectedArgs = expectedArgs; + } + + /// + /// Validate the arguments for the method. + /// + /// The arguments with which the method was called + protected override bool DoIsExpected(object[] args) + { + return Validate.ArgsEqual(expectedArgs, args); + } + + /// + /// Gets the error message. + /// + /// + public override string ErrorMessage + { + get + { + MethodCallUtil.FormatArgumnet format = new MethodCallUtil.FormatArgumnet(FormatArg); + string methodCall = MethodCallUtil.StringPresentation(Originalinvocation,format, Method, ExpectedArgs); + return base.CreateErrorMessage(methodCall); + } + } + + /// + /// Get the expected args. + /// + public object[] ExpectedArgs + { + get { return expectedArgs; } + } + + /// + /// Determines if the object equal to expectation + /// + public override bool Equals(object obj) + { + ArgsEqualExpectation other = obj as ArgsEqualExpectation; + if (other == null) + return false; + return Method.Equals(other.Method) && Validate.ArgsEqual(expectedArgs, other.expectedArgs); + } + + /// + /// Get the hash code + /// + public override int GetHashCode() + { + return Method.GetHashCode(); + } + + + private static string FormatArg(Array args, int i) + { + if (args.Length <= i) + return "missing parameter"; + object arg = args.GetValue(i); + if (arg is Array) + { + Array arr = (Array)arg; + StringBuilder sb = new StringBuilder(); + sb.Append('['); + for (int j = 0; j < arr.Length; j++) + { + sb.Append(FormatArg(arr, j)); + if (j < arr.Length - 1) + sb.Append(", "); + } + sb.Append("]"); + return sb.ToString(); + } + else if (arg is string) + { + return '"' + arg.ToString() + '"'; + } + else if (arg == null) + { + return "null"; + } + else if (arg is IMockedObject) + { + return arg.GetType().ToString(); + } + else + { + return arg.ToString(); + } + } + } +} diff --git a/Rhino.Mocks/Expectations/CallbackExpectation.cs b/Rhino.Mocks/Expectations/CallbackExpectation.cs index 78f29139..c11ed8a0 100644 --- a/Rhino.Mocks/Expectations/CallbackExpectation.cs +++ b/Rhino.Mocks/Expectations/CallbackExpectation.cs @@ -1,127 +1,127 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Expectations -{ - /// - /// Call a specified callback to verify the expectation - /// - public class CallbackExpectation : AbstractExpectation - { - private Delegate callback; - - /// - /// Creates a new instance. - /// - /// Expectation. - /// Callback. - public CallbackExpectation(IExpectation expectation, Delegate callback) : base(expectation) - { - this.callback = callback; - ValidateCallback(); - } - - /// - /// Creates a new instance. - /// - /// Invocation for this expectation - /// Callback. - /// Number of method calls for this expectations - public CallbackExpectation(IInvocation invocation, Delegate callback, Range expectedRange) : base(invocation, expectedRange) - { - this.callback = callback; - ValidateCallback(); - } - - /// - /// Validate the arguments for the method on the child methods - /// - /// The arguments with which the method was called - protected override bool DoIsExpected(object[] args) - { - try - { - return (bool) callback.DynamicInvoke(args); - } - catch (TargetInvocationException e) - { - throw e.InnerException; - } - } - - /// - /// Gets the error message. - /// - /// - public override string ErrorMessage - { - get - { - StringBuilder sb = new StringBuilder(); - sb.Append(Method.DeclaringType.Name).Append(".").Append(Method.Name); - sb.Append("(").Append("callback method: ").Append(callback.Method.DeclaringType.Name); - sb.Append(".").Append(callback.Method.Name).Append(");"); - return CreateErrorMessage(sb.ToString()); - } - } - - private void ValidateCallback() - { - if (callback.Method.ReturnType != typeof (bool)) - throw new InvalidOperationException("Callbacks must return a boolean"); - AssertDelegateArgumentsMatchMethod(callback); - } - - /// - /// Determines if the object equal to expectation - /// - public override bool Equals(object obj) - { - CallbackExpectation other = obj as CallbackExpectation; - if (other == null) - return false; - return Method.Equals(other.Method) && callback.Equals(other.callback); - } - - /// - /// Get the hash code - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Expectations +{ + /// + /// Call a specified callback to verify the expectation + /// + public class CallbackExpectation : AbstractExpectation + { + private Delegate callback; + + /// + /// Creates a new instance. + /// + /// Expectation. + /// Callback. + public CallbackExpectation(IExpectation expectation, Delegate callback) : base(expectation) + { + this.callback = callback; + ValidateCallback(); + } + + /// + /// Creates a new instance. + /// + /// Invocation for this expectation + /// Callback. + /// Number of method calls for this expectations + public CallbackExpectation(IInvocation invocation, Delegate callback, Range expectedRange) : base(invocation, expectedRange) + { + this.callback = callback; + ValidateCallback(); + } + + /// + /// Validate the arguments for the method on the child methods + /// + /// The arguments with which the method was called + protected override bool DoIsExpected(object[] args) + { + try + { + return (bool) callback.DynamicInvoke(args); + } + catch (TargetInvocationException e) + { + throw e.InnerException; + } + } + + /// + /// Gets the error message. + /// + /// + public override string ErrorMessage + { + get + { + StringBuilder sb = new StringBuilder(); + sb.Append(Method.DeclaringType.Name).Append(".").Append(Method.Name); + sb.Append("(").Append("callback method: ").Append(callback.Method.DeclaringType.Name); + sb.Append(".").Append(callback.Method.Name).Append(");"); + return CreateErrorMessage(sb.ToString()); + } + } + + private void ValidateCallback() + { + if (callback.Method.ReturnType != typeof (bool)) + throw new InvalidOperationException("Callbacks must return a boolean"); + AssertDelegateArgumentsMatchMethod(callback); + } + + /// + /// Determines if the object equal to expectation + /// + public override bool Equals(object obj) + { + CallbackExpectation other = obj as CallbackExpectation; + if (other == null) + return false; + return Method.Equals(other.Method) && callback.Equals(other.callback); + } + + /// + /// Get the hash code + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + } +} diff --git a/Rhino.Mocks/Expectations/ConstraintsExpectation.cs b/Rhino.Mocks/Expectations/ConstraintsExpectation.cs index 412a2c23..1f462fe5 100644 --- a/Rhino.Mocks/Expectations/ConstraintsExpectation.cs +++ b/Rhino.Mocks/Expectations/ConstraintsExpectation.cs @@ -1,138 +1,138 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Constraints; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Expectations -{ - /// - /// Expect the method's arguments to match the contraints - /// - public class ConstraintsExpectation : AbstractExpectation - { - private AbstractConstraint[] constraints; - - /// - /// Creates a new instance. - /// - /// Invocation for this expectation - /// Constraints. - /// Number of method calls for this expectations - public ConstraintsExpectation(IInvocation invocation,AbstractConstraint[] constraints, Range expectedRange) : base(invocation, expectedRange) - { - Validate.IsNotNull(constraints, "constraints"); - this.constraints = constraints; - ConstraintsMatchMethod(); - } - - /// - /// Creates a new instance. - /// - /// Expectation. - /// Constraints. - public ConstraintsExpectation(IExpectation expectation, AbstractConstraint[] constraints) : base(expectation) - { - Validate.IsNotNull(constraints, "constraints"); - this.constraints = constraints; - ConstraintsMatchMethod(); - } - - /// - /// Validate the arguments for the method. - /// - /// The arguments with which the method was called - protected override bool DoIsExpected(object[] args) - { - Validate.IsNotNull(args, "args"); - if (args.Length != constraints.Length) - throw new InvalidOperationException("Number of argument doesn't match the number of parameters!"); - for (int i = 0; i < args.Length; i++) - { - if (constraints[i].Eval(args[i]) == false) - return false; - } - return true; - } - - /// - /// Gets the error message. - /// - /// - public override string ErrorMessage - { - get - { - MethodCallUtil.FormatArgumnet format = new MethodCallUtil.FormatArgumnet(FormatArgWithConstraint); - string stringPresentation = MethodCallUtil.StringPresentation(Originalinvocation, format, Method, constraints); - return CreateErrorMessage(stringPresentation); - } - } - - private void ConstraintsMatchMethod() - { - if (constraints.Length != Method.GetParameters().Length) - throw new InvalidOperationException("The number of constraints is not the same as the number of the method's parameters!"); - for (int i = 0; i < constraints.Length; i++) - { - if (constraints[i] == null) - throw new InvalidOperationException(string.Format("The constraint at index {0} is null! Use Is.Null() to represent null parameters.", i)); - } - } - - private string FormatArgWithConstraint(Array args, int i) - { - return constraints[i].Message; - } - - /// - /// Determines if the object equal to expectation - /// - public override bool Equals(object obj) - { - ConstraintsExpectation other = obj as ConstraintsExpectation; - if (other == null) - return false; - return Method.Equals(other.Method) && Validate.ArgsEqual(constraints, other.constraints); - } - - /// - /// Get the hash code - /// - public override int GetHashCode() - { - return base.GetHashCode(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Constraints; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Expectations +{ + /// + /// Expect the method's arguments to match the contraints + /// + public class ConstraintsExpectation : AbstractExpectation + { + private AbstractConstraint[] constraints; + + /// + /// Creates a new instance. + /// + /// Invocation for this expectation + /// Constraints. + /// Number of method calls for this expectations + public ConstraintsExpectation(IInvocation invocation,AbstractConstraint[] constraints, Range expectedRange) : base(invocation, expectedRange) + { + Validate.IsNotNull(constraints, "constraints"); + this.constraints = constraints; + ConstraintsMatchMethod(); + } + + /// + /// Creates a new instance. + /// + /// Expectation. + /// Constraints. + public ConstraintsExpectation(IExpectation expectation, AbstractConstraint[] constraints) : base(expectation) + { + Validate.IsNotNull(constraints, "constraints"); + this.constraints = constraints; + ConstraintsMatchMethod(); + } + + /// + /// Validate the arguments for the method. + /// + /// The arguments with which the method was called + protected override bool DoIsExpected(object[] args) + { + Validate.IsNotNull(args, "args"); + if (args.Length != constraints.Length) + throw new InvalidOperationException("Number of argument doesn't match the number of parameters!"); + for (int i = 0; i < args.Length; i++) + { + if (constraints[i].Eval(args[i]) == false) + return false; + } + return true; + } + + /// + /// Gets the error message. + /// + /// + public override string ErrorMessage + { + get + { + MethodCallUtil.FormatArgumnet format = new MethodCallUtil.FormatArgumnet(FormatArgWithConstraint); + string stringPresentation = MethodCallUtil.StringPresentation(Originalinvocation, format, Method, constraints); + return CreateErrorMessage(stringPresentation); + } + } + + private void ConstraintsMatchMethod() + { + if (constraints.Length != Method.GetParameters().Length) + throw new InvalidOperationException("The number of constraints is not the same as the number of the method's parameters!"); + for (int i = 0; i < constraints.Length; i++) + { + if (constraints[i] == null) + throw new InvalidOperationException(string.Format("The constraint at index {0} is null! Use Is.Null() to represent null parameters.", i)); + } + } + + private string FormatArgWithConstraint(Array args, int i) + { + return constraints[i].Message; + } + + /// + /// Determines if the object equal to expectation + /// + public override bool Equals(object obj) + { + ConstraintsExpectation other = obj as ConstraintsExpectation; + if (other == null) + return false; + return Method.Equals(other.Method) && Validate.ArgsEqual(constraints, other.constraints); + } + + /// + /// Get the hash code + /// + public override int GetHashCode() + { + return base.GetHashCode(); + } + } +} diff --git a/Rhino.Mocks/Generated/ExpectationsListGenerated.cs b/Rhino.Mocks/Generated/ExpectationsListGenerated.cs index 6dd8eb7e..578def03 100644 --- a/Rhino.Mocks/Generated/ExpectationsListGenerated.cs +++ b/Rhino.Mocks/Generated/ExpectationsListGenerated.cs @@ -1,43 +1,43 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Generated -{ - - /// - /// ExpectationsList - /// - public class ExpectationsList : System.Collections.Generic.List - { - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Generated +{ + + /// + /// ExpectationsList + /// + public class ExpectationsList : System.Collections.Generic.List + { + } } \ No newline at end of file diff --git a/Rhino.Mocks/Generated/ProxyMethodExpectationsDictionaryGenerated.cs b/Rhino.Mocks/Generated/ProxyMethodExpectationsDictionaryGenerated.cs index 337945ea..0f104c36 100644 --- a/Rhino.Mocks/Generated/ProxyMethodExpectationsDictionaryGenerated.cs +++ b/Rhino.Mocks/Generated/ProxyMethodExpectationsDictionaryGenerated.cs @@ -1,43 +1,43 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Collections; -using Rhino.Mocks.MethodRecorders; -using Rhino.Mocks.Impl; - -namespace Rhino.Mocks.Generated -{ - /// - /// Dictionary - /// - public class ProxyMethodExpectationsDictionary : System.Collections.Generic.Dictionary - { - } - +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Collections; +using Rhino.Mocks.MethodRecorders; +using Rhino.Mocks.Impl; + +namespace Rhino.Mocks.Generated +{ + /// + /// Dictionary + /// + public class ProxyMethodExpectationsDictionary : System.Collections.Generic.Dictionary + { + } + } \ No newline at end of file diff --git a/Rhino.Mocks/Generated/ProxyStateDictionaryGenerated.cs b/Rhino.Mocks/Generated/ProxyStateDictionaryGenerated.cs index ea9cf060..ec4453e0 100644 --- a/Rhino.Mocks/Generated/ProxyStateDictionaryGenerated.cs +++ b/Rhino.Mocks/Generated/ProxyStateDictionaryGenerated.cs @@ -1,48 +1,48 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Collections.Generic; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Generated -{ - /// - /// Dictionary class - /// - public class ProxyStateDictionary : Dictionary - { - /// - /// Create a new instance of ProxyStateDictionary - /// - public ProxyStateDictionary() : base(MockedObjectsEquality.Instance) - { - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Collections.Generic; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Generated +{ + /// + /// Dictionary class + /// + public class ProxyStateDictionary : Dictionary + { + /// + /// Create a new instance of ProxyStateDictionary + /// + public ProxyStateDictionary() : base(MockedObjectsEquality.Instance) + { + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/CreateMethodExpectation.cs b/Rhino.Mocks/Impl/CreateMethodExpectation.cs index 88305194..95f33141 100644 --- a/Rhino.Mocks/Impl/CreateMethodExpectation.cs +++ b/Rhino.Mocks/Impl/CreateMethodExpectation.cs @@ -1,60 +1,60 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// Allows to call a method and immediately get it's options. - /// - public class CreateMethodExpectation : ICreateMethodExpectation - { - private IMockedObject mockedObject; - private readonly object mockedInstance; - - /// - /// Creates a new instance. - /// - public CreateMethodExpectation(IMockedObject mockedObject, object mockedInstance) - { - this.mockedObject = mockedObject; - this.mockedInstance = mockedInstance; - } - - /// - /// Get the method options for the call - /// - /// The method call should go here, the return value is ignored - public virtual IMethodOptions Call(T ignored) - { - return mockedObject.Repository.LastMethodCall(mockedInstance); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// Allows to call a method and immediately get it's options. + /// + public class CreateMethodExpectation : ICreateMethodExpectation + { + private IMockedObject mockedObject; + private readonly object mockedInstance; + + /// + /// Creates a new instance. + /// + public CreateMethodExpectation(IMockedObject mockedObject, object mockedInstance) + { + this.mockedObject = mockedObject; + this.mockedInstance = mockedInstance; + } + + /// + /// Get the method options for the call + /// + /// The method call should go here, the return value is ignored + public virtual IMethodOptions Call(T ignored) + { + return mockedObject.Repository.LastMethodCall(mockedInstance); + } + } +} diff --git a/Rhino.Mocks/Impl/CreateMethodExpectationForSetupResult.cs b/Rhino.Mocks/Impl/CreateMethodExpectationForSetupResult.cs index 21c53ae9..fa5e4ab2 100644 --- a/Rhino.Mocks/Impl/CreateMethodExpectationForSetupResult.cs +++ b/Rhino.Mocks/Impl/CreateMethodExpectationForSetupResult.cs @@ -1,58 +1,58 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// Allows to call a method and immediately get it's options. - /// Set the expected number for the call to Any() - /// - public class CreateMethodExpectationForSetupResult : CreateMethodExpectation - { - /// - /// Creates a new instance. - /// - /// Proxy. - /// Mocked instance. - public CreateMethodExpectationForSetupResult(IMockedObject mockedObject, object mockedInstance) : base(mockedObject, mockedInstance) - { - } - - /// - /// Get the method options for the call - /// - /// The method call should go here, the return value is ignored - public override IMethodOptions Call(T ignored) - { - return base.Call(ignored).Repeat.Any(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// Allows to call a method and immediately get it's options. + /// Set the expected number for the call to Any() + /// + public class CreateMethodExpectationForSetupResult : CreateMethodExpectation + { + /// + /// Creates a new instance. + /// + /// Proxy. + /// Mocked instance. + public CreateMethodExpectationForSetupResult(IMockedObject mockedObject, object mockedInstance) : base(mockedObject, mockedInstance) + { + } + + /// + /// Get the method options for the call + /// + /// The method call should go here, the return value is ignored + public override IMethodOptions Call(T ignored) + { + return base.Call(ignored).Repeat.Any(); + } + } +} diff --git a/Rhino.Mocks/Impl/DelegateTargetInterfaceCreator.cs b/Rhino.Mocks/Impl/DelegateTargetInterfaceCreator.cs index 20602261..9400b9cb 100644 --- a/Rhino.Mocks/Impl/DelegateTargetInterfaceCreator.cs +++ b/Rhino.Mocks/Impl/DelegateTargetInterfaceCreator.cs @@ -1,99 +1,99 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections; -using System.Reflection; -using System.Reflection.Emit; -using System.Threading; -using Castle.DynamicProxy; - -namespace Rhino.Mocks.Impl -{ - /// - /// This class is reponsible for taking a delegate and creating a wrapper - /// interface around it, so it can be mocked. - /// - internal class DelegateTargetInterfaceCreator - { - private long counter=0; - - /// - /// The scope for all the delegate interfaces create by this mock repository. - /// - private ModuleScope moduleScope = new ModuleScope(); - - private IDictionary delegateTargetInterfaces = new Hashtable(); - - /// - /// Gets a type with an "Invoke" method suitable for use as a target of the - /// specified delegate type. - /// - /// - /// - public Type GetDelegateTargetInterface(Type delegateType) - { - Type type; - lock (delegateTargetInterfaces) - { - type = (Type)delegateTargetInterfaces[delegateType]; - - if (type == null) - { - type = CreateCallableInterfaceFromDelegate(delegateType); - delegateTargetInterfaces[delegateType] = type; - } - } - return type; - } - - private Type CreateCallableInterfaceFromDelegate(Type delegateType) - { - Type type; - long count = Interlocked.Increment(ref counter); - TypeBuilder typeBuilder = moduleScope.ObtainDynamicModule(true).DefineType( - string.Format("ProxyDelegate_{0}_{1}", delegateType.Name, count), - TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public); - - MethodInfo invoke = delegateType.GetMethod("Invoke"); - ParameterInfo[] parameters = invoke.GetParameters(); - - Type returnType = invoke.ReturnType; - Type[] parameterTypes = new Type[parameters.Length]; - for (int i = 0; i < parameters.Length; i++) - parameterTypes[i] = parameters[i].ParameterType; - - typeBuilder.DefineMethod("Invoke", MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.Public, - CallingConventions.HasThis, returnType, parameterTypes); - - type = typeBuilder.CreateType(); - return type; - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections; +using System.Reflection; +using System.Reflection.Emit; +using System.Threading; +using Castle.DynamicProxy; + +namespace Rhino.Mocks.Impl +{ + /// + /// This class is reponsible for taking a delegate and creating a wrapper + /// interface around it, so it can be mocked. + /// + internal class DelegateTargetInterfaceCreator + { + private long counter=0; + + /// + /// The scope for all the delegate interfaces create by this mock repository. + /// + private ModuleScope moduleScope = new ModuleScope(); + + private IDictionary delegateTargetInterfaces = new Hashtable(); + + /// + /// Gets a type with an "Invoke" method suitable for use as a target of the + /// specified delegate type. + /// + /// + /// + public Type GetDelegateTargetInterface(Type delegateType) + { + Type type; + lock (delegateTargetInterfaces) + { + type = (Type)delegateTargetInterfaces[delegateType]; + + if (type == null) + { + type = CreateCallableInterfaceFromDelegate(delegateType); + delegateTargetInterfaces[delegateType] = type; + } + } + return type; + } + + private Type CreateCallableInterfaceFromDelegate(Type delegateType) + { + Type type; + long count = Interlocked.Increment(ref counter); + TypeBuilder typeBuilder = moduleScope.ObtainDynamicModule(true).DefineType( + string.Format("ProxyDelegate_{0}_{1}", delegateType.Name, count), + TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.Public); + + MethodInfo invoke = delegateType.GetMethod("Invoke"); + ParameterInfo[] parameters = invoke.GetParameters(); + + Type returnType = invoke.ReturnType; + Type[] parameterTypes = new Type[parameters.Length]; + for (int i = 0; i < parameters.Length; i++) + parameterTypes[i] = parameters[i].ParameterType; + + typeBuilder.DefineMethod("Invoke", MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.Public, + CallingConventions.HasThis, returnType, parameterTypes); + + type = typeBuilder.CreateType(); + return type; + } + } +} diff --git a/Rhino.Mocks/Impl/EventRaiser.cs b/Rhino.Mocks/Impl/EventRaiser.cs index 94035c21..cef74f7f 100644 --- a/Rhino.Mocks/Impl/EventRaiser.cs +++ b/Rhino.Mocks/Impl/EventRaiser.cs @@ -1,142 +1,142 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Impl -{ - /// - /// Raise events for all subscribers for an event - /// - public class EventRaiser : IEventRaiser - { - string eventName; - IMockedObject proxy; - - /// - /// Create an event raiser for the specified event on this instance. - /// - public static IEventRaiser Create(object instance, string eventName) - { - IMockedObject proxy = instance as IMockedObject; - if (proxy == null) - throw new ArgumentException("Parameter must be a mocked object", "instance"); - return new EventRaiser(proxy, eventName); - } - - /// - /// Creates a new instance of EventRaiser - /// - public EventRaiser(IMockedObject proxy, string eventName) - { - this.eventName = eventName; - this.proxy = proxy; - } - - #region IEventRaiser Members - - /// - /// Raise the event - /// - public void Raise(params object[] args) - { - Delegate subscribed = proxy.GetEventSubscribers(eventName); - if (subscribed != null) - { - AssertMatchingParameters(subscribed.Method, args); - try - { - subscribed.DynamicInvoke(args); - } - catch (TargetInvocationException e) - { - PreserveStackTrace(e.InnerException); - throw e.InnerException; - } - } - } - - private static void PreserveStackTrace(Exception exception) - { - MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace", - BindingFlags.Instance | BindingFlags.NonPublic); - preserveStackTrace.Invoke(exception, null); - } - - private static void AssertMatchingParameters(MethodInfo method, object[] args) - { - ParameterInfo[] parameterInfos = method.GetParameters(); - int paramsCount = parameterInfos.Length; - if(args== null || args.Length != paramsCount) - { - int actualCount; - if(args==null) - actualCount = 0; - else - actualCount = args.Length; - string msg = string.Format("You have called the event raiser with the wrong number of parameters. Expected {0} but was {1}", paramsCount, actualCount); - throw new InvalidOperationException(msg); - } - List errors = new List(); - for (int i = 0; i < parameterInfos.Length; i++) - { - if ((args[i] == null && parameterInfos[i].ParameterType.IsValueType) || - (args[i] != null && parameterInfos[i].ParameterType.IsInstanceOfType(args[i])==false)) - { - string type = "null"; - if(args[i]!=null) - type = args[i].GetType().FullName; - errors.Add("Parameter #" + (i+1) + " is " + type + " but should be " + - parameterInfos[i].ParameterType); - } - } - if(errors.Count>0) - { - throw new InvalidOperationException(string.Join(Environment.NewLine, errors.ToArray())); - } - } - - /// - /// The most common signature for events - /// Here to allow intellisense to make better guesses about how - /// it should suggest parameters. - /// - public void Raise(object sender, EventArgs e) - { - Raise(new object[] { sender, e }); - } - - #endregion - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Impl +{ + /// + /// Raise events for all subscribers for an event + /// + public class EventRaiser : IEventRaiser + { + string eventName; + IMockedObject proxy; + + /// + /// Create an event raiser for the specified event on this instance. + /// + public static IEventRaiser Create(object instance, string eventName) + { + IMockedObject proxy = instance as IMockedObject; + if (proxy == null) + throw new ArgumentException("Parameter must be a mocked object", "instance"); + return new EventRaiser(proxy, eventName); + } + + /// + /// Creates a new instance of EventRaiser + /// + public EventRaiser(IMockedObject proxy, string eventName) + { + this.eventName = eventName; + this.proxy = proxy; + } + + #region IEventRaiser Members + + /// + /// Raise the event + /// + public void Raise(params object[] args) + { + Delegate subscribed = proxy.GetEventSubscribers(eventName); + if (subscribed != null) + { + AssertMatchingParameters(subscribed.Method, args); + try + { + subscribed.DynamicInvoke(args); + } + catch (TargetInvocationException e) + { + PreserveStackTrace(e.InnerException); + throw e.InnerException; + } + } + } + + private static void PreserveStackTrace(Exception exception) + { + MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace", + BindingFlags.Instance | BindingFlags.NonPublic); + preserveStackTrace.Invoke(exception, null); + } + + private static void AssertMatchingParameters(MethodInfo method, object[] args) + { + ParameterInfo[] parameterInfos = method.GetParameters(); + int paramsCount = parameterInfos.Length; + if(args== null || args.Length != paramsCount) + { + int actualCount; + if(args==null) + actualCount = 0; + else + actualCount = args.Length; + string msg = string.Format("You have called the event raiser with the wrong number of parameters. Expected {0} but was {1}", paramsCount, actualCount); + throw new InvalidOperationException(msg); + } + List errors = new List(); + for (int i = 0; i < parameterInfos.Length; i++) + { + if ((args[i] == null && parameterInfos[i].ParameterType.IsValueType) || + (args[i] != null && parameterInfos[i].ParameterType.IsInstanceOfType(args[i])==false)) + { + string type = "null"; + if(args[i]!=null) + type = args[i].GetType().FullName; + errors.Add("Parameter #" + (i+1) + " is " + type + " but should be " + + parameterInfos[i].ParameterType); + } + } + if(errors.Count>0) + { + throw new InvalidOperationException(string.Join(Environment.NewLine, errors.ToArray())); + } + } + + /// + /// The most common signature for events + /// Here to allow intellisense to make better guesses about how + /// it should suggest parameters. + /// + public void Raise(object sender, EventArgs e) + { + Raise(new object[] { sender, e }); + } + + #endregion + } +} diff --git a/Rhino.Mocks/Impl/MethodOptions.cs b/Rhino.Mocks/Impl/MethodOptions.cs index 46980a40..a05aab63 100644 --- a/Rhino.Mocks/Impl/MethodOptions.cs +++ b/Rhino.Mocks/Impl/MethodOptions.cs @@ -1,556 +1,556 @@ -#region license - -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Rhino.Mocks.Constraints; -using Rhino.Mocks.Expectations; -using Rhino.Mocks.Interfaces; -using System.Reflection; -using System.Collections; - -namespace Rhino.Mocks.Impl -{ - /// - /// Allows to define what would happen when a method - /// is called. - /// - public class MethodOptions : IMethodOptions, IRepeat - { - #region Variables - - private IExpectation expectation; - private bool expectationReplaced = false; - private MockRepository repository; - private readonly RecordMockState record; - private IMockedObject proxy; - - #endregion - - #region Properties - - /// - /// Better syntax to define repeats. - /// - public IRepeat Repeat - { - get { return this; } - } - - #endregion - - #region C'tor - - /// - /// Creates a new instance. - /// - /// the repository for this expectation - /// the recorder for this proxy - /// the proxy for this expectation - /// Expectation. - public MethodOptions( - MockRepository repository, - RecordMockState record, - IMockedObject proxy, - IExpectation expectation) - { - this.expectation = expectation; - this.proxy = proxy; - this.repository = repository; - this.record = record; - } - - #endregion - - #region Public Methods - - /// - /// Add constraints for the method's arguments. - /// - public IMethodOptions Constraints(params AbstractConstraint[] constraints) - { - if (expectation is ConstraintsExpectation) - { - throw new InvalidOperationException( - string.Format("You have already specified constraints for this method. ({0})", this.expectation.ErrorMessage)); - } - ConstraintsExpectation constraintsExpectation = new ConstraintsExpectation(expectation, constraints); - ReplaceExpectation(constraintsExpectation); - return this; - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback(Delegate callback) - { - CallbackExpectation callbackExpectation = new CallbackExpectation(expectation, callback); - ReplaceExpectation(callbackExpectation); - return this; - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback(Delegates.Function callback) - { - return Callback((Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback(Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback(Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback(Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - /// - /// Set a callback method for the last call - /// - public IMethodOptions Callback( - Delegates.Function callback) - { - return Callback( (Delegate) callback); - } - - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - public IMethodOptions Do(Delegate action) - { - expectation.ActionToExecute = action; - return this; - } - - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - public IMethodOptions WhenCalled(Action action) - { - expectation.WhenCalled += action; - return this; - } - - - /// - /// 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 - public IMethodOptions Return(T objToReturn) - { - expectation.ReturnValue = objToReturn; - return this; - } - - - /// - /// 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 - public IMethodOptions TentativeReturn() - { - expectation.AllowTentativeReturn = true; - return this; - } - - /// - /// Throws the specified exception when the method is called. - /// - /// Exception to throw - public IMethodOptions Throw(Exception exception) - { - expectation.ExceptionToThrow = exception; - return this; - } - - /// - /// Ignores the arguments for this method. Any argument will be matched - /// againt this method. - /// - public IMethodOptions IgnoreArguments() - { - AnyArgsExpectation anyArgsExpectation = new AnyArgsExpectation(expectation); - ReplaceExpectation(anyArgsExpectation); - return this; - } - - /// - /// Call the original method on the class, bypassing the mocking layers. - /// - /// - [Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")] - public void CallOriginalMethod() - { - CallOriginalMethod(OriginalCallOptions.NoExpectation); - } - - - /// - /// Call the original method on the class, optionally bypassing the mocking layers - /// - /// - public IMethodOptions CallOriginalMethod(OriginalCallOptions options) - { - AssertMethodImplementationExists(); - if (options == OriginalCallOptions.NoExpectation) - { - proxy.RegisterMethodForCallingOriginal(expectation.Method); - repository.Recorder.RemoveExpectation(expectation); - expectation.RepeatableOption = RepeatableOption.OriginalCallBypassingMocking; - } - else - { - expectation.RepeatableOption = RepeatableOption.OriginalCall; - } - return this; - } - - - /// - /// Use the property as a simple property, getting/setting the values without - /// causing mock expectations. - /// - public IMethodOptions PropertyBehavior() - { - AssertExpectationOnPropertyWithGetterAndSetter(); - PropertyInfo prop = GetPropertyFromMethod(expectation.Method); - proxy.RegisterPropertyBehaviorFor(prop); - repository.Recorder.RemoveExpectation(expectation); - expectation.RepeatableOption = RepeatableOption.PropertyBehavior; - return this; - } - - /// - /// Expect last (property) call as property setting, ignore the argument given - /// - /// - public IMethodOptions SetPropertyAndIgnoreArgument() - { - bool isInReplayMode = repository.IsInReplayMode(proxy); - if(isInReplayMode) - repository.BackToRecord(proxy,BackToRecordOptions.None); - expectation.ReturnValue = default(T); - MethodInfo setter = PropertySetterFromMethod(expectation.Method); - repository.Recorder.RemoveExpectation(expectation); - setter.Invoke(proxy, new object[] {default(T)}); - IMethodOptions methodOptions = repository.LastMethodCall(proxy).IgnoreArguments(); - if (isInReplayMode) - repository.ReplayCore(proxy,true); - return methodOptions; - } - - /// - /// Expect last (property) call as property setting with a given argument. - /// - /// - /// - public IMethodOptions SetPropertyWithArgument(T argument) - { - bool isInReplayMode = repository.IsInReplayMode(proxy); - if (isInReplayMode) - repository.BackToRecord(proxy, BackToRecordOptions.None); - expectation.ReturnValue = default(T); - MethodInfo setter = PropertySetterFromMethod(expectation.Method); - repository.Recorder.RemoveExpectation(expectation); - setter.Invoke(proxy, new object[] { argument }); - IMethodOptions methodOptions = repository.LastMethodCall(proxy); - if (isInReplayMode) - repository.ReplayCore(proxy, true); - return methodOptions; - } - - /// - /// Gets the event raiser for the last event - /// - public IEventRaiser GetEventRaiser() - { - AssertLastMethodWasEventAddOrRemove(); - string eventName = expectation.Method.Name.StartsWith("add_") - ? - expectation.Method.Name.Substring(4) - : expectation.Method.Name.Substring(7); - return new EventRaiser(proxy, eventName); - } - - /// - /// Set the parameter values for out and ref parameters. - /// This is done using zero based indexing, and _ignoring_ any non out/ref parameter. - /// - public IMethodOptions OutRef(params object[] parameters) - { - Validate.IsNotNull(parameters, "parameters"); - expectation.OutRefParams = parameters; - return this; - } - - #endregion - - #region Implementation - - private void AssertExpectationOnPropertyWithGetterAndSetter() - { - MethodInfo method = expectation.Method; - //not a property geter or setter - if (false == (method.IsSpecialName && - (method.Name.StartsWith("get_") || - method.Name.StartsWith("set_")))) - throw new InvalidOperationException("Last method call was not made on a setter or a getter"); - PropertyInfo prop = GetPropertyFromMethod(method); - if (false == (prop.CanRead && prop.CanWrite)) - throw new InvalidOperationException("Property must be read/write"); - } - - private void AssertLastMethodWasEventAddOrRemove() - { - MethodInfo method = expectation.Method; - if (!(method.Name.StartsWith("add_") || method.Name.StartsWith("remove_"))) - { - throw new InvalidOperationException("The last method call " + method.Name + " was not an event add / remove method"); - } - } - - private MethodInfo PropertySetterFromMethod(MethodInfo method) - { - //not a property geter or setter - if (false == (method.IsSpecialName && - (method.Name.StartsWith("get_") || - method.Name.StartsWith("set_")))) - throw new InvalidOperationException("Last method call was not made on a setter or a getter"); - PropertyInfo prop = GetPropertyFromMethod(method); - if (!prop.CanWrite) - throw new InvalidOperationException("Property must be writeable"); - - return method.DeclaringType.GetMethod("set_" + method.Name.Substring(4)); - } - - private PropertyInfo GetPropertyFromMethod(MethodInfo method) - { - string propName = method.Name.Substring(4); - ParameterInfo[] args = method.GetParameters(); - ArrayList types = new ArrayList(); - for (int i = 0; i < args.Length; i++) - { - //remove the value parameter for finding the property if indexed - if (i == 0 && method.Name.StartsWith("set_")) - continue; - types.Add(args[i].ParameterType); - } - PropertyInfo prop = expectation.Method.DeclaringType.GetProperty(propName, - (Type[]) types.ToArray(typeof (Type))); - return prop; - } - - private void AssertMethodImplementationExists() - { - if (expectation.Method.IsAbstract) - throw new InvalidOperationException("Can't use CallOriginalMethod on method " + expectation.Method.Name + - " because the method is abstract."); - } - - private void ReplaceExpectation(IExpectation anyArgsExpectation) - { - //All other expectations ignore arguments, so it's safe to replace - //arguments when the previous expectation is any args. - if (expectationReplaced && !(expectation is AnyArgsExpectation)) - { - string message = "This method has already been set to " + expectation.GetType().Name + "."; - throw new InvalidOperationException(message); - } - repository.Recorder.ReplaceExpectation(proxy, expectation.Method, expectation, anyArgsExpectation); - expectation = anyArgsExpectation; - record.LastExpectation = expectation; - expectationReplaced = true; - } - - #endregion - - #region IRepeat Implementation - - /// - /// Repeat the method twice. - /// - public IMethodOptions Twice() - { - expectation.Expected = new Range(2, 2); - return this; - } - - /// - /// Repeat the method once. - /// - public IMethodOptions Once() - { - expectation.Expected = new Range(1, 1); - return this; - } - - /// - /// Repeat the method at least once, then repeat as many time as it would like. - /// - public IMethodOptions AtLeastOnce() - { - expectation.Expected = new Range(1, int.MaxValue); - return this; - } - - /// - /// This method must not appear in the replay state. - /// - public IMethodOptions Never() - { - expectation.Expected = new Range(0, 0); - //This expectation will not be thrown, but it will - //make sure that ExpectationSatisfied will be true if - //the method under consideration has a return value; - expectation.ExceptionToThrow = new InvalidOperationException("This is a method that should not be called"); - expectation.RepeatableOption = RepeatableOption.Never; - repository.Replayer.AddToRepeatableMethods(proxy, expectation.Method, expectation); - return this; - } - - /// - /// Documentation message for the expectation - /// - /// Message - public IMethodOptions Message(string documentationMessage) - { - expectation.Message = documentationMessage; - return this; - } - - /// - /// Repeat the method any number of times. - /// - public IMethodOptions Any() - { - expectation.Expected = new Range(int.MaxValue, int.MaxValue); - expectation.RepeatableOption = RepeatableOption.Any; - repository.Replayer.AddToRepeatableMethods(proxy, expectation.Method, expectation); - return this; - } - - /// - /// Set the range to repeat an action. - /// - /// Min. - /// Max. - public IMethodOptions Times(int min, int max) - { - expectation.Expected = new Range(min, max); - return this; - } - - /// - /// Set the amount of times to repeat an action. - /// - public IMethodOptions Times(int count) - { - expectation.Expected = new Range(count, count); - return this; - } - - #endregion - } -} +#region license + +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using Rhino.Mocks.Constraints; +using Rhino.Mocks.Expectations; +using Rhino.Mocks.Interfaces; +using System.Reflection; +using System.Collections; + +namespace Rhino.Mocks.Impl +{ + /// + /// Allows to define what would happen when a method + /// is called. + /// + public class MethodOptions : IMethodOptions, IRepeat + { + #region Variables + + private IExpectation expectation; + private bool expectationReplaced = false; + private MockRepository repository; + private readonly RecordMockState record; + private IMockedObject proxy; + + #endregion + + #region Properties + + /// + /// Better syntax to define repeats. + /// + public IRepeat Repeat + { + get { return this; } + } + + #endregion + + #region C'tor + + /// + /// Creates a new instance. + /// + /// the repository for this expectation + /// the recorder for this proxy + /// the proxy for this expectation + /// Expectation. + public MethodOptions( + MockRepository repository, + RecordMockState record, + IMockedObject proxy, + IExpectation expectation) + { + this.expectation = expectation; + this.proxy = proxy; + this.repository = repository; + this.record = record; + } + + #endregion + + #region Public Methods + + /// + /// Add constraints for the method's arguments. + /// + public IMethodOptions Constraints(params AbstractConstraint[] constraints) + { + if (expectation is ConstraintsExpectation) + { + throw new InvalidOperationException( + string.Format("You have already specified constraints for this method. ({0})", this.expectation.ErrorMessage)); + } + ConstraintsExpectation constraintsExpectation = new ConstraintsExpectation(expectation, constraints); + ReplaceExpectation(constraintsExpectation); + return this; + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback(Delegate callback) + { + CallbackExpectation callbackExpectation = new CallbackExpectation(expectation, callback); + ReplaceExpectation(callbackExpectation); + return this; + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback(Delegates.Function callback) + { + return Callback((Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback(Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback(Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback(Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + /// + /// Set a callback method for the last call + /// + public IMethodOptions Callback( + Delegates.Function callback) + { + return Callback( (Delegate) callback); + } + + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + public IMethodOptions Do(Delegate action) + { + expectation.ActionToExecute = action; + return this; + } + + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + public IMethodOptions WhenCalled(Action action) + { + expectation.WhenCalled += action; + return this; + } + + + /// + /// 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 + public IMethodOptions Return(T objToReturn) + { + expectation.ReturnValue = objToReturn; + return this; + } + + + /// + /// 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 + public IMethodOptions TentativeReturn() + { + expectation.AllowTentativeReturn = true; + return this; + } + + /// + /// Throws the specified exception when the method is called. + /// + /// Exception to throw + public IMethodOptions Throw(Exception exception) + { + expectation.ExceptionToThrow = exception; + return this; + } + + /// + /// Ignores the arguments for this method. Any argument will be matched + /// againt this method. + /// + public IMethodOptions IgnoreArguments() + { + AnyArgsExpectation anyArgsExpectation = new AnyArgsExpectation(expectation); + ReplaceExpectation(anyArgsExpectation); + return this; + } + + /// + /// Call the original method on the class, bypassing the mocking layers. + /// + /// + [Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")] + public void CallOriginalMethod() + { + CallOriginalMethod(OriginalCallOptions.NoExpectation); + } + + + /// + /// Call the original method on the class, optionally bypassing the mocking layers + /// + /// + public IMethodOptions CallOriginalMethod(OriginalCallOptions options) + { + AssertMethodImplementationExists(); + if (options == OriginalCallOptions.NoExpectation) + { + proxy.RegisterMethodForCallingOriginal(expectation.Method); + repository.Recorder.RemoveExpectation(expectation); + expectation.RepeatableOption = RepeatableOption.OriginalCallBypassingMocking; + } + else + { + expectation.RepeatableOption = RepeatableOption.OriginalCall; + } + return this; + } + + + /// + /// Use the property as a simple property, getting/setting the values without + /// causing mock expectations. + /// + public IMethodOptions PropertyBehavior() + { + AssertExpectationOnPropertyWithGetterAndSetter(); + PropertyInfo prop = GetPropertyFromMethod(expectation.Method); + proxy.RegisterPropertyBehaviorFor(prop); + repository.Recorder.RemoveExpectation(expectation); + expectation.RepeatableOption = RepeatableOption.PropertyBehavior; + return this; + } + + /// + /// Expect last (property) call as property setting, ignore the argument given + /// + /// + public IMethodOptions SetPropertyAndIgnoreArgument() + { + bool isInReplayMode = repository.IsInReplayMode(proxy); + if(isInReplayMode) + repository.BackToRecord(proxy,BackToRecordOptions.None); + expectation.ReturnValue = default(T); + MethodInfo setter = PropertySetterFromMethod(expectation.Method); + repository.Recorder.RemoveExpectation(expectation); + setter.Invoke(proxy, new object[] {default(T)}); + IMethodOptions methodOptions = repository.LastMethodCall(proxy).IgnoreArguments(); + if (isInReplayMode) + repository.ReplayCore(proxy,true); + return methodOptions; + } + + /// + /// Expect last (property) call as property setting with a given argument. + /// + /// + /// + public IMethodOptions SetPropertyWithArgument(T argument) + { + bool isInReplayMode = repository.IsInReplayMode(proxy); + if (isInReplayMode) + repository.BackToRecord(proxy, BackToRecordOptions.None); + expectation.ReturnValue = default(T); + MethodInfo setter = PropertySetterFromMethod(expectation.Method); + repository.Recorder.RemoveExpectation(expectation); + setter.Invoke(proxy, new object[] { argument }); + IMethodOptions methodOptions = repository.LastMethodCall(proxy); + if (isInReplayMode) + repository.ReplayCore(proxy, true); + return methodOptions; + } + + /// + /// Gets the event raiser for the last event + /// + public IEventRaiser GetEventRaiser() + { + AssertLastMethodWasEventAddOrRemove(); + string eventName = expectation.Method.Name.StartsWith("add_") + ? + expectation.Method.Name.Substring(4) + : expectation.Method.Name.Substring(7); + return new EventRaiser(proxy, eventName); + } + + /// + /// Set the parameter values for out and ref parameters. + /// This is done using zero based indexing, and _ignoring_ any non out/ref parameter. + /// + public IMethodOptions OutRef(params object[] parameters) + { + Validate.IsNotNull(parameters, "parameters"); + expectation.OutRefParams = parameters; + return this; + } + + #endregion + + #region Implementation + + private void AssertExpectationOnPropertyWithGetterAndSetter() + { + MethodInfo method = expectation.Method; + //not a property geter or setter + if (false == (method.IsSpecialName && + (method.Name.StartsWith("get_") || + method.Name.StartsWith("set_")))) + throw new InvalidOperationException("Last method call was not made on a setter or a getter"); + PropertyInfo prop = GetPropertyFromMethod(method); + if (false == (prop.CanRead && prop.CanWrite)) + throw new InvalidOperationException("Property must be read/write"); + } + + private void AssertLastMethodWasEventAddOrRemove() + { + MethodInfo method = expectation.Method; + if (!(method.Name.StartsWith("add_") || method.Name.StartsWith("remove_"))) + { + throw new InvalidOperationException("The last method call " + method.Name + " was not an event add / remove method"); + } + } + + private MethodInfo PropertySetterFromMethod(MethodInfo method) + { + //not a property geter or setter + if (false == (method.IsSpecialName && + (method.Name.StartsWith("get_") || + method.Name.StartsWith("set_")))) + throw new InvalidOperationException("Last method call was not made on a setter or a getter"); + PropertyInfo prop = GetPropertyFromMethod(method); + if (!prop.CanWrite) + throw new InvalidOperationException("Property must be writeable"); + + return method.DeclaringType.GetMethod("set_" + method.Name.Substring(4)); + } + + private PropertyInfo GetPropertyFromMethod(MethodInfo method) + { + string propName = method.Name.Substring(4); + ParameterInfo[] args = method.GetParameters(); + ArrayList types = new ArrayList(); + for (int i = 0; i < args.Length; i++) + { + //remove the value parameter for finding the property if indexed + if (i == 0 && method.Name.StartsWith("set_")) + continue; + types.Add(args[i].ParameterType); + } + PropertyInfo prop = expectation.Method.DeclaringType.GetProperty(propName, + (Type[]) types.ToArray(typeof (Type))); + return prop; + } + + private void AssertMethodImplementationExists() + { + if (expectation.Method.IsAbstract) + throw new InvalidOperationException("Can't use CallOriginalMethod on method " + expectation.Method.Name + + " because the method is abstract."); + } + + private void ReplaceExpectation(IExpectation anyArgsExpectation) + { + //All other expectations ignore arguments, so it's safe to replace + //arguments when the previous expectation is any args. + if (expectationReplaced && !(expectation is AnyArgsExpectation)) + { + string message = "This method has already been set to " + expectation.GetType().Name + "."; + throw new InvalidOperationException(message); + } + repository.Recorder.ReplaceExpectation(proxy, expectation.Method, expectation, anyArgsExpectation); + expectation = anyArgsExpectation; + record.LastExpectation = expectation; + expectationReplaced = true; + } + + #endregion + + #region IRepeat Implementation + + /// + /// Repeat the method twice. + /// + public IMethodOptions Twice() + { + expectation.Expected = new Range(2, 2); + return this; + } + + /// + /// Repeat the method once. + /// + public IMethodOptions Once() + { + expectation.Expected = new Range(1, 1); + return this; + } + + /// + /// Repeat the method at least once, then repeat as many time as it would like. + /// + public IMethodOptions AtLeastOnce() + { + expectation.Expected = new Range(1, int.MaxValue); + return this; + } + + /// + /// This method must not appear in the replay state. + /// + public IMethodOptions Never() + { + expectation.Expected = new Range(0, 0); + //This expectation will not be thrown, but it will + //make sure that ExpectationSatisfied will be true if + //the method under consideration has a return value; + expectation.ExceptionToThrow = new InvalidOperationException("This is a method that should not be called"); + expectation.RepeatableOption = RepeatableOption.Never; + repository.Replayer.AddToRepeatableMethods(proxy, expectation.Method, expectation); + return this; + } + + /// + /// Documentation message for the expectation + /// + /// Message + public IMethodOptions Message(string documentationMessage) + { + expectation.Message = documentationMessage; + return this; + } + + /// + /// Repeat the method any number of times. + /// + public IMethodOptions Any() + { + expectation.Expected = new Range(int.MaxValue, int.MaxValue); + expectation.RepeatableOption = RepeatableOption.Any; + repository.Replayer.AddToRepeatableMethods(proxy, expectation.Method, expectation); + return this; + } + + /// + /// Set the range to repeat an action. + /// + /// Min. + /// Max. + public IMethodOptions Times(int min, int max) + { + expectation.Expected = new Range(min, max); + return this; + } + + /// + /// Set the amount of times to repeat an action. + /// + public IMethodOptions Times(int count) + { + expectation.Expected = new Range(count, count); + return this; + } + + #endregion + } +} diff --git a/Rhino.Mocks/Impl/MockedObjectsEquality.cs b/Rhino.Mocks/Impl/MockedObjectsEquality.cs index 9f0bb82e..5fb9e846 100644 --- a/Rhino.Mocks/Impl/MockedObjectsEquality.cs +++ b/Rhino.Mocks/Impl/MockedObjectsEquality.cs @@ -1,134 +1,134 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections; -using System.Threading; -using Rhino.Mocks.Interfaces; -using System.Collections.Generic; - -namespace Rhino.Mocks.Impl -{ - /// - /// 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. - /// - public class MockedObjectsEquality : IComparer, IEqualityComparer, IEqualityComparer - { - private static readonly MockedObjectsEquality instance = new MockedObjectsEquality(); - - private static int baseHashcode = 0; - - /// - /// The next hash code value for a mock object. - /// This is safe for multi threading. - /// - public static int NextHashCode - { - get - { - return Interlocked.Increment(ref baseHashcode); - } - } - - /// - /// The sole instance of - /// - public static MockedObjectsEquality Instance - { - get { return instance; } - } - - /// - /// Get the hash code for a proxy object without calling GetHashCode() - /// on the object. - /// - public int GetHashCode(object obj) - { - IMockedObject mockedObject = MockRepository.GetMockedObjectOrNull(obj); - if (mockedObject==null) - return obj.GetHashCode(); - return mockedObject.ProxyHash; - } - - /// - /// Compares two instances of mocked objects - /// - public int Compare(object x, object y) - { - if (x == null && y == null) - return 0; - if (x == null) - return 1; - if (y == null) - return -1; - - IMockedObject one = MockRepository.GetMockedObjectOrNull(x); - IMockedObject two = MockRepository.GetMockedObjectOrNull(y); - if (one == null && two == null) - return -2;//both of them are probably transperant proxies - if (one == null) - return 1; - if (two == null) - return -1; - - return one.ProxyHash - two.ProxyHash; - } - - private MockedObjectsEquality() - { - } - - #region IEqualityComparer Members - - /// - /// Compare two mocked objects - /// - public new bool Equals(object x, object y) - { - return Compare(x, y)==0; - } - - #endregion - - #region IEqualityComparer Members - bool System.Collections.Generic.IEqualityComparer.Equals(object x, object y) - { - return Compare(x, y) == 0; - } - - int System.Collections.Generic.IEqualityComparer.GetHashCode(object obj) - { - return this.GetHashCode(obj); - } - #endregion - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections; +using System.Threading; +using Rhino.Mocks.Interfaces; +using System.Collections.Generic; + +namespace Rhino.Mocks.Impl +{ + /// + /// 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. + /// + public class MockedObjectsEquality : IComparer, IEqualityComparer, IEqualityComparer + { + private static readonly MockedObjectsEquality instance = new MockedObjectsEquality(); + + private static int baseHashcode = 0; + + /// + /// The next hash code value for a mock object. + /// This is safe for multi threading. + /// + public static int NextHashCode + { + get + { + return Interlocked.Increment(ref baseHashcode); + } + } + + /// + /// The sole instance of + /// + public static MockedObjectsEquality Instance + { + get { return instance; } + } + + /// + /// Get the hash code for a proxy object without calling GetHashCode() + /// on the object. + /// + public int GetHashCode(object obj) + { + IMockedObject mockedObject = MockRepository.GetMockedObjectOrNull(obj); + if (mockedObject==null) + return obj.GetHashCode(); + return mockedObject.ProxyHash; + } + + /// + /// Compares two instances of mocked objects + /// + public int Compare(object x, object y) + { + if (x == null && y == null) + return 0; + if (x == null) + return 1; + if (y == null) + return -1; + + IMockedObject one = MockRepository.GetMockedObjectOrNull(x); + IMockedObject two = MockRepository.GetMockedObjectOrNull(y); + if (one == null && two == null) + return -2;//both of them are probably transperant proxies + if (one == null) + return 1; + if (two == null) + return -1; + + return one.ProxyHash - two.ProxyHash; + } + + private MockedObjectsEquality() + { + } + + #region IEqualityComparer Members + + /// + /// Compare two mocked objects + /// + public new bool Equals(object x, object y) + { + return Compare(x, y)==0; + } + + #endregion + + #region IEqualityComparer Members + bool System.Collections.Generic.IEqualityComparer.Equals(object x, object y) + { + return Compare(x, y) == 0; + } + + int System.Collections.Generic.IEqualityComparer.GetHashCode(object obj) + { + return this.GetHashCode(obj); + } + #endregion + } +} diff --git a/Rhino.Mocks/Impl/NullLogger.cs b/Rhino.Mocks/Impl/NullLogger.cs index 24caee88..4f8f98d6 100644 --- a/Rhino.Mocks/Impl/NullLogger.cs +++ b/Rhino.Mocks/Impl/NullLogger.cs @@ -1,38 +1,38 @@ -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// Doesn't log anything, just makes happy noises - /// - public class NullLogger : IExpectationLogger - { - /// - /// Logs the expectation as is was recorded - /// - /// The invocation. - /// The expectation. - public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) - { - } - - /// - /// Logs the expectation as it was recorded - /// - /// The invocation. - /// The expectation. - public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) - { - } - - /// - /// Logs the unexpected method call. - /// - /// The invocation. - /// The message. - public void LogUnexpectedMethodCall(IInvocation invocation, string message) - { - } - } +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// Doesn't log anything, just makes happy noises + /// + public class NullLogger : IExpectationLogger + { + /// + /// Logs the expectation as is was recorded + /// + /// The invocation. + /// The expectation. + public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) + { + } + + /// + /// Logs the expectation as it was recorded + /// + /// The invocation. + /// The expectation. + public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) + { + } + + /// + /// Logs the unexpected method call. + /// + /// The invocation. + /// The message. + public void LogUnexpectedMethodCall(IInvocation invocation, string message) + { + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/ProxyInstance.cs b/Rhino.Mocks/Impl/ProxyInstance.cs index 0b7e57a8..63007b30 100644 --- a/Rhino.Mocks/Impl/ProxyInstance.cs +++ b/Rhino.Mocks/Impl/ProxyInstance.cs @@ -1,362 +1,362 @@ -#region license - -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// This is a dummy type that is used merely to give DynamicProxy the proxy instance that - /// it needs to create IProxy's types. - /// - public class ProxyInstance : MarshalByRefObject, IMockedObject - { - private readonly MockRepository repository; - private readonly int hashCode; - private IList originalMethodsToCall; - private IList propertiesToSimulate; - private IDictionary propertiesValues; - private IDictionary eventsSubscribers; - private readonly Type[] implemented; - - private readonly IDictionary> methodToActualCalls = new Dictionary>(); - private object[] constructorArguments = new object[0]; - private IList dependentMocks = new List(); - - /// - /// Create a new instance of - /// - public ProxyInstance(MockRepository repository, params Type[] implemented) - { - this.repository = repository; - this.implemented = implemented; - hashCode = MockedObjectsEquality.NextHashCode; - } - - /// - /// Mocks that are tied to this mock lifestyle - /// - public IList DependentMocks - { - get { return dependentMocks; } - } - - /// - /// The unique hash code of this proxy, which is not related - /// to the value of the GetHashCode() call on the object. - /// - public int ProxyHash - { - get { return hashCode; } - } - - /// - /// Gets the repository. - /// - public MockRepository Repository - { - get { return repository; } - } - - /// - /// Return true if it should call the original method on the object - /// instead of pass it to the message chain. - /// - /// The method to call - public bool ShouldCallOriginal(MethodInfo method) - { - if (originalMethodsToCall == null) - return false; - return originalMethodsToCall.Contains(method); - } - - /// - /// Register a method to be called on the object directly - /// - public void RegisterMethodForCallingOriginal(MethodInfo method) - { - if (originalMethodsToCall == null) - originalMethodsToCall = new ArrayList(); - originalMethodsToCall.Add(method); - } - - /// - /// Register a property on the object that will behave as a simple property - /// Return true if there is already a value for the property - /// - public bool RegisterPropertyBehaviorFor(PropertyInfo prop) - { - if (propertiesToSimulate == null) - propertiesToSimulate = new ArrayList(); - MethodInfo getMethod = prop.GetGetMethod(true); - MethodInfo setMethod = prop.GetSetMethod(true); - if (propertiesToSimulate.Contains(getMethod) == false) - propertiesToSimulate.Add(getMethod); - if (propertiesToSimulate.Contains(setMethod) == false) - propertiesToSimulate.Add(setMethod); - return propertiesValues!=null && - propertiesValues.Contains(GenerateKey(getMethod, new object[0])); - } - - /// - /// Check if the method was registered as a property method. - /// - public bool IsPropertyMethod(MethodInfo method) - { - if (propertiesToSimulate == null) - return false; - //we have to do it this way, to handle generic types - foreach (MethodInfo info in propertiesToSimulate) - { - if( AreMethodEquals(info, method)) - return true; - } - return false; - } - - private static bool AreMethodEquals(MethodInfo left, MethodInfo right) - { - if (left.Equals(right)) - return true; - // GetHashCode calls to RuntimeMethodHandle.StripMethodInstantiation() - // which is needed to fix issues with method equality from generic types. - if (left.GetHashCode() != right.GetHashCode()) - return false; - if (left.DeclaringType != right.DeclaringType) - return false; - ParameterInfo[] leftParams = left.GetParameters(); - ParameterInfo[] rightParams = right.GetParameters(); - if (leftParams.Length != rightParams.Length) - return false; - for (int i = 0; i < leftParams.Length; i++) - { - if (leftParams[i].ParameterType != rightParams[i].ParameterType) - return false; - } - if (left.ReturnType != right.ReturnType) - return false; - return true; - } - - /// - /// Do get/set on the property, according to need. - /// - public object HandleProperty(MethodInfo method, object[] args) - { - if (propertiesValues == null) - propertiesValues = new Hashtable(); - - if (method.Name.StartsWith("get_")) - { - string key = GenerateKey(method, args); - if (propertiesValues.Contains(key) == false && method.ReturnType.IsValueType) - { - throw new InvalidOperationException( - string.Format( - "Can't return a value for property {0} because no value was set and the Property return a value type.", - method.Name.Substring(4))); - } - return propertiesValues[key]; - } - - object value = args[args.Length - 1]; - propertiesValues[GenerateKey(method, args)] = value; - return null; - } - - - /// - /// Do add/remove on the event - /// - public void HandleEvent(MethodInfo method, object[] args) - { - if (eventsSubscribers == null) - eventsSubscribers = new Hashtable(); - - Delegate subscriber = (Delegate) args[0]; - if (method.Name.StartsWith("add_")) - { - AddEvent(method, subscriber); - } - else - { - RemoveEvent(method, subscriber); - } - } - - /// - /// Get the subscribers of a spesific event - /// - public Delegate GetEventSubscribers(string eventName) - { - if (eventsSubscribers == null) - return null; - return (Delegate) eventsSubscribers[eventName]; - } - - /// - /// Gets the declaring type of the method, taking into acccount the possible generic - /// parameters that it was created with. - /// - public Type GetDeclaringType(MethodInfo info) - { - Type typeDeclaringTheMethod = info.DeclaringType; - foreach (Type type in implemented) - { - if (type == typeDeclaringTheMethod) - return type; - if (typeDeclaringTheMethod.IsGenericType && - typeDeclaringTheMethod == type.GetGenericTypeDefinition()) - return type; - } - return null; - } - - - /// - /// Gets or sets the constructor arguments. - /// - /// The constructor arguments. - public object[] ConstructorArguments - { - get { return constructorArguments; } - set { constructorArguments = value; } - } - - private object mockedObjectInstance; - - /// - /// The mocked instance that this is representing - /// - public object MockedObjectInstance - { - get { return mockedObjectInstance; } - set { mockedObjectInstance = value; } - } - - /// - /// Gets the implemented types by this mocked object - /// - /// The implemented. - public Type[] ImplementedTypes - { - get { return implemented; } - } - - /// - /// Get all the method calls arguments that were made against this object with the specificed - /// method. - /// - /// - /// - /// - /// Only method calls in replay mode are counted - /// - public ICollection GetCallArgumentsFor(MethodInfo method) - { - if (methodToActualCalls.ContainsKey(method) == false) - return new List(); - return methodToActualCalls[method]; - } - - - /// - /// Records the method call - /// - /// - /// - public void MethodCall(MethodInfo method, object[] args) - { - if(repository.IsInReplayMode(this)==false) - return; - if (methodToActualCalls.ContainsKey(method) == false) - methodToActualCalls[method] = new List(); - methodToActualCalls[method].Add(args); - } - - /// - /// Clears the state of the object, remove original calls, property behavior, subscribed events, etc. - /// - public void ClearState(BackToRecordOptions options) - { - if (eventsSubscribers != null && - (options & BackToRecordOptions.EventSubscribers) != 0) - eventsSubscribers.Clear(); - if (originalMethodsToCall != null && - (options & BackToRecordOptions.OriginalMethodsToCall) != 0) - originalMethodsToCall.Clear(); - if (propertiesValues != null && - (options & BackToRecordOptions.PropertyBehavior) != 0) - propertiesValues.Clear(); - if (propertiesToSimulate != null && - (options & BackToRecordOptions.PropertyBehavior) != 0) - propertiesToSimulate.Clear(); - } - - private static string GenerateKey(MethodInfo method, object[] args) - { - var baseName = method.DeclaringType.FullName + method.Name.Substring(4); - if ((method.Name.StartsWith("get_") && args.Length == 0) || - (method.Name.StartsWith("set_") && args.Length == 1)) - return baseName; - StringBuilder sb = new StringBuilder(); - sb.Append(baseName); - int len = args.Length; - if (method.Name.StartsWith("set_")) - len--; - for (int i = 0; i < len; i++) - { - sb.Append(args[i].GetHashCode()); - } - return sb.ToString(); - } - - private void RemoveEvent(MethodInfo method, Delegate subscriber) - { - string eventName = method.Name.Substring(7); - Delegate existing = (MulticastDelegate) eventsSubscribers[eventName]; - existing = MulticastDelegate.Remove(existing, subscriber); - eventsSubscribers[eventName] = existing; - } - - private void AddEvent(MethodInfo method, Delegate subscriber) - { - string eventName = method.Name.Substring(4); - Delegate existing = (MulticastDelegate) eventsSubscribers[eventName]; - existing = MulticastDelegate.Combine(existing, subscriber); - eventsSubscribers[eventName] = existing; - } - } +#region license + +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// This is a dummy type that is used merely to give DynamicProxy the proxy instance that + /// it needs to create IProxy's types. + /// + public class ProxyInstance : MarshalByRefObject, IMockedObject + { + private readonly MockRepository repository; + private readonly int hashCode; + private IList originalMethodsToCall; + private IList propertiesToSimulate; + private IDictionary propertiesValues; + private IDictionary eventsSubscribers; + private readonly Type[] implemented; + + private readonly IDictionary> methodToActualCalls = new Dictionary>(); + private object[] constructorArguments = new object[0]; + private IList dependentMocks = new List(); + + /// + /// Create a new instance of + /// + public ProxyInstance(MockRepository repository, params Type[] implemented) + { + this.repository = repository; + this.implemented = implemented; + hashCode = MockedObjectsEquality.NextHashCode; + } + + /// + /// Mocks that are tied to this mock lifestyle + /// + public IList DependentMocks + { + get { return dependentMocks; } + } + + /// + /// The unique hash code of this proxy, which is not related + /// to the value of the GetHashCode() call on the object. + /// + public int ProxyHash + { + get { return hashCode; } + } + + /// + /// Gets the repository. + /// + public MockRepository Repository + { + get { return repository; } + } + + /// + /// Return true if it should call the original method on the object + /// instead of pass it to the message chain. + /// + /// The method to call + public bool ShouldCallOriginal(MethodInfo method) + { + if (originalMethodsToCall == null) + return false; + return originalMethodsToCall.Contains(method); + } + + /// + /// Register a method to be called on the object directly + /// + public void RegisterMethodForCallingOriginal(MethodInfo method) + { + if (originalMethodsToCall == null) + originalMethodsToCall = new ArrayList(); + originalMethodsToCall.Add(method); + } + + /// + /// Register a property on the object that will behave as a simple property + /// Return true if there is already a value for the property + /// + public bool RegisterPropertyBehaviorFor(PropertyInfo prop) + { + if (propertiesToSimulate == null) + propertiesToSimulate = new ArrayList(); + MethodInfo getMethod = prop.GetGetMethod(true); + MethodInfo setMethod = prop.GetSetMethod(true); + if (propertiesToSimulate.Contains(getMethod) == false) + propertiesToSimulate.Add(getMethod); + if (propertiesToSimulate.Contains(setMethod) == false) + propertiesToSimulate.Add(setMethod); + return propertiesValues!=null && + propertiesValues.Contains(GenerateKey(getMethod, new object[0])); + } + + /// + /// Check if the method was registered as a property method. + /// + public bool IsPropertyMethod(MethodInfo method) + { + if (propertiesToSimulate == null) + return false; + //we have to do it this way, to handle generic types + foreach (MethodInfo info in propertiesToSimulate) + { + if( AreMethodEquals(info, method)) + return true; + } + return false; + } + + private static bool AreMethodEquals(MethodInfo left, MethodInfo right) + { + if (left.Equals(right)) + return true; + // GetHashCode calls to RuntimeMethodHandle.StripMethodInstantiation() + // which is needed to fix issues with method equality from generic types. + if (left.GetHashCode() != right.GetHashCode()) + return false; + if (left.DeclaringType != right.DeclaringType) + return false; + ParameterInfo[] leftParams = left.GetParameters(); + ParameterInfo[] rightParams = right.GetParameters(); + if (leftParams.Length != rightParams.Length) + return false; + for (int i = 0; i < leftParams.Length; i++) + { + if (leftParams[i].ParameterType != rightParams[i].ParameterType) + return false; + } + if (left.ReturnType != right.ReturnType) + return false; + return true; + } + + /// + /// Do get/set on the property, according to need. + /// + public object HandleProperty(MethodInfo method, object[] args) + { + if (propertiesValues == null) + propertiesValues = new Hashtable(); + + if (method.Name.StartsWith("get_")) + { + string key = GenerateKey(method, args); + if (propertiesValues.Contains(key) == false && method.ReturnType.IsValueType) + { + throw new InvalidOperationException( + string.Format( + "Can't return a value for property {0} because no value was set and the Property return a value type.", + method.Name.Substring(4))); + } + return propertiesValues[key]; + } + + object value = args[args.Length - 1]; + propertiesValues[GenerateKey(method, args)] = value; + return null; + } + + + /// + /// Do add/remove on the event + /// + public void HandleEvent(MethodInfo method, object[] args) + { + if (eventsSubscribers == null) + eventsSubscribers = new Hashtable(); + + Delegate subscriber = (Delegate) args[0]; + if (method.Name.StartsWith("add_")) + { + AddEvent(method, subscriber); + } + else + { + RemoveEvent(method, subscriber); + } + } + + /// + /// Get the subscribers of a spesific event + /// + public Delegate GetEventSubscribers(string eventName) + { + if (eventsSubscribers == null) + return null; + return (Delegate) eventsSubscribers[eventName]; + } + + /// + /// Gets the declaring type of the method, taking into acccount the possible generic + /// parameters that it was created with. + /// + public Type GetDeclaringType(MethodInfo info) + { + Type typeDeclaringTheMethod = info.DeclaringType; + foreach (Type type in implemented) + { + if (type == typeDeclaringTheMethod) + return type; + if (typeDeclaringTheMethod.IsGenericType && + typeDeclaringTheMethod == type.GetGenericTypeDefinition()) + return type; + } + return null; + } + + + /// + /// Gets or sets the constructor arguments. + /// + /// The constructor arguments. + public object[] ConstructorArguments + { + get { return constructorArguments; } + set { constructorArguments = value; } + } + + private object mockedObjectInstance; + + /// + /// The mocked instance that this is representing + /// + public object MockedObjectInstance + { + get { return mockedObjectInstance; } + set { mockedObjectInstance = value; } + } + + /// + /// Gets the implemented types by this mocked object + /// + /// The implemented. + public Type[] ImplementedTypes + { + get { return implemented; } + } + + /// + /// Get all the method calls arguments that were made against this object with the specificed + /// method. + /// + /// + /// + /// + /// Only method calls in replay mode are counted + /// + public ICollection GetCallArgumentsFor(MethodInfo method) + { + if (methodToActualCalls.ContainsKey(method) == false) + return new List(); + return methodToActualCalls[method]; + } + + + /// + /// Records the method call + /// + /// + /// + public void MethodCall(MethodInfo method, object[] args) + { + if(repository.IsInReplayMode(this)==false) + return; + if (methodToActualCalls.ContainsKey(method) == false) + methodToActualCalls[method] = new List(); + methodToActualCalls[method].Add(args); + } + + /// + /// Clears the state of the object, remove original calls, property behavior, subscribed events, etc. + /// + public void ClearState(BackToRecordOptions options) + { + if (eventsSubscribers != null && + (options & BackToRecordOptions.EventSubscribers) != 0) + eventsSubscribers.Clear(); + if (originalMethodsToCall != null && + (options & BackToRecordOptions.OriginalMethodsToCall) != 0) + originalMethodsToCall.Clear(); + if (propertiesValues != null && + (options & BackToRecordOptions.PropertyBehavior) != 0) + propertiesValues.Clear(); + if (propertiesToSimulate != null && + (options & BackToRecordOptions.PropertyBehavior) != 0) + propertiesToSimulate.Clear(); + } + + private static string GenerateKey(MethodInfo method, object[] args) + { + var baseName = method.DeclaringType.FullName + method.Name.Substring(4); + if ((method.Name.StartsWith("get_") && args.Length == 0) || + (method.Name.StartsWith("set_") && args.Length == 1)) + return baseName; + StringBuilder sb = new StringBuilder(); + sb.Append(baseName); + int len = args.Length; + if (method.Name.StartsWith("set_")) + len--; + for (int i = 0; i < len; i++) + { + sb.Append(args[i].GetHashCode()); + } + return sb.ToString(); + } + + private void RemoveEvent(MethodInfo method, Delegate subscriber) + { + string eventName = method.Name.Substring(7); + Delegate existing = (MulticastDelegate) eventsSubscribers[eventName]; + existing = MulticastDelegate.Remove(existing, subscriber); + eventsSubscribers[eventName] = existing; + } + + private void AddEvent(MethodInfo method, Delegate subscriber) + { + string eventName = method.Name.Substring(4); + Delegate existing = (MulticastDelegate) eventsSubscribers[eventName]; + existing = MulticastDelegate.Combine(existing, subscriber); + eventsSubscribers[eventName] = existing; + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/Range.cs b/Rhino.Mocks/Impl/Range.cs index e475d0e2..0d149fde 100644 --- a/Rhino.Mocks/Impl/Range.cs +++ b/Rhino.Mocks/Impl/Range.cs @@ -1,83 +1,83 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -namespace Rhino.Mocks.Impl -{ - /// - /// Range for expected method calls - /// - public class Range - { - private int min; - private int? max; - - /// - /// Creates a new instance. - /// - /// Min. - /// Max. - public Range(int min, int? max) - { - this.min = min; - this.max = max; - } - - /// - /// Gets or sets the min. - /// - /// - public int Min - { - get { return min; } - } - - /// - /// Gets or sets the max. - /// - /// - public int? Max - { - get { return max; } - } - - /// - /// Return the string representation of this range. - /// - public override string ToString() - { - if (min == 0) - return max.ToString(); - if (max != null && min != max.Value) - return min + ".." + max; - return min.ToString(); - } - - - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +namespace Rhino.Mocks.Impl +{ + /// + /// Range for expected method calls + /// + public class Range + { + private int min; + private int? max; + + /// + /// Creates a new instance. + /// + /// Min. + /// Max. + public Range(int min, int? max) + { + this.min = min; + this.max = max; + } + + /// + /// Gets or sets the min. + /// + /// + public int Min + { + get { return min; } + } + + /// + /// Gets or sets the max. + /// + /// + public int? Max + { + get { return max; } + } + + /// + /// Return the string representation of this range. + /// + public override string ToString() + { + if (min == 0) + return max.ToString(); + if (max != null && min != max.Value) + return min + ".." + max; + return min.ToString(); + } + + + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/RecordDynamicMockState.cs b/Rhino.Mocks/Impl/RecordDynamicMockState.cs index 59b26596..dcda62c3 100644 --- a/Rhino.Mocks/Impl/RecordDynamicMockState.cs +++ b/Rhino.Mocks/Impl/RecordDynamicMockState.cs @@ -1,77 +1,77 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// Records all the expectations for a mock and - /// return a ReplayDynamicMockState when Replay() - /// is called. - /// - public class RecordDynamicMockState : RecordMockState - { - /// - /// Creates a new instance. - /// - /// Repository. - /// The proxy that generates the method calls - public RecordDynamicMockState(IMockedObject mockedObject, MockRepository repository) : base(mockedObject, repository) - { - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - protected override IMockState DoReplay() - { - return new ReplayDynamicMockState(this); - } - - /// - /// Get the default call count range expectation - /// - /// - protected override Range GetDefaultCallCountRangeExpectation() - { - return new Range(1, null); - } - - /// - /// Gets a mock state that match the original mock state of the object. - /// - public override IMockState BackToRecord() - { - return new RecordDynamicMockState(this.Proxy, Repository); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// Records all the expectations for a mock and + /// return a ReplayDynamicMockState when Replay() + /// is called. + /// + public class RecordDynamicMockState : RecordMockState + { + /// + /// Creates a new instance. + /// + /// Repository. + /// The proxy that generates the method calls + public RecordDynamicMockState(IMockedObject mockedObject, MockRepository repository) : base(mockedObject, repository) + { + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + protected override IMockState DoReplay() + { + return new ReplayDynamicMockState(this); + } + + /// + /// Get the default call count range expectation + /// + /// + protected override Range GetDefaultCallCountRangeExpectation() + { + return new Range(1, null); + } + + /// + /// Gets a mock state that match the original mock state of the object. + /// + public override IMockState BackToRecord() + { + return new RecordDynamicMockState(this.Proxy, Repository); + } + } +} diff --git a/Rhino.Mocks/Impl/RecordMockState.cs b/Rhino.Mocks/Impl/RecordMockState.cs index 99625c53..edca3f76 100644 --- a/Rhino.Mocks/Impl/RecordMockState.cs +++ b/Rhino.Mocks/Impl/RecordMockState.cs @@ -1,348 +1,348 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Constraints; -using Rhino.Mocks.Expectations; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Impl -{ - /// - /// Records all the expectations for a mock - /// - public class RecordMockState : IMockState - { - #region Variables - - private MockRepository repository; - private readonly IMockedObject mockedObject; - private int methodCallsCount = 0; - private IExpectation lastExpectation; - private bool lastCallWasPropertyBehavior; - - #endregion - - #region Properties - - /// - /// Gets the last expectation. - /// - public IExpectation LastExpectation - { - get { return lastExpectation; } - set - { - lastCallWasPropertyBehavior = false; - lastExpectation = value; - } - } - - /// - /// Gets the total method calls count. - /// - public int MethodCallsCount - { - get { return methodCallsCount; } - } - - /// - /// Get the options for the last method call - /// - public IMethodOptions GetLastMethodOptions() - { - if(lastCallWasPropertyBehavior) - { - string message = - @"You are trying to set an expectation on a property that was defined to use PropertyBehavior. -Instead of writing code such as this: mockObject.Stub(x => x.SomeProperty).Return(42); -You can use the property directly to achieve the same result: mockObject.SomeProperty = 42;"; - throw new InvalidOperationException(message); - } - if (LastExpectation == null) - throw new InvalidOperationException("There is no matching last call on this object. Are you sure that the last call was a virtual or interface method call?"); - return new MethodOptions(repository, this, mockedObject, LastExpectation); - } - - /// - /// Get the options for the last method call - /// - public IMethodOptions LastMethodOptions - { - get { return GetLastMethodOptions(); } - } - - /// - /// 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. - /// - public void SetExceptionToThrowOnVerify(Exception ex) - { - //not implementing this, since there is never a call to Verify() anyway. - } - - /// - /// 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(). - /// - public void NotifyCallOnPropertyBehavior() - { - LastExpectation = null; - lastCallWasPropertyBehavior = true; - } - - /// - /// Gets the matching verify state for this state - /// - public IMockState VerifyState - { - get { throw InvalidOperationOnRecord(); } - } - - #endregion - - #region C'tor - - /// - /// Creates a new instance. - /// - /// Repository. - /// The proxy that generates the method calls - public RecordMockState(IMockedObject mockedObject, MockRepository repository) - { - Validate.IsNotNull(mockedObject, "proxy"); - Validate.IsNotNull(repository, "repository"); - this.repository = repository; - this.mockedObject = mockedObject; - } - - #endregion - - #region Methods - - /// - /// 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 - public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args) - { - try - { - AssertPreviousMethodIsClose(); - repository.lastMockedObject = mockedObject; - MockRepository.lastRepository = repository; - IExpectation expectation; - - // Has the Arg class been used? - if (ArgManager.HasBeenUsed) - { - expectation = BuildParamExpectation(invocation, method); - } - else - { - expectation = BuildDefaultExpectation(invocation, method, args); - } - repository.Recorder.Record(mockedObject, method, expectation); - LastExpectation = expectation; - methodCallsCount++; - RhinoMocks.Logger.LogRecordedExpectation(invocation, expectation); - object returnValue; - if (TryCreateReturnValue(expectation, out returnValue)) - return returnValue; - return ReturnValueUtil.DefaultValue(method.ReturnType, invocation); - } - finally - { - // Consume the Arg constraints only once, and reset it after each call. - // this is in the finally block to make sure that an exeption does not - // make subsequent unit tests fail. - ArgManager.Clear(); - } - } - - private bool TryCreateReturnValue(IExpectation expectation, out object returnValue) - { - returnValue = null; - - //use already created instance if any - if (mockedObject.DependentMocks != null && mockedObject.DependentMocks.Count > 0) - { - foreach (IMockedObject dependentMock in mockedObject.DependentMocks) - { - if (dependentMock.ImplementedTypes != null && dependentMock.ImplementedTypes.Length > 0) - { - foreach (Type type in dependentMock.ImplementedTypes) - { - if (type == expectation.Method.ReturnType) - { - returnValue = dependentMock.MockedObjectInstance; - return true; - } - } - } - } - return false; - } - //create new instance - try - { - returnValue = Repository.DynamicMock(expectation.Method.ReturnType); - } - catch (Exception) - { - // couldn't create mock object for it, we fall back to returning a default value - returnValue = null; - return false; - } - - mockedObject.DependentMocks.Add(MockRepository.GetMockedObject(returnValue)); - - expectation.ReturnValue = returnValue; - expectation.AllowTentativeReturn = true; - - return true; - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - public virtual IMockState Replay() - { - AssertPreviousMethodIsClose(); - return DoReplay(); - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - protected virtual IMockState DoReplay() - { - return new ReplayMockState(this); - } - - /// - /// Verify that this mock expectations have passed. - /// - public virtual void Verify() - { - throw InvalidOperationOnRecord(); - } - - /// - /// Gets a mock state that match the original mock state of the object. - /// - public virtual IMockState BackToRecord() - { - return new RecordMockState(mockedObject, repository); - } - - #endregion - - #region Private Methods - - /// - /// Asserts the previous method is closed (had an expectation set on it so we can replay it correctly) - /// - protected virtual void AssertPreviousMethodIsClose() - { - if (LastExpectation != null && !LastExpectation.ActionsSatisfied) - throw new InvalidOperationException("Previous method '" + LastExpectation.ErrorMessage + "' requires a return value or an exception to throw."); - } - - private Exception InvalidOperationOnRecord() - { - // Format the mock types into a string for display in the exception message, - // using the pattern {Namespace.IType1, Namespace.IType2}. - string mockedTypes = string.Empty; - if (this.mockedObject.ImplementedTypes.Length > 0) { - mockedTypes = string.Format("{{{0}}} ", string.Join(", ", Array.ConvertAll(this.mockedObject.ImplementedTypes, delegate(Type ty) { return ty.FullName; }))); - } - - return new InvalidOperationException(string.Format("This action is invalid when the mock object {0}is in record state.", mockedTypes)); - } - - private IExpectation BuildDefaultExpectation(IInvocation invocation, MethodInfo method, object[] args) - { - ParameterInfo[] parameters = method.GetParameters(); - if (!Array.Exists(parameters, delegate(ParameterInfo p) { return p.IsOut; })) - { - return new ArgsEqualExpectation(invocation, args, GetDefaultCallCountRangeExpectation()); - } - - //The value of an incoming out parameter variable is ignored - AbstractConstraint[] constraints = new AbstractConstraint[parameters.Length]; - for (int i = 0; i < parameters.Length; i++) - { - constraints[i] = parameters[i].IsOut ? Is.Anything() : Is.Equal(args[i]); - } - return new ConstraintsExpectation(invocation, constraints, GetDefaultCallCountRangeExpectation()); - } - - /// - /// Get the default call count range expectation - /// - /// - protected virtual Range GetDefaultCallCountRangeExpectation() - { - return new Range(1, 1); - } - - private static IExpectation BuildParamExpectation(IInvocation invocation, MethodInfo method) - { - ArgManager.CheckMethodSignature(method); - IExpectation expectation = new ConstraintsExpectation(invocation, ArgManager.GetAllConstraints(), new Range(1, null)); - expectation.OutRefParams = ArgManager.GetAllReturnValues(); - return expectation; - } - - #endregion - - #region Internal - internal MockRepository Repository - { - get { return repository; } - } - - internal IMockedObject Proxy - { - get { return mockedObject; } - } - - #endregion - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Constraints; +using Rhino.Mocks.Expectations; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Impl +{ + /// + /// Records all the expectations for a mock + /// + public class RecordMockState : IMockState + { + #region Variables + + private MockRepository repository; + private readonly IMockedObject mockedObject; + private int methodCallsCount = 0; + private IExpectation lastExpectation; + private bool lastCallWasPropertyBehavior; + + #endregion + + #region Properties + + /// + /// Gets the last expectation. + /// + public IExpectation LastExpectation + { + get { return lastExpectation; } + set + { + lastCallWasPropertyBehavior = false; + lastExpectation = value; + } + } + + /// + /// Gets the total method calls count. + /// + public int MethodCallsCount + { + get { return methodCallsCount; } + } + + /// + /// Get the options for the last method call + /// + public IMethodOptions GetLastMethodOptions() + { + if(lastCallWasPropertyBehavior) + { + string message = + @"You are trying to set an expectation on a property that was defined to use PropertyBehavior. +Instead of writing code such as this: mockObject.Stub(x => x.SomeProperty).Return(42); +You can use the property directly to achieve the same result: mockObject.SomeProperty = 42;"; + throw new InvalidOperationException(message); + } + if (LastExpectation == null) + throw new InvalidOperationException("There is no matching last call on this object. Are you sure that the last call was a virtual or interface method call?"); + return new MethodOptions(repository, this, mockedObject, LastExpectation); + } + + /// + /// Get the options for the last method call + /// + public IMethodOptions LastMethodOptions + { + get { return GetLastMethodOptions(); } + } + + /// + /// 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. + /// + public void SetExceptionToThrowOnVerify(Exception ex) + { + //not implementing this, since there is never a call to Verify() anyway. + } + + /// + /// 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(). + /// + public void NotifyCallOnPropertyBehavior() + { + LastExpectation = null; + lastCallWasPropertyBehavior = true; + } + + /// + /// Gets the matching verify state for this state + /// + public IMockState VerifyState + { + get { throw InvalidOperationOnRecord(); } + } + + #endregion + + #region C'tor + + /// + /// Creates a new instance. + /// + /// Repository. + /// The proxy that generates the method calls + public RecordMockState(IMockedObject mockedObject, MockRepository repository) + { + Validate.IsNotNull(mockedObject, "proxy"); + Validate.IsNotNull(repository, "repository"); + this.repository = repository; + this.mockedObject = mockedObject; + } + + #endregion + + #region Methods + + /// + /// 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 + public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args) + { + try + { + AssertPreviousMethodIsClose(); + repository.lastMockedObject = mockedObject; + MockRepository.lastRepository = repository; + IExpectation expectation; + + // Has the Arg class been used? + if (ArgManager.HasBeenUsed) + { + expectation = BuildParamExpectation(invocation, method); + } + else + { + expectation = BuildDefaultExpectation(invocation, method, args); + } + repository.Recorder.Record(mockedObject, method, expectation); + LastExpectation = expectation; + methodCallsCount++; + RhinoMocks.Logger.LogRecordedExpectation(invocation, expectation); + object returnValue; + if (TryCreateReturnValue(expectation, out returnValue)) + return returnValue; + return ReturnValueUtil.DefaultValue(method.ReturnType, invocation); + } + finally + { + // Consume the Arg constraints only once, and reset it after each call. + // this is in the finally block to make sure that an exeption does not + // make subsequent unit tests fail. + ArgManager.Clear(); + } + } + + private bool TryCreateReturnValue(IExpectation expectation, out object returnValue) + { + returnValue = null; + + //use already created instance if any + if (mockedObject.DependentMocks != null && mockedObject.DependentMocks.Count > 0) + { + foreach (IMockedObject dependentMock in mockedObject.DependentMocks) + { + if (dependentMock.ImplementedTypes != null && dependentMock.ImplementedTypes.Length > 0) + { + foreach (Type type in dependentMock.ImplementedTypes) + { + if (type == expectation.Method.ReturnType) + { + returnValue = dependentMock.MockedObjectInstance; + return true; + } + } + } + } + return false; + } + //create new instance + try + { + returnValue = Repository.DynamicMock(expectation.Method.ReturnType); + } + catch (Exception) + { + // couldn't create mock object for it, we fall back to returning a default value + returnValue = null; + return false; + } + + mockedObject.DependentMocks.Add(MockRepository.GetMockedObject(returnValue)); + + expectation.ReturnValue = returnValue; + expectation.AllowTentativeReturn = true; + + return true; + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + public virtual IMockState Replay() + { + AssertPreviousMethodIsClose(); + return DoReplay(); + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + protected virtual IMockState DoReplay() + { + return new ReplayMockState(this); + } + + /// + /// Verify that this mock expectations have passed. + /// + public virtual void Verify() + { + throw InvalidOperationOnRecord(); + } + + /// + /// Gets a mock state that match the original mock state of the object. + /// + public virtual IMockState BackToRecord() + { + return new RecordMockState(mockedObject, repository); + } + + #endregion + + #region Private Methods + + /// + /// Asserts the previous method is closed (had an expectation set on it so we can replay it correctly) + /// + protected virtual void AssertPreviousMethodIsClose() + { + if (LastExpectation != null && !LastExpectation.ActionsSatisfied) + throw new InvalidOperationException("Previous method '" + LastExpectation.ErrorMessage + "' requires a return value or an exception to throw."); + } + + private Exception InvalidOperationOnRecord() + { + // Format the mock types into a string for display in the exception message, + // using the pattern {Namespace.IType1, Namespace.IType2}. + string mockedTypes = string.Empty; + if (this.mockedObject.ImplementedTypes.Length > 0) { + mockedTypes = string.Format("{{{0}}} ", string.Join(", ", Array.ConvertAll(this.mockedObject.ImplementedTypes, delegate(Type ty) { return ty.FullName; }))); + } + + return new InvalidOperationException(string.Format("This action is invalid when the mock object {0}is in record state.", mockedTypes)); + } + + private IExpectation BuildDefaultExpectation(IInvocation invocation, MethodInfo method, object[] args) + { + ParameterInfo[] parameters = method.GetParameters(); + if (!Array.Exists(parameters, delegate(ParameterInfo p) { return p.IsOut; })) + { + return new ArgsEqualExpectation(invocation, args, GetDefaultCallCountRangeExpectation()); + } + + //The value of an incoming out parameter variable is ignored + AbstractConstraint[] constraints = new AbstractConstraint[parameters.Length]; + for (int i = 0; i < parameters.Length; i++) + { + constraints[i] = parameters[i].IsOut ? Is.Anything() : Is.Equal(args[i]); + } + return new ConstraintsExpectation(invocation, constraints, GetDefaultCallCountRangeExpectation()); + } + + /// + /// Get the default call count range expectation + /// + /// + protected virtual Range GetDefaultCallCountRangeExpectation() + { + return new Range(1, 1); + } + + private static IExpectation BuildParamExpectation(IInvocation invocation, MethodInfo method) + { + ArgManager.CheckMethodSignature(method); + IExpectation expectation = new ConstraintsExpectation(invocation, ArgManager.GetAllConstraints(), new Range(1, null)); + expectation.OutRefParams = ArgManager.GetAllReturnValues(); + return expectation; + } + + #endregion + + #region Internal + internal MockRepository Repository + { + get { return repository; } + } + + internal IMockedObject Proxy + { + get { return mockedObject; } + } + + #endregion + } +} diff --git a/Rhino.Mocks/Impl/RecordPartialMockState.cs b/Rhino.Mocks/Impl/RecordPartialMockState.cs index f7685846..75cb6b2c 100644 --- a/Rhino.Mocks/Impl/RecordPartialMockState.cs +++ b/Rhino.Mocks/Impl/RecordPartialMockState.cs @@ -1,69 +1,69 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// Records all the expectations for a mock and - /// return a ReplayPartialMockState when Replay() - /// is called. - /// - public class RecordPartialMockState : RecordMockState - { - /// - /// Creates a new instance. - /// - /// Repository. - /// The proxy that generates the method calls - public RecordPartialMockState(IMockedObject mockedObject, MockRepository repository) - : base(mockedObject, repository) - { - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - protected override IMockState DoReplay() - { - return new ReplayPartialMockState(this); - } - - - /// - /// Gets a mock state that matches the original mock state of the object. - /// - public override IMockState BackToRecord() - { - return new RecordPartialMockState(this.Proxy, Repository); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// Records all the expectations for a mock and + /// return a ReplayPartialMockState when Replay() + /// is called. + /// + public class RecordPartialMockState : RecordMockState + { + /// + /// Creates a new instance. + /// + /// Repository. + /// The proxy that generates the method calls + public RecordPartialMockState(IMockedObject mockedObject, MockRepository repository) + : base(mockedObject, repository) + { + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + protected override IMockState DoReplay() + { + return new ReplayPartialMockState(this); + } + + + /// + /// Gets a mock state that matches the original mock state of the object. + /// + public override IMockState BackToRecord() + { + return new RecordPartialMockState(this.Proxy, Repository); + } + } +} diff --git a/Rhino.Mocks/Impl/RemotingMock/IRemotingProxyOperation.cs b/Rhino.Mocks/Impl/RemotingMock/IRemotingProxyOperation.cs index d9427823..d72fe03c 100644 --- a/Rhino.Mocks/Impl/RemotingMock/IRemotingProxyOperation.cs +++ b/Rhino.Mocks/Impl/RemotingMock/IRemotingProxyOperation.cs @@ -1,27 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Rhino.Mocks.Impl.RemotingMock -{ - /// - /// 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. - /// - internal interface IRemotingProxyOperation - { - void Process(RemotingProxy proxy); - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rhino.Mocks.Impl.RemotingMock +{ + /// + /// 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. + /// + internal interface IRemotingProxyOperation + { + void Process(RemotingProxy proxy); + } +} diff --git a/Rhino.Mocks/Impl/RemotingMock/RemotingInvocation.cs b/Rhino.Mocks/Impl/RemotingMock/RemotingInvocation.cs index 89fc1e0a..a92914ed 100644 --- a/Rhino.Mocks/Impl/RemotingMock/RemotingInvocation.cs +++ b/Rhino.Mocks/Impl/RemotingMock/RemotingInvocation.cs @@ -1,105 +1,105 @@ -using System; - -namespace Rhino.Mocks.Impl.RemotingMock -{ - using System; - using System.Reflection; - using System.Runtime.Remoting.Messaging; - using System.Runtime.Remoting.Proxies; - using Castle.Core.Interceptor; - - /// - /// 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 - internal class RemotingInvocation : IInvocation - { - private readonly IMethodCallMessage _message; - private object _returnValue; - private readonly RealProxy _realProxy; - private object[] _args; - - public RemotingInvocation(RealProxy realProxy, IMethodCallMessage message) - { - _message = message; - _realProxy = realProxy; - this._args = (object[])this._message.Properties["__Args"]; - } - - public object[] Arguments - { - get { return _args; } - } - - public Type[] GenericArguments - { - get - { - MethodBase method = _message.MethodBase; - if (!method.IsGenericMethod) - { - return new Type[0]; - } - - return method.GetGenericArguments(); - } - } - - public object GetArgumentValue(int index) - { - throw new NotSupportedException(); - } - - public MethodInfo GetConcreteMethod() - { - return (MethodInfo)_message.MethodBase; - } - - public MethodInfo GetConcreteMethodInvocationTarget() - { - throw new NotSupportedException(); - } - - public object InvocationTarget - { - get { throw new NotSupportedException(); } - } - - public MethodInfo Method - { - get { return GetConcreteMethod(); } - } - - public MethodInfo MethodInvocationTarget - { - get { throw new NotSupportedException(); } - } - - public void Proceed() - { - throw new InvalidOperationException("Proceed() is not applicable to remoting mocks."); - } - - public object Proxy - { - get { return _realProxy.GetTransparentProxy(); } - } - - public object ReturnValue - { - get { return _returnValue; } - set { _returnValue = value; } - } - - public void SetArgumentValue(int index, object value) - { - throw new NotSupportedException(); - } - - public Type TargetType - { - get { throw new NotSupportedException(); } - } - } -} +using System; + +namespace Rhino.Mocks.Impl.RemotingMock +{ + using System; + using System.Reflection; + using System.Runtime.Remoting.Messaging; + using System.Runtime.Remoting.Proxies; + using Castle.Core.Interceptor; + + /// + /// 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 + internal class RemotingInvocation : IInvocation + { + private readonly IMethodCallMessage _message; + private object _returnValue; + private readonly RealProxy _realProxy; + private object[] _args; + + public RemotingInvocation(RealProxy realProxy, IMethodCallMessage message) + { + _message = message; + _realProxy = realProxy; + this._args = (object[])this._message.Properties["__Args"]; + } + + public object[] Arguments + { + get { return _args; } + } + + public Type[] GenericArguments + { + get + { + MethodBase method = _message.MethodBase; + if (!method.IsGenericMethod) + { + return new Type[0]; + } + + return method.GetGenericArguments(); + } + } + + public object GetArgumentValue(int index) + { + throw new NotSupportedException(); + } + + public MethodInfo GetConcreteMethod() + { + return (MethodInfo)_message.MethodBase; + } + + public MethodInfo GetConcreteMethodInvocationTarget() + { + throw new NotSupportedException(); + } + + public object InvocationTarget + { + get { throw new NotSupportedException(); } + } + + public MethodInfo Method + { + get { return GetConcreteMethod(); } + } + + public MethodInfo MethodInvocationTarget + { + get { throw new NotSupportedException(); } + } + + public void Proceed() + { + throw new InvalidOperationException("Proceed() is not applicable to remoting mocks."); + } + + public object Proxy + { + get { return _realProxy.GetTransparentProxy(); } + } + + public object ReturnValue + { + get { return _returnValue; } + set { _returnValue = value; } + } + + public void SetArgumentValue(int index, object value) + { + throw new NotSupportedException(); + } + + public Type TargetType + { + get { throw new NotSupportedException(); } + } + } +} diff --git a/Rhino.Mocks/Impl/RemotingMock/RemotingMockGenerator.cs b/Rhino.Mocks/Impl/RemotingMock/RemotingMockGenerator.cs index 85e87f31..632e0b67 100644 --- a/Rhino.Mocks/Impl/RemotingMock/RemotingMockGenerator.cs +++ b/Rhino.Mocks/Impl/RemotingMock/RemotingMockGenerator.cs @@ -1,56 +1,56 @@ -namespace Rhino.Mocks.Impl.RemotingMock -{ - using System; - using Rhino.Mocks.Interfaces; - using Castle.Core.Interceptor; - - /// - /// Generates remoting proxies and provides utility functions - /// - internal class RemotingMockGenerator - { - /// - /// Create the proxy using remoting - /// - public object CreateRemotingMock(Type type, IInterceptor interceptor, IMockedObject mockedObject) - { - if (type.IsInterface == false && !typeof(MarshalByRefObject).IsAssignableFrom(type)) - { - throw new InvalidCastException( - String.Format("Cannot create remoting proxy. '{0}' is not derived from MarshalByRefObject", type.Name)); - } - - return new RemotingProxy(type, interceptor, mockedObject).GetTransparentProxy(); - } - - /// - /// 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 - public static bool IsRemotingProxy(object obj) - { - if (obj == null) return false; - RemotingProxyDetector detector = new RemotingProxyDetector(); - obj.Equals(detector); - return detector.Detected; - } - - /// - /// 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 - public static IMockedObject GetMockedObjectFromProxy(object proxy) - { - if (proxy == null) return null; - RemotingProxyMockedObjectGetter getter = new RemotingProxyMockedObjectGetter(); - proxy.Equals(getter); - return getter.MockedObject; - } - } -} +namespace Rhino.Mocks.Impl.RemotingMock +{ + using System; + using Rhino.Mocks.Interfaces; + using Castle.Core.Interceptor; + + /// + /// Generates remoting proxies and provides utility functions + /// + internal class RemotingMockGenerator + { + /// + /// Create the proxy using remoting + /// + public object CreateRemotingMock(Type type, IInterceptor interceptor, IMockedObject mockedObject) + { + if (type.IsInterface == false && !typeof(MarshalByRefObject).IsAssignableFrom(type)) + { + throw new InvalidCastException( + String.Format("Cannot create remoting proxy. '{0}' is not derived from MarshalByRefObject", type.Name)); + } + + return new RemotingProxy(type, interceptor, mockedObject).GetTransparentProxy(); + } + + /// + /// 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 + public static bool IsRemotingProxy(object obj) + { + if (obj == null) return false; + RemotingProxyDetector detector = new RemotingProxyDetector(); + obj.Equals(detector); + return detector.Detected; + } + + /// + /// 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 + public static IMockedObject GetMockedObjectFromProxy(object proxy) + { + if (proxy == null) return null; + RemotingProxyMockedObjectGetter getter = new RemotingProxyMockedObjectGetter(); + proxy.Equals(getter); + return getter.MockedObject; + } + } +} diff --git a/Rhino.Mocks/Impl/RemotingMock/RemotingProxy.cs b/Rhino.Mocks/Impl/RemotingMock/RemotingProxy.cs index ed9e9992..767d908c 100644 --- a/Rhino.Mocks/Impl/RemotingMock/RemotingProxy.cs +++ b/Rhino.Mocks/Impl/RemotingMock/RemotingProxy.cs @@ -1,119 +1,119 @@ -namespace Rhino.Mocks.Impl.RemotingMock -{ - using System; - using System.Reflection; - using System.Runtime.Remoting.Messaging; - using System.Runtime.Remoting.Proxies; - using Castle.Core.Interceptor; - using Rhino.Mocks.Interfaces; - - internal class RemotingProxy : RealProxy - { - private readonly IInterceptor _interceptor; - private readonly IMockedObject _mockedObject; - - public RemotingProxy(Type type, IInterceptor interceptor, IMockedObject mockedObject) - : - base(type) - { - _interceptor = interceptor; - _mockedObject = mockedObject; - } - - public IMockedObject MockedObject - { - get { return _mockedObject; } - } - - private static IMessage ReturnValue(object value, object[] outParams, IMethodCallMessage mcm) - { - return new ReturnMessage(value, outParams, outParams == null ? 0 : outParams.Length, mcm.LogicalCallContext, mcm); - } - - public override IMessage Invoke(IMessage msg) - { - IMethodCallMessage mcm = msg as IMethodCallMessage; - if (mcm == null) return null; - - if (IsEqualsMethod(mcm)) - { - return ReturnValue(HandleEquals(mcm), mcm); - } - - if (IsGetHashCodeMethod(mcm)) - { - return ReturnValue(GetHashCode(), mcm); - } - - if (IsGetTypeMethod(mcm)) - { - return ReturnValue(GetProxiedType(), mcm); - } - - if (IsToStringMethod(mcm)) - { - string retVal = String.Format("RemotingMock_{1}<{0}>", this.GetProxiedType().Name, this.GetHashCode()); - return ReturnValue(retVal, mcm); - } - - RemotingInvocation invocation = new RemotingInvocation(this, mcm); - _interceptor.Intercept(invocation); - - return ReturnValue(invocation.ReturnValue, invocation.Arguments, mcm); - } - - private bool IsGetTypeMethod(IMethodCallMessage mcm) - { - if (mcm.MethodName != "GetType") return false; - if (mcm.MethodBase.DeclaringType != typeof(object)) return false; - Type[] args = mcm.MethodSignature as Type[]; - if (args == null) return false; - return args.Length == 0; - } - - private static bool IsEqualsMethod(IMethodMessage mcm) - { - if (mcm.MethodName != "Equals") return false; - Type[] argTypes = mcm.MethodSignature as Type[]; - if (argTypes == null) return false; - if (argTypes.Length == 1 && argTypes[0] == typeof(object)) return true; - return false; - } - - private static bool IsGetHashCodeMethod(IMethodMessage mcm) - { - if (mcm.MethodName != "GetHashCode") return false; - Type[] argTypes = mcm.MethodSignature as Type[]; - if (argTypes == null) return false; - return (argTypes.Length == 0); - } - - private static bool IsToStringMethod(IMethodCallMessage mcm) - { - if (mcm.MethodName != "ToString") return false; - Type[] args = mcm.MethodSignature as Type[]; - if (args == null) return false; - return args.Length == 0; - } - - - private bool HandleEquals(IMethodMessage mcm) - { - object another = mcm.Args[0]; - if (another == null) return false; - - if (another is IRemotingProxyOperation) - { - ((IRemotingProxyOperation)another).Process(this); - return false; - } - - return ReferenceEquals(GetTransparentProxy(), another); - } - - private static IMessage ReturnValue(object value, IMethodCallMessage mcm) - { - return new ReturnMessage(value, null, 0, mcm.LogicalCallContext, mcm); - } - } -} +namespace Rhino.Mocks.Impl.RemotingMock +{ + using System; + using System.Reflection; + using System.Runtime.Remoting.Messaging; + using System.Runtime.Remoting.Proxies; + using Castle.Core.Interceptor; + using Rhino.Mocks.Interfaces; + + internal class RemotingProxy : RealProxy + { + private readonly IInterceptor _interceptor; + private readonly IMockedObject _mockedObject; + + public RemotingProxy(Type type, IInterceptor interceptor, IMockedObject mockedObject) + : + base(type) + { + _interceptor = interceptor; + _mockedObject = mockedObject; + } + + public IMockedObject MockedObject + { + get { return _mockedObject; } + } + + private static IMessage ReturnValue(object value, object[] outParams, IMethodCallMessage mcm) + { + return new ReturnMessage(value, outParams, outParams == null ? 0 : outParams.Length, mcm.LogicalCallContext, mcm); + } + + public override IMessage Invoke(IMessage msg) + { + IMethodCallMessage mcm = msg as IMethodCallMessage; + if (mcm == null) return null; + + if (IsEqualsMethod(mcm)) + { + return ReturnValue(HandleEquals(mcm), mcm); + } + + if (IsGetHashCodeMethod(mcm)) + { + return ReturnValue(GetHashCode(), mcm); + } + + if (IsGetTypeMethod(mcm)) + { + return ReturnValue(GetProxiedType(), mcm); + } + + if (IsToStringMethod(mcm)) + { + string retVal = String.Format("RemotingMock_{1}<{0}>", this.GetProxiedType().Name, this.GetHashCode()); + return ReturnValue(retVal, mcm); + } + + RemotingInvocation invocation = new RemotingInvocation(this, mcm); + _interceptor.Intercept(invocation); + + return ReturnValue(invocation.ReturnValue, invocation.Arguments, mcm); + } + + private bool IsGetTypeMethod(IMethodCallMessage mcm) + { + if (mcm.MethodName != "GetType") return false; + if (mcm.MethodBase.DeclaringType != typeof(object)) return false; + Type[] args = mcm.MethodSignature as Type[]; + if (args == null) return false; + return args.Length == 0; + } + + private static bool IsEqualsMethod(IMethodMessage mcm) + { + if (mcm.MethodName != "Equals") return false; + Type[] argTypes = mcm.MethodSignature as Type[]; + if (argTypes == null) return false; + if (argTypes.Length == 1 && argTypes[0] == typeof(object)) return true; + return false; + } + + private static bool IsGetHashCodeMethod(IMethodMessage mcm) + { + if (mcm.MethodName != "GetHashCode") return false; + Type[] argTypes = mcm.MethodSignature as Type[]; + if (argTypes == null) return false; + return (argTypes.Length == 0); + } + + private static bool IsToStringMethod(IMethodCallMessage mcm) + { + if (mcm.MethodName != "ToString") return false; + Type[] args = mcm.MethodSignature as Type[]; + if (args == null) return false; + return args.Length == 0; + } + + + private bool HandleEquals(IMethodMessage mcm) + { + object another = mcm.Args[0]; + if (another == null) return false; + + if (another is IRemotingProxyOperation) + { + ((IRemotingProxyOperation)another).Process(this); + return false; + } + + return ReferenceEquals(GetTransparentProxy(), another); + } + + private static IMessage ReturnValue(object value, IMethodCallMessage mcm) + { + return new ReturnMessage(value, null, 0, mcm.LogicalCallContext, mcm); + } + } +} diff --git a/Rhino.Mocks/Impl/RemotingMock/RemotingProxyDetector.cs b/Rhino.Mocks/Impl/RemotingMock/RemotingProxyDetector.cs index f1ad470c..3053cfbb 100644 --- a/Rhino.Mocks/Impl/RemotingMock/RemotingProxyDetector.cs +++ b/Rhino.Mocks/Impl/RemotingMock/RemotingProxyDetector.cs @@ -1,21 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Rhino.Mocks.Impl.RemotingMock -{ - internal class RemotingProxyDetector : IRemotingProxyOperation - { - bool _detected = false; - - public bool Detected - { - get { return _detected; } - } - - public void Process(RemotingProxy proxy) - { - _detected = true; - } - } -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rhino.Mocks.Impl.RemotingMock +{ + internal class RemotingProxyDetector : IRemotingProxyOperation + { + bool _detected = false; + + public bool Detected + { + get { return _detected; } + } + + public void Process(RemotingProxy proxy) + { + _detected = true; + } + } +} diff --git a/Rhino.Mocks/Impl/RemotingMock/RemotingProxyMockedObjectGetter.cs b/Rhino.Mocks/Impl/RemotingMock/RemotingProxyMockedObjectGetter.cs index f47cd0ce..02eeeccc 100644 --- a/Rhino.Mocks/Impl/RemotingMock/RemotingProxyMockedObjectGetter.cs +++ b/Rhino.Mocks/Impl/RemotingMock/RemotingProxyMockedObjectGetter.cs @@ -1,19 +1,19 @@ -namespace Rhino.Mocks.Impl.RemotingMock -{ - using Rhino.Mocks.Interfaces; - - class RemotingProxyMockedObjectGetter : IRemotingProxyOperation - { - IMockedObject _mockedObject; - - public IMockedObject MockedObject - { - get { return _mockedObject; } - } - - public void Process(RemotingProxy proxy) - { - _mockedObject = proxy.MockedObject; - } - } -} +namespace Rhino.Mocks.Impl.RemotingMock +{ + using Rhino.Mocks.Interfaces; + + class RemotingProxyMockedObjectGetter : IRemotingProxyOperation + { + IMockedObject _mockedObject; + + public IMockedObject MockedObject + { + get { return _mockedObject; } + } + + public void Process(RemotingProxy proxy) + { + _mockedObject = proxy.MockedObject; + } + } +} diff --git a/Rhino.Mocks/Impl/RepeatableOption.cs b/Rhino.Mocks/Impl/RepeatableOption.cs index 8e8e23a0..5a17b207 100644 --- a/Rhino.Mocks/Impl/RepeatableOption.cs +++ b/Rhino.Mocks/Impl/RepeatableOption.cs @@ -1,64 +1,64 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; - -namespace Rhino.Mocks.Impl -{ - /// - /// Options for special repeat option - /// - public enum RepeatableOption - { - /// - /// This method can be called only as many times as the IMethodOptions.Expect allows. - /// - Normal, - /// - /// This method should never be called - /// - Never, - /// - /// This method can be call any number of times - /// - Any, - /// - /// This method will call the original method - /// - OriginalCall, - /// - /// This method will call the original method, bypassing the mocking layer - /// - OriginalCallBypassingMocking, - /// - /// This method will simulate simple property behavior - /// - PropertyBehavior - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; + +namespace Rhino.Mocks.Impl +{ + /// + /// Options for special repeat option + /// + public enum RepeatableOption + { + /// + /// This method can be called only as many times as the IMethodOptions.Expect allows. + /// + Normal, + /// + /// This method should never be called + /// + Never, + /// + /// This method can be call any number of times + /// + Any, + /// + /// This method will call the original method + /// + OriginalCall, + /// + /// This method will call the original method, bypassing the mocking layer + /// + OriginalCallBypassingMocking, + /// + /// This method will simulate simple property behavior + /// + PropertyBehavior + } +} diff --git a/Rhino.Mocks/Impl/ReplayDynamicMockState.cs b/Rhino.Mocks/Impl/ReplayDynamicMockState.cs index 14e39444..10666ba6 100644 --- a/Rhino.Mocks/Impl/ReplayDynamicMockState.cs +++ b/Rhino.Mocks/Impl/ReplayDynamicMockState.cs @@ -1,82 +1,82 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; -using Castle.DynamicProxy; - -namespace Rhino.Mocks.Impl -{ - /// - /// Validate all expectations on a mock and ignores calls to - /// any method that was not setup properly. - /// - public class ReplayDynamicMockState : ReplayMockState - { - /// - /// Creates a new instance. - /// - /// The previous state for this method - public ReplayDynamicMockState(RecordDynamicMockState previousState):base(previousState) - {} - - /// - /// 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 - protected override object DoMethodCall(IInvocation invocation, MethodInfo method, params object[] args) - { - IExpectation expectation = repository.Replayer.GetRecordedExpectationOrNull(proxy, method, args); - if (expectation != null) - { - RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); - return expectation.ReturnOrThrow(invocation,args); - } - else - { - RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Dynamic Mock: Unexpected method call ignored"); - return ReturnValueUtil.DefaultValue(method.ReturnType, invocation); - } - - } - - /// - /// Gets a mock state that match the original mock state of the object. - /// - public override IMockState BackToRecord() - { - return new RecordDynamicMockState(proxy, repository); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; +using Castle.DynamicProxy; + +namespace Rhino.Mocks.Impl +{ + /// + /// Validate all expectations on a mock and ignores calls to + /// any method that was not setup properly. + /// + public class ReplayDynamicMockState : ReplayMockState + { + /// + /// Creates a new instance. + /// + /// The previous state for this method + public ReplayDynamicMockState(RecordDynamicMockState previousState):base(previousState) + {} + + /// + /// 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 + protected override object DoMethodCall(IInvocation invocation, MethodInfo method, params object[] args) + { + IExpectation expectation = repository.Replayer.GetRecordedExpectationOrNull(proxy, method, args); + if (expectation != null) + { + RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); + return expectation.ReturnOrThrow(invocation,args); + } + else + { + RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Dynamic Mock: Unexpected method call ignored"); + return ReturnValueUtil.DefaultValue(method.ReturnType, invocation); + } + + } + + /// + /// Gets a mock state that match the original mock state of the object. + /// + public override IMockState BackToRecord() + { + return new RecordDynamicMockState(proxy, repository); + } + } +} diff --git a/Rhino.Mocks/Impl/ReplayMockState.cs b/Rhino.Mocks/Impl/ReplayMockState.cs index 293da4dd..e8ef0cdb 100644 --- a/Rhino.Mocks/Impl/ReplayMockState.cs +++ b/Rhino.Mocks/Impl/ReplayMockState.cs @@ -1,205 +1,205 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Interfaces; -using Castle.DynamicProxy; - -namespace Rhino.Mocks.Impl -{ - /// - /// Validate all expectations on a mock - /// - public class ReplayMockState : IMockState - { - #region Variables - - /// - /// The repository for this state - /// - protected MockRepository repository; - /// - /// The proxy object for this state - /// - protected IMockedObject proxy; - - private Exception exceptionToThrowOnVerify; - - #endregion - - #region Properties - - /// - /// Get the options for the last method call - /// - public IMethodOptions GetLastMethodOptions() - { - throw InvalidInReplayState(); - } - - /// - /// Get the options for the last method call - /// - public IMethodOptions LastMethodOptions - { - get { throw InvalidInReplayState(); } - } - - /// - /// Gets the matching verify state for this state - /// - public virtual IMockState VerifyState - { - get { return new VerifiedMockState(this); } - } - - #endregion - - #region C'tor - - /// - /// Creates a new instance. - /// - /// The previous state for this method - public ReplayMockState(RecordMockState previousState) - { - this.repository = previousState.Repository; - this.proxy = previousState.Proxy; - } - - #endregion - - #region Methods - - /// - /// 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 - public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args) - { - IExpectation expectation = repository.Replayer.GetRepeatableExpectation(proxy, method, args); - if (expectation != null) - { - RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); - return expectation.ReturnOrThrow(invocation,args); - } - return DoMethodCall(invocation, method, args); - } - - /// - /// 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 - protected virtual object DoMethodCall(IInvocation invocation, MethodInfo method, object[] args) - { - IExpectation expectation = repository.Replayer.GetRecordedExpectation(invocation, proxy, method, args); - RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); - return expectation.ReturnOrThrow(invocation,args); - } - - /// - /// 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. - /// - public void SetExceptionToThrowOnVerify(Exception ex) - { - this.exceptionToThrowOnVerify = ex; - } - - /// - /// not relevant - /// - public void NotifyCallOnPropertyBehavior() - { - // doesn't deal with recording anyway - } - - /// - /// Verify that this mock expectations have passed. - /// - public virtual void Verify() - { - if (exceptionToThrowOnVerify != null) - throw exceptionToThrowOnVerify; - StringBuilder sb = new StringBuilder(); - bool verifiedFailed = false; - foreach (IExpectation expectation in repository.Recorder.GetAllExpectationsForProxy(proxy)) - { - if (expectation.ExpectationSatisfied == false) - { - if (verifiedFailed) - sb.Append("\r\n"); - sb.Append(expectation.BuildVerificationFailureMessage()); - verifiedFailed = true; - } - } - if (verifiedFailed) - throw new ExpectationViolationException(sb.ToString()); - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - public virtual IMockState Replay() - { - throw InvalidInReplayState(); - } - - /// - /// Gets a mock state that match the original mock state of the object. - /// - public virtual IMockState BackToRecord() - { - return new RecordMockState(proxy, repository); - } - - #endregion - - #region Private Methods - - private Exception InvalidInReplayState() - { - return new InvalidOperationException("This action is invalid when the mock object is in replay state."); - } - - #endregion - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Interfaces; +using Castle.DynamicProxy; + +namespace Rhino.Mocks.Impl +{ + /// + /// Validate all expectations on a mock + /// + public class ReplayMockState : IMockState + { + #region Variables + + /// + /// The repository for this state + /// + protected MockRepository repository; + /// + /// The proxy object for this state + /// + protected IMockedObject proxy; + + private Exception exceptionToThrowOnVerify; + + #endregion + + #region Properties + + /// + /// Get the options for the last method call + /// + public IMethodOptions GetLastMethodOptions() + { + throw InvalidInReplayState(); + } + + /// + /// Get the options for the last method call + /// + public IMethodOptions LastMethodOptions + { + get { throw InvalidInReplayState(); } + } + + /// + /// Gets the matching verify state for this state + /// + public virtual IMockState VerifyState + { + get { return new VerifiedMockState(this); } + } + + #endregion + + #region C'tor + + /// + /// Creates a new instance. + /// + /// The previous state for this method + public ReplayMockState(RecordMockState previousState) + { + this.repository = previousState.Repository; + this.proxy = previousState.Proxy; + } + + #endregion + + #region Methods + + /// + /// 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 + public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args) + { + IExpectation expectation = repository.Replayer.GetRepeatableExpectation(proxy, method, args); + if (expectation != null) + { + RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); + return expectation.ReturnOrThrow(invocation,args); + } + return DoMethodCall(invocation, method, args); + } + + /// + /// 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 + protected virtual object DoMethodCall(IInvocation invocation, MethodInfo method, object[] args) + { + IExpectation expectation = repository.Replayer.GetRecordedExpectation(invocation, proxy, method, args); + RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); + return expectation.ReturnOrThrow(invocation,args); + } + + /// + /// 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. + /// + public void SetExceptionToThrowOnVerify(Exception ex) + { + this.exceptionToThrowOnVerify = ex; + } + + /// + /// not relevant + /// + public void NotifyCallOnPropertyBehavior() + { + // doesn't deal with recording anyway + } + + /// + /// Verify that this mock expectations have passed. + /// + public virtual void Verify() + { + if (exceptionToThrowOnVerify != null) + throw exceptionToThrowOnVerify; + StringBuilder sb = new StringBuilder(); + bool verifiedFailed = false; + foreach (IExpectation expectation in repository.Recorder.GetAllExpectationsForProxy(proxy)) + { + if (expectation.ExpectationSatisfied == false) + { + if (verifiedFailed) + sb.Append("\r\n"); + sb.Append(expectation.BuildVerificationFailureMessage()); + verifiedFailed = true; + } + } + if (verifiedFailed) + throw new ExpectationViolationException(sb.ToString()); + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + public virtual IMockState Replay() + { + throw InvalidInReplayState(); + } + + /// + /// Gets a mock state that match the original mock state of the object. + /// + public virtual IMockState BackToRecord() + { + return new RecordMockState(proxy, repository); + } + + #endregion + + #region Private Methods + + private Exception InvalidInReplayState() + { + return new InvalidOperationException("This action is invalid when the mock object is in replay state."); + } + + #endregion + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/ReplayPartialMockState.cs b/Rhino.Mocks/Impl/ReplayPartialMockState.cs index 1ae316c7..3f677234 100644 --- a/Rhino.Mocks/Impl/ReplayPartialMockState.cs +++ b/Rhino.Mocks/Impl/ReplayPartialMockState.cs @@ -1,88 +1,88 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; -using Castle.DynamicProxy; - -namespace Rhino.Mocks.Impl -{ - /// - /// Validate all expectations on a mock and ignores calls to - /// any method that was not setup properly. - /// - public class ReplayPartialMockState : ReplayMockState - { - /// - /// Creates a new instance. - /// - /// The previous state for this method - public ReplayPartialMockState(RecordPartialMockState previousState) - : base(previousState) - { - } - - /// - /// 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 - protected override object DoMethodCall(IInvocation invocation, MethodInfo method, params object[] args) - { - IExpectation expectation = repository.Replayer.GetRecordedExpectationOrNull(proxy, method, args); - if (expectation != null) - { - RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); - return expectation.ReturnOrThrow(invocation,args); - } - if (method.IsAbstract == false) - { - RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Partial mock: calling original method"); - invocation.Proceed(); - return invocation.ReturnValue; - } - RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Partial mock: abstract method called but was not expected"); - //because the expectation doesn't exist, an exception will be thrown - return repository.Replayer.GetRecordedExpectation(invocation,proxy, method, args); - } - - - /// - /// Gets a mock state that match the original mock state of the object. - /// - public override IMockState BackToRecord() - { - return new RecordPartialMockState(proxy, repository); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; +using Castle.DynamicProxy; + +namespace Rhino.Mocks.Impl +{ + /// + /// Validate all expectations on a mock and ignores calls to + /// any method that was not setup properly. + /// + public class ReplayPartialMockState : ReplayMockState + { + /// + /// Creates a new instance. + /// + /// The previous state for this method + public ReplayPartialMockState(RecordPartialMockState previousState) + : base(previousState) + { + } + + /// + /// 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 + protected override object DoMethodCall(IInvocation invocation, MethodInfo method, params object[] args) + { + IExpectation expectation = repository.Replayer.GetRecordedExpectationOrNull(proxy, method, args); + if (expectation != null) + { + RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); + return expectation.ReturnOrThrow(invocation,args); + } + if (method.IsAbstract == false) + { + RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Partial mock: calling original method"); + invocation.Proceed(); + return invocation.ReturnValue; + } + RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Partial mock: abstract method called but was not expected"); + //because the expectation doesn't exist, an exception will be thrown + return repository.Replayer.GetRecordedExpectation(invocation,proxy, method, args); + } + + + /// + /// Gets a mock state that match the original mock state of the object. + /// + public override IMockState BackToRecord() + { + return new RecordPartialMockState(proxy, repository); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/RhinoInterceptor.cs b/Rhino.Mocks/Impl/RhinoInterceptor.cs index e04f0787..70379d63 100644 --- a/Rhino.Mocks/Impl/RhinoInterceptor.cs +++ b/Rhino.Mocks/Impl/RhinoInterceptor.cs @@ -1,114 +1,114 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - using System.Runtime.CompilerServices; - - /// - /// Summary description for RhinoInterceptor. - /// - public class RhinoInterceptor : MarshalByRefObject, IInterceptor - { - private readonly MockRepository repository; - private readonly IMockedObject proxyInstance; - - private static MethodInfo[] objectMethods = - new MethodInfo[] - { - typeof (object).GetMethod("ToString"), typeof (object).GetMethod("Equals", new Type[] {typeof (object)}), - typeof (object).GetMethod("GetHashCode"), typeof (object).GetMethod("GetType") - }; - - /// - /// Creates a new instance. - /// - public RhinoInterceptor(MockRepository repository, IMockedObject proxyInstance) - { - this.repository = repository; - this.proxyInstance = proxyInstance; - } - - /// - /// Intercept a method call and direct it to the repository. - /// - [MethodImpl(MethodImplOptions.Synchronized)] - public void Intercept(IInvocation invocation) - { - proxyInstance.MockedObjectInstance = invocation.Proxy; - if (Array.IndexOf(objectMethods, invocation.Method) != -1) - { - invocation.Proceed(); - return; - } - if (invocation.Method.DeclaringType == typeof (IMockedObject)) - { - invocation.ReturnValue = invocation.Method.Invoke(proxyInstance, invocation.Arguments); - return; - } - if (proxyInstance.ShouldCallOriginal(invocation.GetConcreteMethod())) - { - invocation.Proceed(); - return; - } - if (proxyInstance.IsPropertyMethod(invocation.GetConcreteMethod())) - { - invocation.ReturnValue = proxyInstance.HandleProperty(invocation.GetConcreteMethod(), invocation.Arguments); - repository.RegisterPropertyBehaviorOn(proxyInstance); - return; - } - //This call handle the subscribe / remove this method call is for an event, - //processing then continue normally (so we get an expectation for subscribing / removing from the event - HandleEvent(invocation, invocation.Arguments); - object proxy = repository.GetMockObjectFromInvocationProxy(invocation.Proxy); - MethodInfo method = invocation.GetConcreteMethod(); - invocation.ReturnValue = repository.MethodCall(invocation, proxy, method, invocation.Arguments); - } - - private void HandleEvent(IInvocation invocation, object[] args) - { - if (IsEvent(invocation)) - { - proxyInstance.HandleEvent(invocation.Method, args); - } - } - - private bool IsEvent(IInvocation invocation) - { - return - invocation.Method.Name.StartsWith("add_") || - invocation.Method.Name.StartsWith("remove_"); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + using System.Runtime.CompilerServices; + + /// + /// Summary description for RhinoInterceptor. + /// + public class RhinoInterceptor : MarshalByRefObject, IInterceptor + { + private readonly MockRepository repository; + private readonly IMockedObject proxyInstance; + + private static MethodInfo[] objectMethods = + new MethodInfo[] + { + typeof (object).GetMethod("ToString"), typeof (object).GetMethod("Equals", new Type[] {typeof (object)}), + typeof (object).GetMethod("GetHashCode"), typeof (object).GetMethod("GetType") + }; + + /// + /// Creates a new instance. + /// + public RhinoInterceptor(MockRepository repository, IMockedObject proxyInstance) + { + this.repository = repository; + this.proxyInstance = proxyInstance; + } + + /// + /// Intercept a method call and direct it to the repository. + /// + [MethodImpl(MethodImplOptions.Synchronized)] + public void Intercept(IInvocation invocation) + { + proxyInstance.MockedObjectInstance = invocation.Proxy; + if (Array.IndexOf(objectMethods, invocation.Method) != -1) + { + invocation.Proceed(); + return; + } + if (invocation.Method.DeclaringType == typeof (IMockedObject)) + { + invocation.ReturnValue = invocation.Method.Invoke(proxyInstance, invocation.Arguments); + return; + } + if (proxyInstance.ShouldCallOriginal(invocation.GetConcreteMethod())) + { + invocation.Proceed(); + return; + } + if (proxyInstance.IsPropertyMethod(invocation.GetConcreteMethod())) + { + invocation.ReturnValue = proxyInstance.HandleProperty(invocation.GetConcreteMethod(), invocation.Arguments); + repository.RegisterPropertyBehaviorOn(proxyInstance); + return; + } + //This call handle the subscribe / remove this method call is for an event, + //processing then continue normally (so we get an expectation for subscribing / removing from the event + HandleEvent(invocation, invocation.Arguments); + object proxy = repository.GetMockObjectFromInvocationProxy(invocation.Proxy); + MethodInfo method = invocation.GetConcreteMethod(); + invocation.ReturnValue = repository.MethodCall(invocation, proxy, method, invocation.Arguments); + } + + private void HandleEvent(IInvocation invocation, object[] args) + { + if (IsEvent(invocation)) + { + proxyInstance.HandleEvent(invocation.Method, args); + } + } + + private bool IsEvent(IInvocation invocation) + { + return + invocation.Method.Name.StartsWith("add_") || + invocation.Method.Name.StartsWith("remove_"); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/StubRecordMockState.cs b/Rhino.Mocks/Impl/StubRecordMockState.cs index 20d4687d..155c4381 100644 --- a/Rhino.Mocks/Impl/StubRecordMockState.cs +++ b/Rhino.Mocks/Impl/StubRecordMockState.cs @@ -1,117 +1,126 @@ -#region license - -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Reflection; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Impl -{ - /// - /// 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. - /// - public class StubRecordMockState : RecordMockState - { - /// - /// Initializes a new instance of the class. - /// - /// The proxy that generates the method calls - /// Repository. - public StubRecordMockState(IMockedObject mockedObject, MockRepository repository) - : base(mockedObject, repository) - { - Type[] types = mockedObject.ImplementedTypes; - SetPropertyBehavior(mockedObject, types); - } - - private void SetPropertyBehavior(IMockedObject mockedObject, params Type[] types) - { - foreach (Type implementedType in types) - { - if (implementedType.BaseType != null && implementedType.BaseType != typeof(object)) - { - SetPropertyBehavior(mockedObject, implementedType.BaseType); - } - - SetPropertyBehavior(mockedObject, implementedType.GetInterfaces()); - - foreach (PropertyInfo property in implementedType.GetProperties()) - { - if (property.CanRead && property.CanWrite) - { - bool alreadyHasValue = mockedObject.RegisterPropertyBehaviorFor(property); - if (property.PropertyType.IsValueType && alreadyHasValue == false) - { - //make sure that it creates a default value for value types - mockedObject.HandleProperty(property.GetSetMethod(true), - new object[] { Activator.CreateInstance(property.PropertyType) }); - } - } - } - - } - } - - /// - /// We don't care much about expectations here, so we will remove the expectation if - /// it is not closed. - /// - protected override void AssertPreviousMethodIsClose() - { - if (LastExpectation == null) - return; - if (LastExpectation.ActionsSatisfied) - return; - Repository.Recorder.RemoveExpectation(LastExpectation); - LastExpectation = null; - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - /// - public override IMockState Replay() - { - AssertPreviousMethodIsClose(); - return new StubReplayMockState(this); - } - - /// - /// Get the default call count range expectation - /// - /// - protected override Range GetDefaultCallCountRangeExpectation() - { - return new Range(1, null); - } - } -} +#region license + +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using System.Reflection; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Impl +{ + /// + /// 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. + /// + public class StubRecordMockState : RecordMockState + { + /// + /// Initializes a new instance of the class. + /// + /// The proxy that generates the method calls + /// Repository. + public StubRecordMockState(IMockedObject mockedObject, MockRepository repository) + : base(mockedObject, repository) + { + Type[] types = mockedObject.ImplementedTypes; + SetPropertyBehavior(mockedObject, types); + } + + private void SetPropertyBehavior(IMockedObject mockedObject, params Type[] types) + { + foreach (Type implementedType in types) + { + if (implementedType.BaseType != null && implementedType.BaseType != typeof(object)) + { + SetPropertyBehavior(mockedObject, implementedType.BaseType); + } + + SetPropertyBehavior(mockedObject, implementedType.GetInterfaces()); + + foreach (PropertyInfo property in implementedType.GetProperties()) + { + if (property.CanRead && CanWriteToPropertyThroughPublicSignature(property)) + { + bool alreadyHasValue = mockedObject.RegisterPropertyBehaviorFor(property); + if (property.PropertyType.IsValueType && alreadyHasValue == false) + { + CreateDefaultValueForValueTypes(mockedObject, property); + } + } + } + + } + } + + void CreateDefaultValueForValueTypes(IMockedObject mockedObject, PropertyInfo property) + { + mockedObject.HandleProperty(property.GetSetMethod(true), + new object[] { Activator.CreateInstance(property.PropertyType) }); + } + + bool CanWriteToPropertyThroughPublicSignature(PropertyInfo property) + { + return property.CanWrite && property.GetSetMethod(false) != null; + } + + /// + /// We don't care much about expectations here, so we will remove the expectation if + /// it is not closed. + /// + protected override void AssertPreviousMethodIsClose() + { + if (LastExpectation == null) + return; + if (LastExpectation.ActionsSatisfied) + return; + Repository.Recorder.RemoveExpectation(LastExpectation); + LastExpectation = null; + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + /// + public override IMockState Replay() + { + AssertPreviousMethodIsClose(); + return new StubReplayMockState(this); + } + + /// + /// Get the default call count range expectation + /// + /// + protected override Range GetDefaultCallCountRangeExpectation() + { + return new Range(1, null); + } + } +} diff --git a/Rhino.Mocks/Impl/StubReplayMockState.cs b/Rhino.Mocks/Impl/StubReplayMockState.cs index e05c3267..c4833c32 100644 --- a/Rhino.Mocks/Impl/StubReplayMockState.cs +++ b/Rhino.Mocks/Impl/StubReplayMockState.cs @@ -1,94 +1,94 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Impl -{ - /// - /// Validate expectations on recorded methods, but in general completely ignoring them. - /// Similar to except that it would return a - /// when BackToRecord is called. - /// - internal class StubReplayMockState : ReplayMockState - { - /// - /// Initializes a new instance of the class. - /// - /// The previous state for this method - public StubReplayMockState(RecordMockState previousState) : base(previousState) - { - } - - /// - /// 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 - protected override object DoMethodCall(IInvocation invocation, MethodInfo method, params object[] args) - { - IExpectation expectation = repository.Replayer.GetRecordedExpectationOrNull(proxy, method, args); - if (expectation != null) - { - RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); - return expectation.ReturnOrThrow(invocation, args); - } - else - { - RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Stub Mock: Unexpected method call ignored"); - return ReturnValueUtil.DefaultValue(method.ReturnType, invocation); - } - - } - - /// - /// Gets a mock state that matches the original mock state of the object. - /// - public override IMockState BackToRecord() - { - return new StubRecordMockState(proxy, repository); - } - - public override void Verify() - { - //stub doesn't do verifications - } - - public override IMockState VerifyState - { - get - { - return this;// there is no meaning to be verified in stubs. - } - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Impl +{ + /// + /// Validate expectations on recorded methods, but in general completely ignoring them. + /// Similar to except that it would return a + /// when BackToRecord is called. + /// + internal class StubReplayMockState : ReplayMockState + { + /// + /// Initializes a new instance of the class. + /// + /// The previous state for this method + public StubReplayMockState(RecordMockState previousState) : base(previousState) + { + } + + /// + /// 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 + protected override object DoMethodCall(IInvocation invocation, MethodInfo method, params object[] args) + { + IExpectation expectation = repository.Replayer.GetRecordedExpectationOrNull(proxy, method, args); + if (expectation != null) + { + RhinoMocks.Logger.LogReplayedExpectation(invocation, expectation); + return expectation.ReturnOrThrow(invocation, args); + } + else + { + RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Stub Mock: Unexpected method call ignored"); + return ReturnValueUtil.DefaultValue(method.ReturnType, invocation); + } + + } + + /// + /// Gets a mock state that matches the original mock state of the object. + /// + public override IMockState BackToRecord() + { + return new StubRecordMockState(proxy, repository); + } + + public override void Verify() + { + //stub doesn't do verifications + } + + public override IMockState VerifyState + { + get + { + return this;// there is no meaning to be verified in stubs. + } + } + } +} diff --git a/Rhino.Mocks/Impl/TextWriterExpectationLogger.cs b/Rhino.Mocks/Impl/TextWriterExpectationLogger.cs index 7be19e32..3408eb83 100644 --- a/Rhino.Mocks/Impl/TextWriterExpectationLogger.cs +++ b/Rhino.Mocks/Impl/TextWriterExpectationLogger.cs @@ -1,59 +1,59 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Impl -{ - /// - /// Rudimetry implementation that simply logs methods calls as text. - /// - public class TextWriterExpectationLogger : IExpectationLogger - { - private readonly TextWriter writer; - - /// - /// Initializes a new instance of the class. - /// - /// The writer. - public TextWriterExpectationLogger(TextWriter writer) - { - this.writer = writer; - } - /// - /// Logs the expectation as it was recorded - /// - /// The invocation. - /// The expectation. - public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) - { - string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - writer.WriteLine("Recorded expectation: {0}", methodCall); - } - - /// - /// Logs the expectation as it was recorded - /// - /// The invocation. - /// The expectation. - public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) - { - string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - writer.WriteLine("Replayed expectation: {0}", methodCall); - } - - /// - /// Logs the unexpected method call. - /// - /// The invocation. - /// The message. - public void LogUnexpectedMethodCall(IInvocation invocation, string message) - { - string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - writer.WriteLine("{1}: {0}", methodCall, message); - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Impl +{ + /// + /// Rudimetry implementation that simply logs methods calls as text. + /// + public class TextWriterExpectationLogger : IExpectationLogger + { + private readonly TextWriter writer; + + /// + /// Initializes a new instance of the class. + /// + /// The writer. + public TextWriterExpectationLogger(TextWriter writer) + { + this.writer = writer; + } + /// + /// Logs the expectation as it was recorded + /// + /// The invocation. + /// The expectation. + public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) + { + string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + writer.WriteLine("Recorded expectation: {0}", methodCall); + } + + /// + /// Logs the expectation as it was recorded + /// + /// The invocation. + /// The expectation. + public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) + { + string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + writer.WriteLine("Replayed expectation: {0}", methodCall); + } + + /// + /// Logs the unexpected method call. + /// + /// The invocation. + /// The message. + public void LogUnexpectedMethodCall(IInvocation invocation, string message) + { + string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + writer.WriteLine("{1}: {0}", methodCall, message); + } + } +} diff --git a/Rhino.Mocks/Impl/TraceWriterExpectationLogger.cs b/Rhino.Mocks/Impl/TraceWriterExpectationLogger.cs index d8099ab5..10e10352 100644 --- a/Rhino.Mocks/Impl/TraceWriterExpectationLogger.cs +++ b/Rhino.Mocks/Impl/TraceWriterExpectationLogger.cs @@ -1,88 +1,88 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.Impl -{ - /// - /// Write rhino mocks log info to the trace - /// - public class TraceWriterExpectationLogger : IExpectationLogger - { - private readonly bool _logRecorded = true; - private readonly bool _logReplayed = true; - private readonly bool _logUnexpected = true; - - /// - /// Initializes a new instance of the class. - /// - public TraceWriterExpectationLogger() - {} - - /// - /// 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]. - public TraceWriterExpectationLogger(bool logRecorded, bool logReplayed, bool logUnexpected) - { - _logRecorded = logRecorded; - _logReplayed = logReplayed; - _logUnexpected = logUnexpected; - } - - #region IExpectationLogger Members - - /// - /// Logs the expectation as is was recorded - /// - /// The invocation. - /// The expectation. - public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) - { - if (_logRecorded) - { - string methodCall = - MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - Trace.WriteLine(string.Format("Recorded expectation: {0}", methodCall)); - } - } - - /// - /// Logs the expectation as it was recorded - /// - /// The invocation. - /// The expectation. - public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) - { - if (_logReplayed) - { - string methodCall = - MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - Trace.WriteLine(string.Format("Replayed expectation: {0}", methodCall)); - } - } - - /// - /// Logs the unexpected method call. - /// - /// The invocation. - /// The message. - public void LogUnexpectedMethodCall(IInvocation invocation, string message) - { - if (_logUnexpected) - { - string methodCall = - MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - Trace.WriteLine(string.Format("{1}: {0}", methodCall, message)); - } - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.Impl +{ + /// + /// Write rhino mocks log info to the trace + /// + public class TraceWriterExpectationLogger : IExpectationLogger + { + private readonly bool _logRecorded = true; + private readonly bool _logReplayed = true; + private readonly bool _logUnexpected = true; + + /// + /// Initializes a new instance of the class. + /// + public TraceWriterExpectationLogger() + {} + + /// + /// 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]. + public TraceWriterExpectationLogger(bool logRecorded, bool logReplayed, bool logUnexpected) + { + _logRecorded = logRecorded; + _logReplayed = logReplayed; + _logUnexpected = logUnexpected; + } + + #region IExpectationLogger Members + + /// + /// Logs the expectation as is was recorded + /// + /// The invocation. + /// The expectation. + public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) + { + if (_logRecorded) + { + string methodCall = + MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + Trace.WriteLine(string.Format("Recorded expectation: {0}", methodCall)); + } + } + + /// + /// Logs the expectation as it was recorded + /// + /// The invocation. + /// The expectation. + public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) + { + if (_logReplayed) + { + string methodCall = + MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + Trace.WriteLine(string.Format("Replayed expectation: {0}", methodCall)); + } + } + + /// + /// Logs the unexpected method call. + /// + /// The invocation. + /// The message. + public void LogUnexpectedMethodCall(IInvocation invocation, string message) + { + if (_logUnexpected) + { + string methodCall = + MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + Trace.WriteLine(string.Format("{1}: {0}", methodCall, message)); + } + } + + #endregion + } +} diff --git a/Rhino.Mocks/Impl/TraceWriterWithStackTraceExpectationWriter.cs b/Rhino.Mocks/Impl/TraceWriterWithStackTraceExpectationWriter.cs index 054e0a93..b1ca4036 100644 --- a/Rhino.Mocks/Impl/TraceWriterWithStackTraceExpectationWriter.cs +++ b/Rhino.Mocks/Impl/TraceWriterWithStackTraceExpectationWriter.cs @@ -1,71 +1,71 @@ -namespace Rhino.Mocks.Impl -{ - using System.Diagnostics; - using System.IO; - using Castle.Core.Interceptor; - using Interfaces; - using Utilities; - - /// - /// Writes log information as stack traces about rhino mocks activity - /// - public class TraceWriterWithStackTraceExpectationWriter : IExpectationLogger - { - /// - /// Allows to redirect output to a different location. - /// - public TextWriter AlternativeWriter; - - /// - /// Logs the expectation as is was recorded - /// - /// The invocation. - /// The expectation. - public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) - { - string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - WriteLine("Recorded expectation: {0}", methodCall); - WriteCurrentMethod(); - } - - private void WriteLine(string msg, params object[] args) - { - string result = string.Format(msg, args); - if (AlternativeWriter != null) - { - AlternativeWriter.WriteLine(result); - return; - } - Debug.WriteLine(result); - } - - private void WriteCurrentMethod() - { - WriteLine(new StackTrace(true).ToString()); - } - - /// - /// Logs the expectation as it was recorded - /// - /// The invocation. - /// The expectation. - public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) - { - string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - WriteLine("Replayed expectation: {0}", methodCall); - WriteCurrentMethod(); - } - - /// - /// Logs the unexpected method call. - /// - /// The invocation. - /// The message. - public void LogUnexpectedMethodCall(IInvocation invocation, string message) - { - string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); - WriteLine("{1}: {0}", methodCall, message); - WriteCurrentMethod(); - } - } +namespace Rhino.Mocks.Impl +{ + using System.Diagnostics; + using System.IO; + using Castle.Core.Interceptor; + using Interfaces; + using Utilities; + + /// + /// Writes log information as stack traces about rhino mocks activity + /// + public class TraceWriterWithStackTraceExpectationWriter : IExpectationLogger + { + /// + /// Allows to redirect output to a different location. + /// + public TextWriter AlternativeWriter; + + /// + /// Logs the expectation as is was recorded + /// + /// The invocation. + /// The expectation. + public void LogRecordedExpectation(IInvocation invocation, IExpectation expectation) + { + string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + WriteLine("Recorded expectation: {0}", methodCall); + WriteCurrentMethod(); + } + + private void WriteLine(string msg, params object[] args) + { + string result = string.Format(msg, args); + if (AlternativeWriter != null) + { + AlternativeWriter.WriteLine(result); + return; + } + Debug.WriteLine(result); + } + + private void WriteCurrentMethod() + { + WriteLine(new StackTrace(true).ToString()); + } + + /// + /// Logs the expectation as it was recorded + /// + /// The invocation. + /// The expectation. + public void LogReplayedExpectation(IInvocation invocation, IExpectation expectation) + { + string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + WriteLine("Replayed expectation: {0}", methodCall); + WriteCurrentMethod(); + } + + /// + /// Logs the unexpected method call. + /// + /// The invocation. + /// The message. + public void LogUnexpectedMethodCall(IInvocation invocation, string message) + { + string methodCall = MethodCallUtil.StringPresentation(invocation, invocation.Method, invocation.Arguments); + WriteLine("{1}: {0}", methodCall, message); + WriteCurrentMethod(); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Impl/Validate.cs b/Rhino.Mocks/Impl/Validate.cs index dfe3985b..4856e8b4 100644 --- a/Rhino.Mocks/Impl/Validate.cs +++ b/Rhino.Mocks/Impl/Validate.cs @@ -1,138 +1,138 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Interfaces; -using System.Collections; - -namespace Rhino.Mocks.Impl -{ - /// - /// Validate arguments for methods - /// - public static class Validate - { - /// - /// 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. - /// - public static void IsNotNull(object obj, string name) - { - if (obj == null) - throw new ArgumentNullException(name); - } - - /// - /// Validate that the arguments are equal. - /// - /// Expected args. - /// Actual Args. - public static bool ArgsEqual(object[] expectedArgs, object[] actualArgs) - { - return RecursiveCollectionEqual(expectedArgs, actualArgs); - } - - /// - /// Validate that the two arguments are equals, including validation for - /// when the arguments are collections, in which case it will validate their values. - /// - public static bool AreEqual(object expectedArg, object actualArg) - { - return RecursiveCollectionEqual(new object[] { expectedArg }, new object[] { actualArg }); - } - - #region Implementation - - private static bool RecursiveCollectionEqual(ICollection expectedArgs, ICollection actualArgs) - { - if(expectedArgs == null && actualArgs == null) - return true; - if(expectedArgs==null || actualArgs==null) - return false; - - if (expectedArgs.Count != actualArgs.Count) - return false; - - IEnumerator expectedArgsEnumerator = expectedArgs.GetEnumerator(); - IEnumerator actualArgsEnumerator = actualArgs.GetEnumerator(); - while (expectedArgsEnumerator.MoveNext() - && actualArgsEnumerator.MoveNext()) - { - object expected = expectedArgsEnumerator.Current; - object actual = actualArgsEnumerator.Current; - - if (expected == null) - { - if (actual == null) - continue; - else - return false; - } - - if (SafeEquals(expected, actual)) - continue; - - if (expected is ICollection) - { - if (!RecursiveCollectionEqual(expected as ICollection, actual as ICollection)) - return false; - - continue; - } - return false; - } - return true; - } - - /// - /// This method is safe for use even if any of the objects is a mocked object - /// that override equals. - /// - private static bool SafeEquals(object expected, object actual) - { - IMockedObject expectedMock = expected as IMockedObject; - IMockedObject actualMock = actual as IMockedObject; - //none are mocked object - if (expectedMock == null && actualMock == null) - { - return expected.Equals(actual); - } - //if any of them is a mocked object, use mocks equality - //this may not be what the user is expecting, but it is needed, because - //otherwise we get into endless loop. - return MockedObjectsEquality.Instance.Equals(expected,actual); - } - #endregion - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Interfaces; +using System.Collections; + +namespace Rhino.Mocks.Impl +{ + /// + /// Validate arguments for methods + /// + public static class Validate + { + /// + /// 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. + /// + public static void IsNotNull(object obj, string name) + { + if (obj == null) + throw new ArgumentNullException(name); + } + + /// + /// Validate that the arguments are equal. + /// + /// Expected args. + /// Actual Args. + public static bool ArgsEqual(object[] expectedArgs, object[] actualArgs) + { + return RecursiveCollectionEqual(expectedArgs, actualArgs); + } + + /// + /// Validate that the two arguments are equals, including validation for + /// when the arguments are collections, in which case it will validate their values. + /// + public static bool AreEqual(object expectedArg, object actualArg) + { + return RecursiveCollectionEqual(new object[] { expectedArg }, new object[] { actualArg }); + } + + #region Implementation + + private static bool RecursiveCollectionEqual(ICollection expectedArgs, ICollection actualArgs) + { + if(expectedArgs == null && actualArgs == null) + return true; + if(expectedArgs==null || actualArgs==null) + return false; + + if (expectedArgs.Count != actualArgs.Count) + return false; + + IEnumerator expectedArgsEnumerator = expectedArgs.GetEnumerator(); + IEnumerator actualArgsEnumerator = actualArgs.GetEnumerator(); + while (expectedArgsEnumerator.MoveNext() + && actualArgsEnumerator.MoveNext()) + { + object expected = expectedArgsEnumerator.Current; + object actual = actualArgsEnumerator.Current; + + if (expected == null) + { + if (actual == null) + continue; + else + return false; + } + + if (SafeEquals(expected, actual)) + continue; + + if (expected is ICollection) + { + if (!RecursiveCollectionEqual(expected as ICollection, actual as ICollection)) + return false; + + continue; + } + return false; + } + return true; + } + + /// + /// This method is safe for use even if any of the objects is a mocked object + /// that override equals. + /// + private static bool SafeEquals(object expected, object actual) + { + IMockedObject expectedMock = expected as IMockedObject; + IMockedObject actualMock = actual as IMockedObject; + //none are mocked object + if (expectedMock == null && actualMock == null) + { + return expected.Equals(actual); + } + //if any of them is a mocked object, use mocks equality + //this may not be what the user is expecting, but it is needed, because + //otherwise we get into endless loop. + return MockedObjectsEquality.Instance.Equals(expected,actual); + } + #endregion + } +} diff --git a/Rhino.Mocks/Impl/VerifiedMockState.cs b/Rhino.Mocks/Impl/VerifiedMockState.cs index c9b98821..29d7ddbe 100644 --- a/Rhino.Mocks/Impl/VerifiedMockState.cs +++ b/Rhino.Mocks/Impl/VerifiedMockState.cs @@ -1,139 +1,139 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; -using Castle.DynamicProxy; - -namespace Rhino.Mocks.Impl -{ - /// - /// Throw an object already verified when accessed - /// - public class VerifiedMockState : IMockState - { - IMockState previous; - - /// - /// Create a new instance of VerifiedMockState - /// - /// The previous mock state, used to get the initial record state - public VerifiedMockState(IMockState previous) - { - this.previous = previous; - } - - /// - /// Gets the matching verify state for this state - /// - public IMockState VerifyState - { - get { throw InvalidInVerifiedState(); } - } - - /// - /// 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 - public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args) - { - if(method.Name == "Finalize") // skip finalizers - return null; - throw InvalidInVerifiedState(); - } - - /// - /// Verify that this mock expectations have passed. - /// - public void Verify() - { - throw InvalidInVerifiedState(); - } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - public IMockState Replay() - { - throw InvalidInVerifiedState(); - } - - /// - /// Gets a mock state that match the original mock state of the object. - /// - public virtual IMockState BackToRecord() - { - return previous.BackToRecord(); - } - - /// - /// Get the options for the last method call - /// - public IMethodOptions GetLastMethodOptions() - { - throw InvalidInVerifiedState(); - } - - /// - /// Get the options for the last method call - /// - public IMethodOptions LastMethodOptions - { - get { throw InvalidInVerifiedState(); } - } - - /// - /// 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. - /// - public void SetExceptionToThrowOnVerify(Exception ex) - { - //not implementing this, we are already verified. - } - - /// - /// not relevant - /// - public void NotifyCallOnPropertyBehavior() - { - // doesn't deal with recording anyway - } - - private Exception InvalidInVerifiedState() - { - return new InvalidOperationException("This action is invalid when the mock object is in verified state."); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; +using Castle.DynamicProxy; + +namespace Rhino.Mocks.Impl +{ + /// + /// Throw an object already verified when accessed + /// + public class VerifiedMockState : IMockState + { + IMockState previous; + + /// + /// Create a new instance of VerifiedMockState + /// + /// The previous mock state, used to get the initial record state + public VerifiedMockState(IMockState previous) + { + this.previous = previous; + } + + /// + /// Gets the matching verify state for this state + /// + public IMockState VerifyState + { + get { throw InvalidInVerifiedState(); } + } + + /// + /// 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 + public object MethodCall(IInvocation invocation, MethodInfo method, params object[] args) + { + if(method.Name == "Finalize") // skip finalizers + return null; + throw InvalidInVerifiedState(); + } + + /// + /// Verify that this mock expectations have passed. + /// + public void Verify() + { + throw InvalidInVerifiedState(); + } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + public IMockState Replay() + { + throw InvalidInVerifiedState(); + } + + /// + /// Gets a mock state that match the original mock state of the object. + /// + public virtual IMockState BackToRecord() + { + return previous.BackToRecord(); + } + + /// + /// Get the options for the last method call + /// + public IMethodOptions GetLastMethodOptions() + { + throw InvalidInVerifiedState(); + } + + /// + /// Get the options for the last method call + /// + public IMethodOptions LastMethodOptions + { + get { throw InvalidInVerifiedState(); } + } + + /// + /// 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. + /// + public void SetExceptionToThrowOnVerify(Exception ex) + { + //not implementing this, we are already verified. + } + + /// + /// not relevant + /// + public void NotifyCallOnPropertyBehavior() + { + // doesn't deal with recording anyway + } + + private Exception InvalidInVerifiedState() + { + return new InvalidOperationException("This action is invalid when the mock object is in verified state."); + } + } +} diff --git a/Rhino.Mocks/Interfaces/ICreateMethodExpectation.cs b/Rhino.Mocks/Interfaces/ICreateMethodExpectation.cs index 201bddaa..b355f3d3 100644 --- a/Rhino.Mocks/Interfaces/ICreateMethodExpectation.cs +++ b/Rhino.Mocks/Interfaces/ICreateMethodExpectation.cs @@ -1,43 +1,43 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Interface to allow calling a method and immediately get it's options. - /// - public interface ICreateMethodExpectation - { - /// - /// Get the method options for the call - /// - /// The method call should go here, the return value is ignored - IMethodOptions Call(T ignored); - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Interface to allow calling a method and immediately get it's options. + /// + public interface ICreateMethodExpectation + { + /// + /// Get the method options for the call + /// + /// The method call should go here, the return value is ignored + IMethodOptions Call(T ignored); + } +} diff --git a/Rhino.Mocks/Interfaces/IEventRaiser.cs b/Rhino.Mocks/Interfaces/IEventRaiser.cs index 2176d05c..f43274c9 100644 --- a/Rhino.Mocks/Interfaces/IEventRaiser.cs +++ b/Rhino.Mocks/Interfaces/IEventRaiser.cs @@ -1,49 +1,49 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Raise events for all subscribers for an event - /// - public interface IEventRaiser - { - /// - /// Raise the event - /// - void Raise(params object[] args); - - /// - /// The most common form for the event handler signature - /// - void Raise(object sender, EventArgs e); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Raise events for all subscribers for an event + /// + public interface IEventRaiser + { + /// + /// Raise the event + /// + void Raise(params object[] args); + + /// + /// The most common form for the event handler signature + /// + void Raise(object sender, EventArgs e); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IExpectation.cs b/Rhino.Mocks/Interfaces/IExpectation.cs index 2ad2cc40..5030f975 100644 --- a/Rhino.Mocks/Interfaces/IExpectation.cs +++ b/Rhino.Mocks/Interfaces/IExpectation.cs @@ -1,161 +1,161 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Impl; - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Interface to validate that a method call is correct. - /// - public interface IExpectation - { - /// - /// 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 - bool IsExpected(object[] args); - - /// - /// Gets the error message. - /// - /// - string ErrorMessage { get; } - - /// - /// Range of expected calls - /// - Range Expected { get; set; } - - /// - /// Number of call actually made for this method - /// - int ActualCallsCount { get; } - - /// - /// If this expectation is still waiting for calls. - /// - bool CanAcceptCalls { get; } - - /// - /// Add an actual method call to this expectation - /// - void AddActualCall(); - - /// - /// The return value for a method matching this expectation - /// - object ReturnValue { get; set; } - - /// - /// Gets or sets the exception to throw on a method matching this expectation. - /// - Exception ExceptionToThrow { get; set; } - - /// - /// Returns the return value or throw the exception and setup any output / ref parameters - /// that has been set. - /// - object ReturnOrThrow(IInvocation invocation, object [] args); - - /// - /// 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. - /// - bool ActionsSatisfied { get; } - - /// - /// Gets the method this expectation is for. - /// - MethodInfo Method { get; } - - /// - /// Gets or sets what special condtions there are for this method - /// repeating. - /// - RepeatableOption RepeatableOption { get; set; } - - /// - /// Gets a value indicating whether this expectation was satisfied - /// - bool ExpectationSatisfied { get; } - - /// - /// Specify whatever this expectation has a return value set - /// You can't check ReturnValue for this because a valid return value include null. - /// - bool HasReturnValue { get; } - - /// - /// An action to execute when the method is matched. - /// - Delegate ActionToExecute { get; set; } - - /// - /// 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. - /// - object[] OutRefParams { get; set; } - - /// - /// Documentation Message - /// - string Message { get; set; } - /// - /// Gets the invocation for this expectation - /// - /// The invocation. - IInvocation Originalinvocation { get;} - - /// - /// Occurs when the exceptation is match on a method call - /// - event Action WhenCalled; - - /// - /// Builds the verification failure message. - /// - /// - string BuildVerificationFailureMessage(); - - /// - /// Allow to set the return value in the future, if it was already set. - /// - bool AllowTentativeReturn { set; get; } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Impl; + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Interface to validate that a method call is correct. + /// + public interface IExpectation + { + /// + /// 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 + bool IsExpected(object[] args); + + /// + /// Gets the error message. + /// + /// + string ErrorMessage { get; } + + /// + /// Range of expected calls + /// + Range Expected { get; set; } + + /// + /// Number of call actually made for this method + /// + int ActualCallsCount { get; } + + /// + /// If this expectation is still waiting for calls. + /// + bool CanAcceptCalls { get; } + + /// + /// Add an actual method call to this expectation + /// + void AddActualCall(); + + /// + /// The return value for a method matching this expectation + /// + object ReturnValue { get; set; } + + /// + /// Gets or sets the exception to throw on a method matching this expectation. + /// + Exception ExceptionToThrow { get; set; } + + /// + /// Returns the return value or throw the exception and setup any output / ref parameters + /// that has been set. + /// + object ReturnOrThrow(IInvocation invocation, object [] args); + + /// + /// 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. + /// + bool ActionsSatisfied { get; } + + /// + /// Gets the method this expectation is for. + /// + MethodInfo Method { get; } + + /// + /// Gets or sets what special condtions there are for this method + /// repeating. + /// + RepeatableOption RepeatableOption { get; set; } + + /// + /// Gets a value indicating whether this expectation was satisfied + /// + bool ExpectationSatisfied { get; } + + /// + /// Specify whatever this expectation has a return value set + /// You can't check ReturnValue for this because a valid return value include null. + /// + bool HasReturnValue { get; } + + /// + /// An action to execute when the method is matched. + /// + Delegate ActionToExecute { get; set; } + + /// + /// 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. + /// + object[] OutRefParams { get; set; } + + /// + /// Documentation Message + /// + string Message { get; set; } + /// + /// Gets the invocation for this expectation + /// + /// The invocation. + IInvocation Originalinvocation { get;} + + /// + /// Occurs when the exceptation is match on a method call + /// + event Action WhenCalled; + + /// + /// Builds the verification failure message. + /// + /// + string BuildVerificationFailureMessage(); + + /// + /// Allow to set the return value in the future, if it was already set. + /// + bool AllowTentativeReturn { set; get; } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IExpectationLogger.cs b/Rhino.Mocks/Interfaces/IExpectationLogger.cs index e7e9980d..2e61f29f 100644 --- a/Rhino.Mocks/Interfaces/IExpectationLogger.cs +++ b/Rhino.Mocks/Interfaces/IExpectationLogger.cs @@ -1,59 +1,59 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using Castle.Core.Interceptor; - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Log expectations - allows to see what is going on inside Rhino Mocks - /// - public interface IExpectationLogger - { - /// - /// Logs the expectation as is was recorded - /// - /// The invocation. - /// The expectation. - void LogRecordedExpectation(IInvocation invocation, IExpectation expectation); - - /// - /// Logs the expectation as it was recorded - /// - /// The invocation. - /// The expectation. - void LogReplayedExpectation(IInvocation invocation, IExpectation expectation); - - /// - /// Logs the unexpected method call. - /// - /// The invocation. - /// The message. - void LogUnexpectedMethodCall(IInvocation invocation, string message); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using Castle.Core.Interceptor; + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Log expectations - allows to see what is going on inside Rhino Mocks + /// + public interface IExpectationLogger + { + /// + /// Logs the expectation as is was recorded + /// + /// The invocation. + /// The expectation. + void LogRecordedExpectation(IInvocation invocation, IExpectation expectation); + + /// + /// Logs the expectation as it was recorded + /// + /// The invocation. + /// The expectation. + void LogReplayedExpectation(IInvocation invocation, IExpectation expectation); + + /// + /// Logs the unexpected method call. + /// + /// The invocation. + /// The message. + void LogUnexpectedMethodCall(IInvocation invocation, string message); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IMethodOptions.cs b/Rhino.Mocks/Interfaces/IMethodOptions.cs index 495c8fca..ad28f21b 100644 --- a/Rhino.Mocks/Interfaces/IMethodOptions.cs +++ b/Rhino.Mocks/Interfaces/IMethodOptions.cs @@ -1,315 +1,315 @@ -#region license - -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Castle.Core.Interceptor; -using Rhino.Mocks.Constraints; -using System.Reflection; - -namespace Rhino.Mocks.Interfaces -{ - /* - * Interface: IMethodOptions - * - * Allows to define what would happen when a method is called. - * - */ - - /// - /// Allows to define what would happen when a method - /// is called. - /// - public interface IMethodOptions - { - /* - * Method: Return - * - * Sets the return value when the 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 - IMethodOptions Return(T objToReturn); - - /// - /// Allow to override this return value in the future - /// - /// IRepeat that defines how many times the method will return this value - IMethodOptions TentativeReturn(); - - /* - * Method: Throw - * - * Throws the specified exception when the method is called. - */ - - /// - /// Throws the specified exception when the method is called. - /// - /// Exception to throw - IMethodOptions Throw(Exception exception); - - /* - * Method: IgnoreArguments - * - * Ignores the arguments for this method. Any arguments are considered fine for this - * method. - */ - - /// - /// Ignores the arguments for this method. Any argument will be matched - /// againt this method. - /// - IMethodOptions IgnoreArguments(); - - /* - * Property: Repeat - * - * Allows to get the instance that would allow to - * set the expected number of times that this method will occur. - */ - - /// - /// Better syntax to define repeats. - /// - IRepeat Repeat { get; } - - /* - * Method: Constraints - * - * Sets the contraints on this method parameters. - * The number of the constraints *must* be equal to the number of method arguments. - */ - - /// - /// Add constraints for the method's arguments. - /// - IMethodOptions Constraints(params AbstractConstraint[] constraints); - - /* - * Method: Callback - * - * Sets a callback delegate to be called when this method is called. - * - * Important: - * The callback *must* have the same signature as the last method call but its return value - * *must* be a boolean. - * The callback will be called with the same parameters as the method and the method will - * be accepted if the delegate return a positive value. - * Note: - * The callback may be called several times - * - */ - - /// - /// Set a callback method for the last call - /// - IMethodOptions Callback(Delegate callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Callback(Delegates.Function callback); - - - /* - * Method: Do - * - * Set an action to run when the expectation is matched. - * - * Important: - * The action's delegate *must* have the same signature as the last methdo call, and its return - * value must be assignable to the last method call return value. - * - * Note: - * This method is only called once, after the method call was match to the expectation. - * - * - */ - - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - IMethodOptions Do(Delegate action); - - /// - /// Set a delegate to be called when the expectation is matched - /// and allow to optionally modify the invocation as needed - /// - IMethodOptions WhenCalled(Action action); - - /* - * Method: CallOriginalMethod - * - * Call the original method on the class, bypassing the mocking layers. - * - * Important: - * Can only be used on a method that has an implementation. - * If you try that on an interface method or an abstract method, you'll get an - * exception. - * - */ - - /// - /// Call the original method on the class, bypassing the mocking layers. - /// - /// - [Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")] - void CallOriginalMethod(); - - /* - * Method: CallOriginalMethod - * - * Call the original method on the class, optionally bypassing the mocking layers. - * - * Important: - * Can only be used on a method that has an implementation. - * If you try that on an interface method or an abstract method, you'll get an - * exception. - * - */ - - /// - /// Call the original method on the class, optionally bypassing the mocking layers. - /// - /// - IMethodOptions CallOriginalMethod(OriginalCallOptions options); - - /* Method: PropertyBehavior - * - * Use the property as a normal property, so you can use it to save/load values - * without having to specify expectations for it. - * - * Note: - * This can be called only when the last call is a getter or setter. - */ - - /// - /// Use the property as a simple property, getting/setting the values without - /// causing mock expectations. - /// - IMethodOptions PropertyBehavior(); - - /// - /// Expect last (property) call as property setting, ignore the argument given - /// - /// - IMethodOptions SetPropertyAndIgnoreArgument(); - - /// - /// Expect last (property) call as property setting with a given argument. - /// - /// - /// - IMethodOptions SetPropertyWithArgument(T argument); - - /// - /// Get an event raiser for the last subscribed event. - /// - IEventRaiser GetEventRaiser(); - - /// - /// Set the parameter values for out and ref parameters. - /// This is done using zero based indexing, and _ignoring_ any non out/ref parameter. - /// - IMethodOptions OutRef(params object[] parameters); - - /// - /// Documentation message for the expectation - /// - /// Message - IMethodOptions Message(string documentationMessage); - } -} +#region license + +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using Castle.Core.Interceptor; +using Rhino.Mocks.Constraints; +using System.Reflection; + +namespace Rhino.Mocks.Interfaces +{ + /* + * Interface: IMethodOptions + * + * Allows to define what would happen when a method is called. + * + */ + + /// + /// Allows to define what would happen when a method + /// is called. + /// + public interface IMethodOptions + { + /* + * Method: Return + * + * Sets the return value when the 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 + IMethodOptions Return(T objToReturn); + + /// + /// Allow to override this return value in the future + /// + /// IRepeat that defines how many times the method will return this value + IMethodOptions TentativeReturn(); + + /* + * Method: Throw + * + * Throws the specified exception when the method is called. + */ + + /// + /// Throws the specified exception when the method is called. + /// + /// Exception to throw + IMethodOptions Throw(Exception exception); + + /* + * Method: IgnoreArguments + * + * Ignores the arguments for this method. Any arguments are considered fine for this + * method. + */ + + /// + /// Ignores the arguments for this method. Any argument will be matched + /// againt this method. + /// + IMethodOptions IgnoreArguments(); + + /* + * Property: Repeat + * + * Allows to get the instance that would allow to + * set the expected number of times that this method will occur. + */ + + /// + /// Better syntax to define repeats. + /// + IRepeat Repeat { get; } + + /* + * Method: Constraints + * + * Sets the contraints on this method parameters. + * The number of the constraints *must* be equal to the number of method arguments. + */ + + /// + /// Add constraints for the method's arguments. + /// + IMethodOptions Constraints(params AbstractConstraint[] constraints); + + /* + * Method: Callback + * + * Sets a callback delegate to be called when this method is called. + * + * Important: + * The callback *must* have the same signature as the last method call but its return value + * *must* be a boolean. + * The callback will be called with the same parameters as the method and the method will + * be accepted if the delegate return a positive value. + * Note: + * The callback may be called several times + * + */ + + /// + /// Set a callback method for the last call + /// + IMethodOptions Callback(Delegate callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Callback(Delegates.Function callback); + + + /* + * Method: Do + * + * Set an action to run when the expectation is matched. + * + * Important: + * The action's delegate *must* have the same signature as the last methdo call, and its return + * value must be assignable to the last method call return value. + * + * Note: + * This method is only called once, after the method call was match to the expectation. + * + * + */ + + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + IMethodOptions Do(Delegate action); + + /// + /// Set a delegate to be called when the expectation is matched + /// and allow to optionally modify the invocation as needed + /// + IMethodOptions WhenCalled(Action action); + + /* + * Method: CallOriginalMethod + * + * Call the original method on the class, bypassing the mocking layers. + * + * Important: + * Can only be used on a method that has an implementation. + * If you try that on an interface method or an abstract method, you'll get an + * exception. + * + */ + + /// + /// Call the original method on the class, bypassing the mocking layers. + /// + /// + [Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")] + void CallOriginalMethod(); + + /* + * Method: CallOriginalMethod + * + * Call the original method on the class, optionally bypassing the mocking layers. + * + * Important: + * Can only be used on a method that has an implementation. + * If you try that on an interface method or an abstract method, you'll get an + * exception. + * + */ + + /// + /// Call the original method on the class, optionally bypassing the mocking layers. + /// + /// + IMethodOptions CallOriginalMethod(OriginalCallOptions options); + + /* Method: PropertyBehavior + * + * Use the property as a normal property, so you can use it to save/load values + * without having to specify expectations for it. + * + * Note: + * This can be called only when the last call is a getter or setter. + */ + + /// + /// Use the property as a simple property, getting/setting the values without + /// causing mock expectations. + /// + IMethodOptions PropertyBehavior(); + + /// + /// Expect last (property) call as property setting, ignore the argument given + /// + /// + IMethodOptions SetPropertyAndIgnoreArgument(); + + /// + /// Expect last (property) call as property setting with a given argument. + /// + /// + /// + IMethodOptions SetPropertyWithArgument(T argument); + + /// + /// Get an event raiser for the last subscribed event. + /// + IEventRaiser GetEventRaiser(); + + /// + /// Set the parameter values for out and ref parameters. + /// This is done using zero based indexing, and _ignoring_ any non out/ref parameter. + /// + IMethodOptions OutRef(params object[] parameters); + + /// + /// Documentation message for the expectation + /// + /// Message + IMethodOptions Message(string documentationMessage); + } +} diff --git a/Rhino.Mocks/Interfaces/IMethodRecorder.cs b/Rhino.Mocks/Interfaces/IMethodRecorder.cs index aa8aa65f..be2e28f6 100644 --- a/Rhino.Mocks/Interfaces/IMethodRecorder.cs +++ b/Rhino.Mocks/Interfaces/IMethodRecorder.cs @@ -1,145 +1,145 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Generated; - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Records the actions on all the mocks created by a repository. - /// - public interface IMethodRecorder - { - /// - /// Records the specified call with the specified args on the mocked object. - /// - void Record(object proxy, MethodInfo method, IExpectation expectation); - - /// - /// Get the expectation for this method on this object with this arguments - /// - IExpectation GetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args); - - /// - /// This check the methods that were setup using the SetupResult.For() - /// or LastCall.Repeat.Any() and that bypass the whole expectation model. - /// - IExpectation GetRepeatableExpectation(object proxy, MethodInfo method, object[] args); - - /// - /// 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 - ExpectationsList GetAllExpectationsForProxyAndMethod(object proxy, MethodInfo method); - - /// - /// Gets the all expectations for proxy. - /// - /// Mocked object. - /// List of all relevant expectation - ExpectationsList GetAllExpectationsForProxy(object proxy); - - /// - /// Removes all the repeatable expectations for proxy. - /// - /// Mocked object. - void RemoveAllRepeatableExpectationsForProxy(object proxy); - - /// - /// 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. - void ReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation); - - /// - /// Gets a value indicating whether this instance has expectations that weren't satisfied yet. - /// - /// - /// true if this instance has expectations; otherwise, false. - /// - bool HasExpectations { get; } - - /// - /// Adds the recorder and turn it into the active recorder. - /// - /// Recorder. - void AddRecorder(IMethodRecorder recorder); - - /// - /// Moves to previous recorder. - /// - bool MoveToPreviousRecorder(); - - /// - /// Gets the recorded expectation or null. - /// - IExpectation GetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args); - - /// - /// Gets the next expected calls string. - /// - string GetExpectedCallsMessage(); - - /// - /// Moves to parent recorder. - /// - void MoveToParentReplayer(); - - /// - /// Set the expectation so it can repeat any number of times. - /// - void AddToRepeatableMethods(object proxy, MethodInfo method, IExpectation expectation); - - /// - /// Removes the expectation from the recorder - /// - void RemoveExpectation(IExpectation expectation); - - /// - /// 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 - /// - void ClearReplayerToCall(IMethodRecorder childReplayer); - - /// - /// Get the expectation for this method on this object with this arguments - /// - ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Generated; + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Records the actions on all the mocks created by a repository. + /// + public interface IMethodRecorder + { + /// + /// Records the specified call with the specified args on the mocked object. + /// + void Record(object proxy, MethodInfo method, IExpectation expectation); + + /// + /// Get the expectation for this method on this object with this arguments + /// + IExpectation GetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args); + + /// + /// This check the methods that were setup using the SetupResult.For() + /// or LastCall.Repeat.Any() and that bypass the whole expectation model. + /// + IExpectation GetRepeatableExpectation(object proxy, MethodInfo method, object[] args); + + /// + /// 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 + ExpectationsList GetAllExpectationsForProxyAndMethod(object proxy, MethodInfo method); + + /// + /// Gets the all expectations for proxy. + /// + /// Mocked object. + /// List of all relevant expectation + ExpectationsList GetAllExpectationsForProxy(object proxy); + + /// + /// Removes all the repeatable expectations for proxy. + /// + /// Mocked object. + void RemoveAllRepeatableExpectationsForProxy(object proxy); + + /// + /// 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. + void ReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation); + + /// + /// Gets a value indicating whether this instance has expectations that weren't satisfied yet. + /// + /// + /// true if this instance has expectations; otherwise, false. + /// + bool HasExpectations { get; } + + /// + /// Adds the recorder and turn it into the active recorder. + /// + /// Recorder. + void AddRecorder(IMethodRecorder recorder); + + /// + /// Moves to previous recorder. + /// + bool MoveToPreviousRecorder(); + + /// + /// Gets the recorded expectation or null. + /// + IExpectation GetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args); + + /// + /// Gets the next expected calls string. + /// + string GetExpectedCallsMessage(); + + /// + /// Moves to parent recorder. + /// + void MoveToParentReplayer(); + + /// + /// Set the expectation so it can repeat any number of times. + /// + void AddToRepeatableMethods(object proxy, MethodInfo method, IExpectation expectation); + + /// + /// Removes the expectation from the recorder + /// + void RemoveExpectation(IExpectation expectation); + + /// + /// 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 + /// + void ClearReplayerToCall(IMethodRecorder childReplayer); + + /// + /// Get the expectation for this method on this object with this arguments + /// + ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IMockState.cs b/Rhino.Mocks/Interfaces/IMockState.cs index 2aeaafbb..fa09d0ee 100644 --- a/Rhino.Mocks/Interfaces/IMockState.cs +++ b/Rhino.Mocks/Interfaces/IMockState.cs @@ -1,94 +1,94 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using Castle.Core.Interceptor; - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Different actions on this mock - /// - public interface IMockState - { - /// - /// 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 - object MethodCall(IInvocation invocation, MethodInfo method, params object[] args); - - /// - /// Verify that this mock expectations have passed. - /// - void Verify(); - - /// - /// Gets the matching verify state for this state - /// - IMockState VerifyState { get; } - - /// - /// Verify that we can move to replay state and move - /// to the reply state. - /// - IMockState Replay(); - - /// - /// Gets a mock state that match the original mock state of the object. - /// - IMockState BackToRecord(); - - /// - /// Get the options for the last method call - /// - IMethodOptions GetLastMethodOptions(); - - /// - /// Get the options for the last method call - /// - IMethodOptions LastMethodOptions { get; } - - /// - /// 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. - /// - void SetExceptionToThrowOnVerify(Exception ex); - - /// - /// 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(). - /// - void NotifyCallOnPropertyBehavior(); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using Castle.Core.Interceptor; + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Different actions on this mock + /// + public interface IMockState + { + /// + /// 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 + object MethodCall(IInvocation invocation, MethodInfo method, params object[] args); + + /// + /// Verify that this mock expectations have passed. + /// + void Verify(); + + /// + /// Gets the matching verify state for this state + /// + IMockState VerifyState { get; } + + /// + /// Verify that we can move to replay state and move + /// to the reply state. + /// + IMockState Replay(); + + /// + /// Gets a mock state that match the original mock state of the object. + /// + IMockState BackToRecord(); + + /// + /// Get the options for the last method call + /// + IMethodOptions GetLastMethodOptions(); + + /// + /// Get the options for the last method call + /// + IMethodOptions LastMethodOptions { get; } + + /// + /// 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. + /// + void SetExceptionToThrowOnVerify(Exception ex); + + /// + /// 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(). + /// + void NotifyCallOnPropertyBehavior(); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IMockedObject.cs b/Rhino.Mocks/Interfaces/IMockedObject.cs index a4c6477e..eacde0df 100644 --- a/Rhino.Mocks/Interfaces/IMockedObject.cs +++ b/Rhino.Mocks/Interfaces/IMockedObject.cs @@ -1,138 +1,138 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections.Generic; - -namespace Rhino.Mocks.Interfaces -{ - using System.Reflection; - - /// - /// Interface to find the repository of a mocked object - /// - public interface IMockedObject - { - /// - /// Mocks that are tied to this mock lifestyle - /// - IList DependentMocks { get; } - - /// - /// The unique hash code of this mock, which is not related - /// to the value of the GetHashCode() call on the object. - /// - int ProxyHash { get; } - - /// - /// Gets the repository. - /// - MockRepository Repository { get; } - - /// - /// Return true if it should call the original method on the object - /// instead of pass it to the message chain. - /// - /// The method to call - bool ShouldCallOriginal(MethodInfo method); - - /// - /// Register a method to be called on the object directly - /// - void RegisterMethodForCallingOriginal(MethodInfo method); - - /// - /// Register a property on the object that will behave as a simple property - /// - bool RegisterPropertyBehaviorFor(PropertyInfo prop); - - /// - /// Check if the method was registered as a property method. - /// - bool IsPropertyMethod(MethodInfo method); - - /// - /// Do get/set on the property, according to need. - /// - object HandleProperty(MethodInfo method, object[] args); - - /// - /// Do add/remove on the event - /// - void HandleEvent(MethodInfo method, object[] args); - - /// - /// Get the subscribers of a spesific event - /// - Delegate GetEventSubscribers(string eventName); - - - /// - /// Gets the declaring type of the method, taking into acccount the possible generic - /// parameters that it was created with. - /// - Type GetDeclaringType(MethodInfo info); - - /// - /// Clears the state of the object, remove original calls, property behavior, subscribed events, etc. - /// - void ClearState(BackToRecordOptions options); - - /// - /// Gets the implemented types by this mocked object - /// - /// The implemented. - Type[] ImplementedTypes { get; } - - /// - /// Gets or sets the constructor arguments. - /// - /// The constructor arguments. - object[] ConstructorArguments { get; set; } - - /// - /// The mocked instance that this is representing - /// - object MockedObjectInstance { get; set; } - - /// - /// Get all the method calls arguments that were made against this object with the specificed - /// method. - /// - /// - /// Only method calls in replay mode are counted - /// - ICollection GetCallArgumentsFor(MethodInfo method); - - /// - /// Records the method call - /// - void MethodCall(MethodInfo method, object[] args); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections.Generic; + +namespace Rhino.Mocks.Interfaces +{ + using System.Reflection; + + /// + /// Interface to find the repository of a mocked object + /// + public interface IMockedObject + { + /// + /// Mocks that are tied to this mock lifestyle + /// + IList DependentMocks { get; } + + /// + /// The unique hash code of this mock, which is not related + /// to the value of the GetHashCode() call on the object. + /// + int ProxyHash { get; } + + /// + /// Gets the repository. + /// + MockRepository Repository { get; } + + /// + /// Return true if it should call the original method on the object + /// instead of pass it to the message chain. + /// + /// The method to call + bool ShouldCallOriginal(MethodInfo method); + + /// + /// Register a method to be called on the object directly + /// + void RegisterMethodForCallingOriginal(MethodInfo method); + + /// + /// Register a property on the object that will behave as a simple property + /// + bool RegisterPropertyBehaviorFor(PropertyInfo prop); + + /// + /// Check if the method was registered as a property method. + /// + bool IsPropertyMethod(MethodInfo method); + + /// + /// Do get/set on the property, according to need. + /// + object HandleProperty(MethodInfo method, object[] args); + + /// + /// Do add/remove on the event + /// + void HandleEvent(MethodInfo method, object[] args); + + /// + /// Get the subscribers of a spesific event + /// + Delegate GetEventSubscribers(string eventName); + + + /// + /// Gets the declaring type of the method, taking into acccount the possible generic + /// parameters that it was created with. + /// + Type GetDeclaringType(MethodInfo info); + + /// + /// Clears the state of the object, remove original calls, property behavior, subscribed events, etc. + /// + void ClearState(BackToRecordOptions options); + + /// + /// Gets the implemented types by this mocked object + /// + /// The implemented. + Type[] ImplementedTypes { get; } + + /// + /// Gets or sets the constructor arguments. + /// + /// The constructor arguments. + object[] ConstructorArguments { get; set; } + + /// + /// The mocked instance that this is representing + /// + object MockedObjectInstance { get; set; } + + /// + /// Get all the method calls arguments that were made against this object with the specificed + /// method. + /// + /// + /// Only method calls in replay mode are counted + /// + ICollection GetCallArgumentsFor(MethodInfo method); + + /// + /// Records the method call + /// + void MethodCall(MethodInfo method, object[] args); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IPartialMockMarker.cs b/Rhino.Mocks/Interfaces/IPartialMockMarker.cs index 879f213f..be25c0bd 100644 --- a/Rhino.Mocks/Interfaces/IPartialMockMarker.cs +++ b/Rhino.Mocks/Interfaces/IPartialMockMarker.cs @@ -1,38 +1,38 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Marker interface used to indicate that this is a partial mock. - /// - public interface IPartialMockMarker - { - - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Marker interface used to indicate that this is a partial mock. + /// + public interface IPartialMockMarker + { + + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/IRepeat.cs b/Rhino.Mocks/Interfaces/IRepeat.cs index 01a2b375..dd1f1b45 100644 --- a/Rhino.Mocks/Interfaces/IRepeat.cs +++ b/Rhino.Mocks/Interfaces/IRepeat.cs @@ -1,126 +1,126 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -namespace Rhino.Mocks.Interfaces -{ - /* - * interface: IRepeat - * - * Allows to specified the number of times a method is called. - */ - /// - /// Allows to specify the number of time for method calls - /// - public interface IRepeat - { - /* - * Method: Twice - * - * The method will repeat twice - */ - /// - /// Repeat the method twice. - /// - IMethodOptions Twice(); - - /* - * Method: Once - * - * The method will repeat once. - * - * note: - * This is the default behaviour. - */ - /// - /// Repeat the method once. - /// - IMethodOptions Once(); - - - /// - /// Repeat the method at least once, then repeat as many time as it would like. - /// - IMethodOptions AtLeastOnce(); - - /* - * Method: Any - * - * Repeat the method any number of times. - * - * note: - * This has special affects in that this method would now ignore orderring. - */ - /// - /// Repeat the method any number of times. - /// This has special affects in that this method would now ignore orderring. - /// - IMethodOptions Any(); - - /* - * Method: Times - * - * Repeat the method the specified number of time between min & max. - * - * Params: - * - min - The minimum number of times the method can repeat - * - max - The maximum number of times the method can repeat - * - */ - /// - /// Set the range to repeat an action. - /// - /// Min. - /// Max. - IMethodOptions Times(int min, int max); - - /* - * Method: Times - * - * Set the exact number of times this method can repeat. - */ - /// - /// Set the amount of times to repeat an action. - /// - IMethodOptions Times(int count); - - /* - * Method: Never - * - * This method must not appear in the replay state. - * - * note: - * This has special affects in that this method would now ignore orderring. - */ - /// - /// This method must not appear in the replay state. - /// This has special affects in that this method would now ignore orderring. - /// - IMethodOptions Never(); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +namespace Rhino.Mocks.Interfaces +{ + /* + * interface: IRepeat + * + * Allows to specified the number of times a method is called. + */ + /// + /// Allows to specify the number of time for method calls + /// + public interface IRepeat + { + /* + * Method: Twice + * + * The method will repeat twice + */ + /// + /// Repeat the method twice. + /// + IMethodOptions Twice(); + + /* + * Method: Once + * + * The method will repeat once. + * + * note: + * This is the default behaviour. + */ + /// + /// Repeat the method once. + /// + IMethodOptions Once(); + + + /// + /// Repeat the method at least once, then repeat as many time as it would like. + /// + IMethodOptions AtLeastOnce(); + + /* + * Method: Any + * + * Repeat the method any number of times. + * + * note: + * This has special affects in that this method would now ignore orderring. + */ + /// + /// Repeat the method any number of times. + /// This has special affects in that this method would now ignore orderring. + /// + IMethodOptions Any(); + + /* + * Method: Times + * + * Repeat the method the specified number of time between min & max. + * + * Params: + * - min - The minimum number of times the method can repeat + * - max - The maximum number of times the method can repeat + * + */ + /// + /// Set the range to repeat an action. + /// + /// Min. + /// Max. + IMethodOptions Times(int min, int max); + + /* + * Method: Times + * + * Set the exact number of times this method can repeat. + */ + /// + /// Set the amount of times to repeat an action. + /// + IMethodOptions Times(int count); + + /* + * Method: Never + * + * This method must not appear in the replay state. + * + * note: + * This has special affects in that this method would now ignore orderring. + */ + /// + /// This method must not appear in the replay state. + /// This has special affects in that this method would now ignore orderring. + /// + IMethodOptions Never(); + } } \ No newline at end of file diff --git a/Rhino.Mocks/Interfaces/OriginalCallOptions.cs b/Rhino.Mocks/Interfaces/OriginalCallOptions.cs index 3dbbbd96..afc4fd0b 100644 --- a/Rhino.Mocks/Interfaces/OriginalCallOptions.cs +++ b/Rhino.Mocks/Interfaces/OriginalCallOptions.cs @@ -1,46 +1,46 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -namespace Rhino.Mocks.Interfaces -{ - /// - /// Options for CallOriginalMethod - /// - public enum OriginalCallOptions - { - /// - /// No expectation is created, the method will be called directly - /// - NoExpectation, - /// - /// Normal expectation is created, but when the method is later called, it will also call the original method - /// - CreateExpectation - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +namespace Rhino.Mocks.Interfaces +{ + /// + /// Options for CallOriginalMethod + /// + public enum OriginalCallOptions + { + /// + /// No expectation is created, the method will be called directly + /// + NoExpectation, + /// + /// Normal expectation is created, but when the method is later called, it will also call the original method + /// + CreateExpectation + } } \ No newline at end of file diff --git a/Rhino.Mocks/LastCall.cs b/Rhino.Mocks/LastCall.cs index 16df2d9c..03f2daef 100644 --- a/Rhino.Mocks/LastCall.cs +++ b/Rhino.Mocks/LastCall.cs @@ -1,391 +1,391 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Constraints; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks -{ - /* - * Class: LastCall - * Allows to set options for the method calls. - * note: - * If the method has a return value, it's recommended to use - * - */ - /// - /// 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 - /// - public static class LastCall - { - /* - * Method: On - * Gets the method options for the last call for mockedInstance. - * This is the recommended approach for multi threaded scenarios. - * - * Expected usage: - * (start code) - * LastCall.On(mockObj).Return(4); - * (end) - * - * Thread safety: - * This method is safe to use in multi threading scenarios. - */ - /// - /// 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 - public static IMethodOptions On(object mockedInstance) - { - IMockedObject mockedObj = MockRepository.GetMockedObject(mockedInstance); - return mockedObj.Repository.LastMethodCall(mockedInstance); - } - - /* - * Method: GetOptions - * *Internal!* - * - * Get the method options for the last method call from *all* the mock objects. - * Throws an exception if there is no such call. - * - * Thread safety: - * *Not* safe for mutli threading, use - */ - internal static IMethodOptions GetOptions() - { - if (MockRepository.LastMockedObject == null) - throw new InvalidOperationException("Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)."); - return MockRepository.lastRepository.LastMethodCall(MockRepository.LastMockedObject); - } - - /* - * Method: Return - * - * Sets the return value when the method is called. - * - * Thread safety: - * *Not* safe for mutli threading, use * - */ - /// - /// 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 - public static IMethodOptions Return(T objToReturn) - { - return GetOptions().Return(objToReturn); - } - - /// - /// 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 - public static IMethodOptions Return(object objToReturn) - { - return GetOptions().Return(objToReturn); - } - - /* - * Method: Throw - * - * Throws the specified exception when the method is called. - * - * Thread safety: - * *Not* safe for mutli threading, use - */ - /// - /// Throws the specified exception when the method is called. - /// - /// Exception to throw - public static IMethodOptions Throw(Exception exception) - { - return GetOptions().Throw(exception); - } - - /* - * Method: IgnoreArguments - * - * Ignores the arguments for this method. Any arguments are considered fine for this - * method. - * - * Thread safety: - * *Not* safe for mutli threading, use - */ - /// - /// Ignores the arguments for this method. Any argument will be matched - /// againt this method. - /// - public static IMethodOptions IgnoreArguments() - { - return GetOptions().IgnoreArguments(); - } - - /* - * Property: Repeat - * - * Allows to get the instance that would allow to - * set the expected number of times that this method will occur. - * - * Thread safety: - * *Not* safe for mutli threading, use - */ - /// - /// Better syntax to define repeats. - /// - public static IRepeat Repeat - { - get { return GetOptions().Repeat; } - } - - /* - * Method: Constraints - * - * Sets the contraints on this method parameters. - * The number of the constraints *must* be equal to the number of method arguments. - * - * Thread safety: - * *Not* safe for mutli threading, use - */ - /// - /// Add constraints for the method's arguments. - /// - public static IMethodOptions Constraints(params AbstractConstraint[] constraints) - { - return GetOptions().Constraints(constraints); - } - - /* - * Method: Callback - * - * Sets a callback delegate to be called when this method is called. - * - * Important: - * The callback *must* have the same signature as the last method call but its return value - * *must* be a boolean. - * The callback will be called with the same parameters as the method and the method will - * be accepted if the delegate return a positive value. - * Note: - * The callback may be called several times - * - * Thread safety: - * *Not* safe for mutli threading, use - */ - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback(Delegate callback) - { - return GetOptions().Callback(callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback(Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback(Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback(Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback(Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Set a callback method for the last call - /// - public static IMethodOptions Callback( - Delegates.Function callback) - { - return Callback((Delegate)callback); - } - - /// - /// Call the original method on the class, bypassing the mocking layers, for the last call. - /// - [Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")] - public static void CallOriginalMethod() - { - GetOptions().CallOriginalMethod(); - } - - - /// - /// Call the original method on the class, optionally bypassing the mocking layers, for the last call. - /// - public static IMethodOptions CallOriginalMethod(OriginalCallOptions options) - { - return GetOptions().CallOriginalMethod(options); - } - - /* - * Method: Do - * - * Set an action to run when the expectation is matched. - * - * Important: - * The action's delegate *must* have the same signature as the last methdo call, and its return - * value must be assignable to the last method call return value. - * - * Note: - * This method is only called once, after the method call was match to the expectation. - * - * - */ - /// - /// Set a delegate to be called when the expectation is matched. - /// The delegate return value will be returned from the expectation. - /// - public static IMethodOptions Do(Delegate action) - { - return GetOptions().Do(action); - } - - /// - /// Gets an interface that will raise the last event when called. - /// - public static IEventRaiser GetEventRaiser() - { - return GetOptions().GetEventRaiser(); - } - - /// - /// Set the parameter values for out and ref parameters. - /// This is done using zero based indexing, and _ignoring_ any non out/ref parameter. - /// - public static IMethodOptions OutRef(params object[] parameters) - { - return GetOptions().OutRef(parameters); - } - - /// - /// Documentation message for the expectation - /// - /// Message - public static IMethodOptions Message(string documentationMessage) - { - return GetOptions().Message(documentationMessage); - } - - /* Method: PropertyBehavior - * - * Use the property as a normal property, so you can use it to save/load values - * without having to specify expectations for it. - * - * Note: - * This can be called only when the last call is a getter or setter. - */ - /// - /// Use the property as a simple property, getting/setting the values without - /// causing mock expectations. - /// - public static IMethodOptions PropertyBehavior() - { - return GetOptions().PropertyBehavior(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Constraints; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks +{ + /* + * Class: LastCall + * Allows to set options for the method calls. + * note: + * If the method has a return value, it's recommended to use + * + */ + /// + /// 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 + /// + public static class LastCall + { + /* + * Method: On + * Gets the method options for the last call for mockedInstance. + * This is the recommended approach for multi threaded scenarios. + * + * Expected usage: + * (start code) + * LastCall.On(mockObj).Return(4); + * (end) + * + * Thread safety: + * This method is safe to use in multi threading scenarios. + */ + /// + /// 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 + public static IMethodOptions On(object mockedInstance) + { + IMockedObject mockedObj = MockRepository.GetMockedObject(mockedInstance); + return mockedObj.Repository.LastMethodCall(mockedInstance); + } + + /* + * Method: GetOptions + * *Internal!* + * + * Get the method options for the last method call from *all* the mock objects. + * Throws an exception if there is no such call. + * + * Thread safety: + * *Not* safe for mutli threading, use + */ + internal static IMethodOptions GetOptions() + { + if (MockRepository.LastMockedObject == null) + throw new InvalidOperationException("Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method)."); + return MockRepository.lastRepository.LastMethodCall(MockRepository.LastMockedObject); + } + + /* + * Method: Return + * + * Sets the return value when the method is called. + * + * Thread safety: + * *Not* safe for mutli threading, use * + */ + /// + /// 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 + public static IMethodOptions Return(T objToReturn) + { + return GetOptions().Return(objToReturn); + } + + /// + /// 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 + public static IMethodOptions Return(object objToReturn) + { + return GetOptions().Return(objToReturn); + } + + /* + * Method: Throw + * + * Throws the specified exception when the method is called. + * + * Thread safety: + * *Not* safe for mutli threading, use + */ + /// + /// Throws the specified exception when the method is called. + /// + /// Exception to throw + public static IMethodOptions Throw(Exception exception) + { + return GetOptions().Throw(exception); + } + + /* + * Method: IgnoreArguments + * + * Ignores the arguments for this method. Any arguments are considered fine for this + * method. + * + * Thread safety: + * *Not* safe for mutli threading, use + */ + /// + /// Ignores the arguments for this method. Any argument will be matched + /// againt this method. + /// + public static IMethodOptions IgnoreArguments() + { + return GetOptions().IgnoreArguments(); + } + + /* + * Property: Repeat + * + * Allows to get the instance that would allow to + * set the expected number of times that this method will occur. + * + * Thread safety: + * *Not* safe for mutli threading, use + */ + /// + /// Better syntax to define repeats. + /// + public static IRepeat Repeat + { + get { return GetOptions().Repeat; } + } + + /* + * Method: Constraints + * + * Sets the contraints on this method parameters. + * The number of the constraints *must* be equal to the number of method arguments. + * + * Thread safety: + * *Not* safe for mutli threading, use + */ + /// + /// Add constraints for the method's arguments. + /// + public static IMethodOptions Constraints(params AbstractConstraint[] constraints) + { + return GetOptions().Constraints(constraints); + } + + /* + * Method: Callback + * + * Sets a callback delegate to be called when this method is called. + * + * Important: + * The callback *must* have the same signature as the last method call but its return value + * *must* be a boolean. + * The callback will be called with the same parameters as the method and the method will + * be accepted if the delegate return a positive value. + * Note: + * The callback may be called several times + * + * Thread safety: + * *Not* safe for mutli threading, use + */ + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback(Delegate callback) + { + return GetOptions().Callback(callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback(Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback(Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback(Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback(Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Set a callback method for the last call + /// + public static IMethodOptions Callback( + Delegates.Function callback) + { + return Callback((Delegate)callback); + } + + /// + /// Call the original method on the class, bypassing the mocking layers, for the last call. + /// + [Obsolete("Use CallOriginalMethod(OriginalCallOptions options) overload to explicitly specify the call options")] + public static void CallOriginalMethod() + { + GetOptions().CallOriginalMethod(); + } + + + /// + /// Call the original method on the class, optionally bypassing the mocking layers, for the last call. + /// + public static IMethodOptions CallOriginalMethod(OriginalCallOptions options) + { + return GetOptions().CallOriginalMethod(options); + } + + /* + * Method: Do + * + * Set an action to run when the expectation is matched. + * + * Important: + * The action's delegate *must* have the same signature as the last methdo call, and its return + * value must be assignable to the last method call return value. + * + * Note: + * This method is only called once, after the method call was match to the expectation. + * + * + */ + /// + /// Set a delegate to be called when the expectation is matched. + /// The delegate return value will be returned from the expectation. + /// + public static IMethodOptions Do(Delegate action) + { + return GetOptions().Do(action); + } + + /// + /// Gets an interface that will raise the last event when called. + /// + public static IEventRaiser GetEventRaiser() + { + return GetOptions().GetEventRaiser(); + } + + /// + /// Set the parameter values for out and ref parameters. + /// This is done using zero based indexing, and _ignoring_ any non out/ref parameter. + /// + public static IMethodOptions OutRef(params object[] parameters) + { + return GetOptions().OutRef(parameters); + } + + /// + /// Documentation message for the expectation + /// + /// Message + public static IMethodOptions Message(string documentationMessage) + { + return GetOptions().Message(documentationMessage); + } + + /* Method: PropertyBehavior + * + * Use the property as a normal property, so you can use it to save/load values + * without having to specify expectations for it. + * + * Note: + * This can be called only when the last call is a getter or setter. + */ + /// + /// Use the property as a simple property, getting/setting the values without + /// causing mock expectations. + /// + public static IMethodOptions PropertyBehavior() + { + return GetOptions().PropertyBehavior(); + } + } +} diff --git a/Rhino.Mocks/MethodInvocation.cs b/Rhino.Mocks/MethodInvocation.cs index 68d1ad5a..914e5b13 100644 --- a/Rhino.Mocks/MethodInvocation.cs +++ b/Rhino.Mocks/MethodInvocation.cs @@ -1,57 +1,57 @@ -using System; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks -{ - /// - /// This is a data structure that is used by - /// to pass - /// the current method to the relevant delegate - /// - public class MethodInvocation - { - private readonly IInvocation invocation; - - /// - /// Initializes a new instance of the class. - /// - /// The invocation. - internal MethodInvocation(IInvocation invocation) - { - this.invocation = invocation; - } - - /// - /// Gets the args for this method invocation - /// - public object[] Arguments - { - get { return invocation.Arguments; } - } - - /// - /// Get the method that was caused this invocation - /// - public MethodInfo Method - { - get - { - return invocation.Method; - } - } - - /// - /// Gets or sets the return value for this method invocation - /// - /// The return value. - public object ReturnValue - { - get { return invocation.ReturnValue; } - set { invocation.ReturnValue = value; } - } - - - } +using System; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks +{ + /// + /// This is a data structure that is used by + /// to pass + /// the current method to the relevant delegate + /// + public class MethodInvocation + { + private readonly IInvocation invocation; + + /// + /// Initializes a new instance of the class. + /// + /// The invocation. + internal MethodInvocation(IInvocation invocation) + { + this.invocation = invocation; + } + + /// + /// Gets the args for this method invocation + /// + public object[] Arguments + { + get { return invocation.Arguments; } + } + + /// + /// Get the method that was caused this invocation + /// + public MethodInfo Method + { + get + { + return invocation.Method; + } + } + + /// + /// Gets or sets the return value for this method invocation + /// + /// The return value. + public object ReturnValue + { + get { return invocation.ReturnValue; } + set { invocation.ReturnValue = value; } + } + + + } } \ No newline at end of file diff --git a/Rhino.Mocks/MethodRecorders/MethodRecorderBase.cs b/Rhino.Mocks/MethodRecorders/MethodRecorderBase.cs index 214e48be..108a511f 100644 --- a/Rhino.Mocks/MethodRecorders/MethodRecorderBase.cs +++ b/Rhino.Mocks/MethodRecorders/MethodRecorderBase.cs @@ -1,445 +1,445 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Diagnostics; -using System.Reflection; -using Castle.Core.Interceptor; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Generated; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; -using System.Collections; - -namespace Rhino.Mocks.MethodRecorders -{ - /// - /// Base class for method recorders, handle delegating to inner recorder if needed. - /// - public abstract class MethodRecorderBase : IMethodRecorder - { - /// - /// List of the expected actions on for this recorder - /// The legal values are: - /// * Expectations - /// * Method Recorders - /// - protected IList recordedActions = new ArrayList(); - - /// - /// The current recorder. - /// - protected IMethodRecorder recorderToCall; - - /// - /// The current replayer; - /// - protected IMethodRecorder replayerToCall; - - /// - /// The parent recorder of this one, may be null. - /// - protected IMethodRecorder parentRecorder; - - /// - /// 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. - /// - private readonly IList replayersToIgnoreForThisCall = new ArrayList(); - - /// - /// All the repeatable methods calls. - /// - private ProxyMethodExpectationsDictionary repeatableMethods; - - /// - /// Counts the recursion depth of the current expectation search stack - /// - private int recursionDepth = 0; - - /// - /// Creates a new instance. - /// - protected MethodRecorderBase(ProxyMethodExpectationsDictionary repeatableMethods) - { - this.repeatableMethods = repeatableMethods; - recorderToCall = null; - replayerToCall = null; - } - - /// - /// Creates a new instance. - /// - /// Parent recorder. - /// Repeatable methods - protected MethodRecorderBase(IMethodRecorder parentRecorder, ProxyMethodExpectationsDictionary repeatableMethods) - : this(repeatableMethods) - { - this.parentRecorder = parentRecorder; - } - - /// - /// Records the specified call with the specified args on the mocked object. - /// - public void Record(object proxy, MethodInfo method, IExpectation expectation) - { - if (recorderToCall != null) - recorderToCall.Record(proxy, method, expectation); - else - DoRecord(proxy, method, expectation); - } - - /// - /// Get the expectation for this method on this object with this arguments - /// - public IExpectation GetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - Validate.IsNotNull(args, "args"); - if (replayerToCall != null) - return replayerToCall.GetRecordedExpectation(invocation, proxy, method, args); - - //merge recorders that contains only a single empty recorder - if (recordedActions.Count == 1 && recordedActions[0] is IMethodRecorder) - { - replayerToCall = (IMethodRecorder)recordedActions[0]; - return replayerToCall.GetRecordedExpectation(invocation, proxy, method, args); - } - - IExpectation expectation = DoGetRecordedExpectation(invocation, proxy, method, args); - if (HasExpectations == false) - MoveToParentReplayer(); - return expectation; - - } - - /// - /// 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 - public abstract ExpectationsList GetAllExpectationsForProxyAndMethod(object proxy, MethodInfo method); - - /// - /// Gets the all expectations for proxy. - /// - /// Mocked object. - /// List of all relevant expectation - public ExpectationsList GetAllExpectationsForProxy(object proxy) - { - ExpectationsList fromChild = null, mine; - if (replayerToCall != null) - fromChild = replayerToCall.GetAllExpectationsForProxy(proxy); - mine = DoGetAllExpectationsForProxy(proxy); - if (fromChild != null) - { - foreach (IExpectation expectation in fromChild) - { - if (mine.Contains(expectation) == false) - mine.Add(expectation); - } - } - return mine; - } - - /// - /// 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. - public void ReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation) - { - if (TryReplaceRepeatableExpectation(method, newExpectation, oldExpectation, proxy)) - return; - if (recorderToCall != null) - recorderToCall.ReplaceExpectation(proxy, method, oldExpectation, newExpectation); - else - DoReplaceExpectation(proxy, method, oldExpectation, newExpectation); - } - - private bool TryReplaceRepeatableExpectation(MethodInfo method, IExpectation newExpectation, IExpectation oldExpectation, object proxy) - { - ProxyMethodPair pair = new ProxyMethodPair(proxy, method); - if (repeatableMethods.ContainsKey(pair)) - { - ExpectationsList expectationsList = repeatableMethods[pair]; - int indexOf = expectationsList.IndexOf(oldExpectation); - if (indexOf != -1) - { - expectationsList[indexOf] = newExpectation; - return true; - } - } - return false; - } - - /// - /// Remove the all repeatable expectations for proxy. - /// - /// Mocked object. - public void RemoveAllRepeatableExpectationsForProxy(object proxy) - { - ProxyMethodPair[] keys = new ProxyMethodPair[repeatableMethods.Keys.Count]; - repeatableMethods.Keys.CopyTo(keys, 0); - foreach (ProxyMethodPair pair in keys) - { - if (MockedObjectsEquality.Instance.Equals(pair.Proxy, proxy)) - repeatableMethods.Remove(pair); - } - } - - /// - /// Gets a value indicating whether this instance has expectations that weren't satisfied yet. - /// - /// - /// true if this instance has expectations; otherwise, false. - /// - public bool HasExpectations - { - get - { - if (replayerToCall != null) - return replayerToCall.HasExpectations; - return DoHasExpectations; - } - } - - - /// - /// Set the expectation so it can repeat any number of times. - /// - public void AddToRepeatableMethods(object proxy, MethodInfo method, IExpectation expectation) - { - //Just to get an error if I make a mistake and try to add a normal - //method to the speical repeat method - Debug.Assert(expectation.RepeatableOption != RepeatableOption.Normal); - RemoveExpectation(expectation); - ProxyMethodPair pair = new ProxyMethodPair(proxy, method); - if (repeatableMethods.ContainsKey(pair) == false) - repeatableMethods.Add(pair, new ExpectationsList()); - ExpectationsList expectationsList = repeatableMethods[pair]; - ExpectationNotOnList(expectationsList, expectation, - MockRepository.IsStub(proxy)); - expectationsList.Add(expectation); - } - - /// - /// Removes the expectation from the recorder - /// - public void RemoveExpectation(IExpectation expectation) - { - if (recorderToCall != null) - recorderToCall.RemoveExpectation(expectation); - else - DoRemoveExpectation(expectation); - } - - /// - /// Adds the recorder and turn it into the active recorder. - /// - /// Recorder. - public void AddRecorder(IMethodRecorder recorder) - { - if (recorderToCall != null) - recorderToCall.AddRecorder(recorder); - else - { - DoAddRecorder(recorder); - recorderToCall = recorder; - } - } - - /// - /// Moves to previous recorder. - /// - public bool MoveToPreviousRecorder() - { - if (recorderToCall == null) - return true; - if (recorderToCall.MoveToPreviousRecorder()) - recorderToCall = null; - return false; - } - - /// - /// Moves to parent recorder. - /// - public void MoveToParentReplayer() - { - replayerToCall = null; - if (parentRecorder == null || HasExpectations) - return; - parentRecorder.MoveToParentReplayer(); - } - - /// - /// Gets the recorded expectation or null. - /// - public IExpectation GetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args) - { - recursionDepth += 1; - try - { - if (replayerToCall != null) - return replayerToCall.GetRecordedExpectationOrNull(proxy, method, args); - else - return DoGetRecordedExpectationOrNull(proxy, method, args); - } - finally - { - recursionDepth -= 1; - if (recursionDepth == 0) - replayersToIgnoreForThisCall.Clear(); - } - } - - /// - /// 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 - /// - public void ClearReplayerToCall(IMethodRecorder childReplayer) - { - replayerToCall = null; - //recordedActions.Remove(childReplayer); - replayersToIgnoreForThisCall.Add(childReplayer); - } - - /// - /// Get the expectation for this method on this object with this arguments - /// - public abstract ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args); - - /// - /// Gets the next expected calls string. - /// - public abstract string GetExpectedCallsMessage(); - - #region Protected Methods - - - /// - /// Handles the real getting of the recorded expectation or null. - /// - protected abstract IExpectation DoGetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args); - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract void DoRecord(object proxy, MethodInfo method, IExpectation expectation); - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract IExpectation DoGetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args); - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract ExpectationsList DoGetAllExpectationsForProxy(object proxy); - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract void DoReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation); - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract bool DoHasExpectations { get; } - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract void DoRemoveExpectation(IExpectation expectation); - - - /// - /// Handle the real execution of this method for the derived class - /// - protected abstract void DoAddRecorder(IMethodRecorder recorder); - - #endregion - - /// - /// Should this replayer be considered valid for this call? - /// - protected bool ShouldConsiderThisReplayer(IMethodRecorder replayer) - { - return replayersToIgnoreForThisCall.Contains(replayer) == false; - } - - /// - /// This check the methods that were setup using the SetupResult.For() - /// or LastCall.Repeat.Any() and that bypass the whole expectation model. - /// - public IExpectation GetRepeatableExpectation(object proxy, MethodInfo method, object[] args) - { - ProxyMethodPair pair = new ProxyMethodPair(proxy, method); - if (repeatableMethods.ContainsKey(pair) == false) - return null; - ExpectationsList list = repeatableMethods[pair]; - foreach (IExpectation expectation in list) - { - if (expectation.IsExpected(args)) - { - expectation.AddActualCall(); - if (expectation.RepeatableOption == RepeatableOption.Never) - { - string errMsg = string.Format("{0} Expected #{1}, Actual #{2}.", expectation.ErrorMessage, expectation.Expected, expectation.ActualCallsCount); - ExpectationViolationException exception = new ExpectationViolationException(errMsg); - MockRepository.SetExceptionToBeThrownOnVerify(proxy, exception); - throw exception; - } - return expectation; - } - } - return null; - } - - private void ExpectationNotOnList(ExpectationsList list, IExpectation expectation, bool isStub) - { - bool expectationExists = list.Contains(expectation); - if (expectationExists == false) - return; - bool isProeprty = expectation.Method.IsSpecialName && - (expectation.Method.Name.StartsWith("get_") || - expectation.Method.Name.StartsWith("set_")); - if (isStub == false || isProeprty == false) - throw new InvalidOperationException("The result for " + expectation.ErrorMessage + " has already been setup."); - throw new InvalidOperationException("The result for " + expectation.ErrorMessage + " has already been setup. Properties are already stubbed with PropertyBehavior by default, no action is required"); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Diagnostics; +using System.Reflection; +using Castle.Core.Interceptor; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Generated; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; +using System.Collections; + +namespace Rhino.Mocks.MethodRecorders +{ + /// + /// Base class for method recorders, handle delegating to inner recorder if needed. + /// + public abstract class MethodRecorderBase : IMethodRecorder + { + /// + /// List of the expected actions on for this recorder + /// The legal values are: + /// * Expectations + /// * Method Recorders + /// + protected IList recordedActions = new ArrayList(); + + /// + /// The current recorder. + /// + protected IMethodRecorder recorderToCall; + + /// + /// The current replayer; + /// + protected IMethodRecorder replayerToCall; + + /// + /// The parent recorder of this one, may be null. + /// + protected IMethodRecorder parentRecorder; + + /// + /// 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. + /// + private readonly IList replayersToIgnoreForThisCall = new ArrayList(); + + /// + /// All the repeatable methods calls. + /// + private ProxyMethodExpectationsDictionary repeatableMethods; + + /// + /// Counts the recursion depth of the current expectation search stack + /// + private int recursionDepth = 0; + + /// + /// Creates a new instance. + /// + protected MethodRecorderBase(ProxyMethodExpectationsDictionary repeatableMethods) + { + this.repeatableMethods = repeatableMethods; + recorderToCall = null; + replayerToCall = null; + } + + /// + /// Creates a new instance. + /// + /// Parent recorder. + /// Repeatable methods + protected MethodRecorderBase(IMethodRecorder parentRecorder, ProxyMethodExpectationsDictionary repeatableMethods) + : this(repeatableMethods) + { + this.parentRecorder = parentRecorder; + } + + /// + /// Records the specified call with the specified args on the mocked object. + /// + public void Record(object proxy, MethodInfo method, IExpectation expectation) + { + if (recorderToCall != null) + recorderToCall.Record(proxy, method, expectation); + else + DoRecord(proxy, method, expectation); + } + + /// + /// Get the expectation for this method on this object with this arguments + /// + public IExpectation GetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + Validate.IsNotNull(args, "args"); + if (replayerToCall != null) + return replayerToCall.GetRecordedExpectation(invocation, proxy, method, args); + + //merge recorders that contains only a single empty recorder + if (recordedActions.Count == 1 && recordedActions[0] is IMethodRecorder) + { + replayerToCall = (IMethodRecorder)recordedActions[0]; + return replayerToCall.GetRecordedExpectation(invocation, proxy, method, args); + } + + IExpectation expectation = DoGetRecordedExpectation(invocation, proxy, method, args); + if (HasExpectations == false) + MoveToParentReplayer(); + return expectation; + + } + + /// + /// 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 + public abstract ExpectationsList GetAllExpectationsForProxyAndMethod(object proxy, MethodInfo method); + + /// + /// Gets the all expectations for proxy. + /// + /// Mocked object. + /// List of all relevant expectation + public ExpectationsList GetAllExpectationsForProxy(object proxy) + { + ExpectationsList fromChild = null, mine; + if (replayerToCall != null) + fromChild = replayerToCall.GetAllExpectationsForProxy(proxy); + mine = DoGetAllExpectationsForProxy(proxy); + if (fromChild != null) + { + foreach (IExpectation expectation in fromChild) + { + if (mine.Contains(expectation) == false) + mine.Add(expectation); + } + } + return mine; + } + + /// + /// 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. + public void ReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation) + { + if (TryReplaceRepeatableExpectation(method, newExpectation, oldExpectation, proxy)) + return; + if (recorderToCall != null) + recorderToCall.ReplaceExpectation(proxy, method, oldExpectation, newExpectation); + else + DoReplaceExpectation(proxy, method, oldExpectation, newExpectation); + } + + private bool TryReplaceRepeatableExpectation(MethodInfo method, IExpectation newExpectation, IExpectation oldExpectation, object proxy) + { + ProxyMethodPair pair = new ProxyMethodPair(proxy, method); + if (repeatableMethods.ContainsKey(pair)) + { + ExpectationsList expectationsList = repeatableMethods[pair]; + int indexOf = expectationsList.IndexOf(oldExpectation); + if (indexOf != -1) + { + expectationsList[indexOf] = newExpectation; + return true; + } + } + return false; + } + + /// + /// Remove the all repeatable expectations for proxy. + /// + /// Mocked object. + public void RemoveAllRepeatableExpectationsForProxy(object proxy) + { + ProxyMethodPair[] keys = new ProxyMethodPair[repeatableMethods.Keys.Count]; + repeatableMethods.Keys.CopyTo(keys, 0); + foreach (ProxyMethodPair pair in keys) + { + if (MockedObjectsEquality.Instance.Equals(pair.Proxy, proxy)) + repeatableMethods.Remove(pair); + } + } + + /// + /// Gets a value indicating whether this instance has expectations that weren't satisfied yet. + /// + /// + /// true if this instance has expectations; otherwise, false. + /// + public bool HasExpectations + { + get + { + if (replayerToCall != null) + return replayerToCall.HasExpectations; + return DoHasExpectations; + } + } + + + /// + /// Set the expectation so it can repeat any number of times. + /// + public void AddToRepeatableMethods(object proxy, MethodInfo method, IExpectation expectation) + { + //Just to get an error if I make a mistake and try to add a normal + //method to the speical repeat method + Debug.Assert(expectation.RepeatableOption != RepeatableOption.Normal); + RemoveExpectation(expectation); + ProxyMethodPair pair = new ProxyMethodPair(proxy, method); + if (repeatableMethods.ContainsKey(pair) == false) + repeatableMethods.Add(pair, new ExpectationsList()); + ExpectationsList expectationsList = repeatableMethods[pair]; + ExpectationNotOnList(expectationsList, expectation, + MockRepository.IsStub(proxy)); + expectationsList.Add(expectation); + } + + /// + /// Removes the expectation from the recorder + /// + public void RemoveExpectation(IExpectation expectation) + { + if (recorderToCall != null) + recorderToCall.RemoveExpectation(expectation); + else + DoRemoveExpectation(expectation); + } + + /// + /// Adds the recorder and turn it into the active recorder. + /// + /// Recorder. + public void AddRecorder(IMethodRecorder recorder) + { + if (recorderToCall != null) + recorderToCall.AddRecorder(recorder); + else + { + DoAddRecorder(recorder); + recorderToCall = recorder; + } + } + + /// + /// Moves to previous recorder. + /// + public bool MoveToPreviousRecorder() + { + if (recorderToCall == null) + return true; + if (recorderToCall.MoveToPreviousRecorder()) + recorderToCall = null; + return false; + } + + /// + /// Moves to parent recorder. + /// + public void MoveToParentReplayer() + { + replayerToCall = null; + if (parentRecorder == null || HasExpectations) + return; + parentRecorder.MoveToParentReplayer(); + } + + /// + /// Gets the recorded expectation or null. + /// + public IExpectation GetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args) + { + recursionDepth += 1; + try + { + if (replayerToCall != null) + return replayerToCall.GetRecordedExpectationOrNull(proxy, method, args); + else + return DoGetRecordedExpectationOrNull(proxy, method, args); + } + finally + { + recursionDepth -= 1; + if (recursionDepth == 0) + replayersToIgnoreForThisCall.Clear(); + } + } + + /// + /// 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 + /// + public void ClearReplayerToCall(IMethodRecorder childReplayer) + { + replayerToCall = null; + //recordedActions.Remove(childReplayer); + replayersToIgnoreForThisCall.Add(childReplayer); + } + + /// + /// Get the expectation for this method on this object with this arguments + /// + public abstract ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args); + + /// + /// Gets the next expected calls string. + /// + public abstract string GetExpectedCallsMessage(); + + #region Protected Methods + + + /// + /// Handles the real getting of the recorded expectation or null. + /// + protected abstract IExpectation DoGetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args); + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract void DoRecord(object proxy, MethodInfo method, IExpectation expectation); + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract IExpectation DoGetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args); + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract ExpectationsList DoGetAllExpectationsForProxy(object proxy); + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract void DoReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation); + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract bool DoHasExpectations { get; } + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract void DoRemoveExpectation(IExpectation expectation); + + + /// + /// Handle the real execution of this method for the derived class + /// + protected abstract void DoAddRecorder(IMethodRecorder recorder); + + #endregion + + /// + /// Should this replayer be considered valid for this call? + /// + protected bool ShouldConsiderThisReplayer(IMethodRecorder replayer) + { + return replayersToIgnoreForThisCall.Contains(replayer) == false; + } + + /// + /// This check the methods that were setup using the SetupResult.For() + /// or LastCall.Repeat.Any() and that bypass the whole expectation model. + /// + public IExpectation GetRepeatableExpectation(object proxy, MethodInfo method, object[] args) + { + ProxyMethodPair pair = new ProxyMethodPair(proxy, method); + if (repeatableMethods.ContainsKey(pair) == false) + return null; + ExpectationsList list = repeatableMethods[pair]; + foreach (IExpectation expectation in list) + { + if (expectation.IsExpected(args)) + { + expectation.AddActualCall(); + if (expectation.RepeatableOption == RepeatableOption.Never) + { + string errMsg = string.Format("{0} Expected #{1}, Actual #{2}.", expectation.ErrorMessage, expectation.Expected, expectation.ActualCallsCount); + ExpectationViolationException exception = new ExpectationViolationException(errMsg); + MockRepository.SetExceptionToBeThrownOnVerify(proxy, exception); + throw exception; + } + return expectation; + } + } + return null; + } + + private void ExpectationNotOnList(ExpectationsList list, IExpectation expectation, bool isStub) + { + bool expectationExists = list.Contains(expectation); + if (expectationExists == false) + return; + bool isProeprty = expectation.Method.IsSpecialName && + (expectation.Method.Name.StartsWith("get_") || + expectation.Method.Name.StartsWith("set_")); + if (isStub == false || isProeprty == false) + throw new InvalidOperationException("The result for " + expectation.ErrorMessage + " has already been setup."); + throw new InvalidOperationException("The result for " + expectation.ErrorMessage + " has already been setup. Properties are already stubbed with PropertyBehavior by default, no action is required"); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/MethodRecorders/OrderedMethodRecorder.cs b/Rhino.Mocks/MethodRecorders/OrderedMethodRecorder.cs index 1b7b28ae..6c34e7a1 100644 --- a/Rhino.Mocks/MethodRecorders/OrderedMethodRecorder.cs +++ b/Rhino.Mocks/MethodRecorders/OrderedMethodRecorder.cs @@ -1,198 +1,198 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Utilities; -using Rhino.Mocks.Impl; - -namespace Rhino.Mocks.MethodRecorders -{ - using Generated; - - /// - /// Ordered collection of methods, methods must arrive in specified order - /// in order to pass. - /// - public class OrderedMethodRecorder : UnorderedMethodRecorder - { - /// - /// Creates a new instance. - /// - /// Parent recorder. - /// Repetable methods - public OrderedMethodRecorder(IMethodRecorder parentRecorder, ProxyMethodExpectationsDictionary repeatableMethods) - : base(parentRecorder, repeatableMethods) - { - } - - /// - /// Creates a new instance. - /// - public OrderedMethodRecorder(ProxyMethodExpectationsDictionary repeatableMethods) - : base(repeatableMethods) - { - } - - /// - /// Handles the real getting of the recorded expectation or null. - /// - protected override IExpectation DoGetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args) - { - int actionPos = 0; - while (actionPos < recordedActions.Count) - { - ProxyMethodExpectationTriplet triplet = recordedActions[actionPos] as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (MockedObjectsEquality.Instance.Equals(triplet.Proxy, proxy) && - triplet.Method == method && - triplet.Expectation.CanAcceptCalls && - triplet.Expectation.IsExpected(args)) - { - // Ensure that this expectation is the first one in the list. - while (actionPos > 0) - { - recordedActions.RemoveAt(0); - actionPos--; - } - - // This call satisfies that expectation. - triplet.Expectation.AddActualCall(); - - // Is this expectation complete? - if (!triplet.Expectation.CanAcceptCalls) - { - recordedActions.RemoveAt(0); - } - - return triplet.Expectation; - } - else - { - // The expectation didn't match. Is the expectation satisfied, so can we consider - // looking at the next expectation? - if (triplet.Expectation.ExpectationSatisfied) - { - actionPos++; - } - else - { - // No. - return null; - } - } - } - else // Action is another recorder - { - IMethodRecorder innerRecorder = (IMethodRecorder)recordedActions[actionPos]; - if (innerRecorder.HasExpectations == false) // so don't need to consider it - { - actionPos++; - continue; - } - if (ShouldConsiderThisReplayer(innerRecorder) == false) - break; - IExpectation expectation = innerRecorder.GetRecordedExpectationOrNull(proxy, method, args); - if (expectation != null) - { - // Ensure that this expectation is the first one in the list. - while (actionPos > 0) - { - recordedActions.RemoveAt(0); - actionPos--; - } - - replayerToCall = innerRecorder; - recordedActions.RemoveAt(0); - return expectation; - } - break; - } - } - if (parentRecorder == null) - return null; - // We only reach this place if we still has valid expectations, but they are not - // mandatory, (AtLeastOnce(), etc). In this case, the recorder (and its children) cannot satisfy the - // expectation, so we move to the parent recorder and let it handle it. - parentRecorder.ClearReplayerToCall(this); - // We need this to give the correct exception if the method is an unepxected one. - // Check the redirection in UnexpectedMethodCall() - parentRecorderRedirection = parentRecorder; - return parentRecorder.GetRecordedExpectationOrNull(proxy, method, args); - } - - /// - /// Get the expectation for this method on this object with this arguments - /// - public override ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args) - { - // We have move to the parent recorder, we need to pass the call to it. - if (parentRecorderRedirection != null) - return parentRecorderRedirection.UnexpectedMethodCall(invocation, proxy, method, args); - StringBuilder sb = new StringBuilder(); - sb.Append("Unordered method call! The expected call is: '"); - sb.Append(GetExpectedCallsMessage()); - sb.Append("' but was: '"). - Append(MethodCallUtil.StringPresentation(invocation, method, args)). - Append("'"); - return new ExpectationViolationException(sb.ToString()); - } - - /// - /// Gets the next expected calls string. - /// - public override string GetExpectedCallsMessage() - { - StringBuilder sb = new StringBuilder(); - sb.Append("Ordered: { "); - if (recordedActions.Count > 0) - { - ProxyMethodExpectationTriplet triplet = recordedActions[0] as ProxyMethodExpectationTriplet; - if (triplet != null) - { - sb.Append(triplet.Expectation.ErrorMessage); - } - else //Action is another recorder - { - sb.Append(((IMethodRecorder)recordedActions[0]).GetExpectedCallsMessage()); - } - } - else - { - sb.Append("No method call is expected"); - } - sb.Append(" }"); - return sb.ToString(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Utilities; +using Rhino.Mocks.Impl; + +namespace Rhino.Mocks.MethodRecorders +{ + using Generated; + + /// + /// Ordered collection of methods, methods must arrive in specified order + /// in order to pass. + /// + public class OrderedMethodRecorder : UnorderedMethodRecorder + { + /// + /// Creates a new instance. + /// + /// Parent recorder. + /// Repetable methods + public OrderedMethodRecorder(IMethodRecorder parentRecorder, ProxyMethodExpectationsDictionary repeatableMethods) + : base(parentRecorder, repeatableMethods) + { + } + + /// + /// Creates a new instance. + /// + public OrderedMethodRecorder(ProxyMethodExpectationsDictionary repeatableMethods) + : base(repeatableMethods) + { + } + + /// + /// Handles the real getting of the recorded expectation or null. + /// + protected override IExpectation DoGetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args) + { + int actionPos = 0; + while (actionPos < recordedActions.Count) + { + ProxyMethodExpectationTriplet triplet = recordedActions[actionPos] as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (MockedObjectsEquality.Instance.Equals(triplet.Proxy, proxy) && + triplet.Method == method && + triplet.Expectation.CanAcceptCalls && + triplet.Expectation.IsExpected(args)) + { + // Ensure that this expectation is the first one in the list. + while (actionPos > 0) + { + recordedActions.RemoveAt(0); + actionPos--; + } + + // This call satisfies that expectation. + triplet.Expectation.AddActualCall(); + + // Is this expectation complete? + if (!triplet.Expectation.CanAcceptCalls) + { + recordedActions.RemoveAt(0); + } + + return triplet.Expectation; + } + else + { + // The expectation didn't match. Is the expectation satisfied, so can we consider + // looking at the next expectation? + if (triplet.Expectation.ExpectationSatisfied) + { + actionPos++; + } + else + { + // No. + return null; + } + } + } + else // Action is another recorder + { + IMethodRecorder innerRecorder = (IMethodRecorder)recordedActions[actionPos]; + if (innerRecorder.HasExpectations == false) // so don't need to consider it + { + actionPos++; + continue; + } + if (ShouldConsiderThisReplayer(innerRecorder) == false) + break; + IExpectation expectation = innerRecorder.GetRecordedExpectationOrNull(proxy, method, args); + if (expectation != null) + { + // Ensure that this expectation is the first one in the list. + while (actionPos > 0) + { + recordedActions.RemoveAt(0); + actionPos--; + } + + replayerToCall = innerRecorder; + recordedActions.RemoveAt(0); + return expectation; + } + break; + } + } + if (parentRecorder == null) + return null; + // We only reach this place if we still has valid expectations, but they are not + // mandatory, (AtLeastOnce(), etc). In this case, the recorder (and its children) cannot satisfy the + // expectation, so we move to the parent recorder and let it handle it. + parentRecorder.ClearReplayerToCall(this); + // We need this to give the correct exception if the method is an unepxected one. + // Check the redirection in UnexpectedMethodCall() + parentRecorderRedirection = parentRecorder; + return parentRecorder.GetRecordedExpectationOrNull(proxy, method, args); + } + + /// + /// Get the expectation for this method on this object with this arguments + /// + public override ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args) + { + // We have move to the parent recorder, we need to pass the call to it. + if (parentRecorderRedirection != null) + return parentRecorderRedirection.UnexpectedMethodCall(invocation, proxy, method, args); + StringBuilder sb = new StringBuilder(); + sb.Append("Unordered method call! The expected call is: '"); + sb.Append(GetExpectedCallsMessage()); + sb.Append("' but was: '"). + Append(MethodCallUtil.StringPresentation(invocation, method, args)). + Append("'"); + return new ExpectationViolationException(sb.ToString()); + } + + /// + /// Gets the next expected calls string. + /// + public override string GetExpectedCallsMessage() + { + StringBuilder sb = new StringBuilder(); + sb.Append("Ordered: { "); + if (recordedActions.Count > 0) + { + ProxyMethodExpectationTriplet triplet = recordedActions[0] as ProxyMethodExpectationTriplet; + if (triplet != null) + { + sb.Append(triplet.Expectation.ErrorMessage); + } + else //Action is another recorder + { + sb.Append(((IMethodRecorder)recordedActions[0]).GetExpectedCallsMessage()); + } + } + else + { + sb.Append("No method call is expected"); + } + sb.Append(" }"); + return sb.ToString(); + } + } +} diff --git a/Rhino.Mocks/MethodRecorders/ProxyMethodExpectationTriplet.cs b/Rhino.Mocks/MethodRecorders/ProxyMethodExpectationTriplet.cs index a0b09505..60a16222 100644 --- a/Rhino.Mocks/MethodRecorders/ProxyMethodExpectationTriplet.cs +++ b/Rhino.Mocks/MethodRecorders/ProxyMethodExpectationTriplet.cs @@ -1,116 +1,116 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Globalization; -using System.Reflection; - -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.MethodRecorders -{ - /// - /// Hold an expectation for a method call on an object - /// - public class ProxyMethodExpectationTriplet - { - private object proxy; - private MethodInfo method; - private IExpectation expectation; - - /// - /// Creates a new instance. - /// - /// Proxy. - /// Method. - /// Expectation. - public ProxyMethodExpectationTriplet(object proxy, MethodInfo method, IExpectation expectation) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - Validate.IsNotNull(expectation, "expectation"); - this.proxy = proxy; - this.method = method; - this.expectation = expectation; - } - - /// - /// Gets the proxy. - /// - /// - public object Proxy - { - get { return proxy; } - } - - /// - /// Gets the method. - /// - /// - public MethodInfo Method - { - get { return method; } - } - - /// - /// Gets the expectation. - /// - /// - public IExpectation Expectation - { - get { return expectation; } - set { expectation = value; } - } - - /// - /// Determines if the object equal to this instance - /// - /// Obj. - /// - public override bool Equals(object obj) - { - ProxyMethodExpectationTriplet other = obj as ProxyMethodExpectationTriplet; - if (other == null) - return false; - return method == other.method && - MockedObjectsEquality.Instance.Compare(proxy, other.proxy) == 0 && - expectation == other.expectation; - } - - /// - /// Gets the hash code. - /// - /// - public override int GetHashCode() - { - return method.GetHashCode() + MockedObjectsEquality.Instance.GetHashCode(proxy) + expectation.GetHashCode(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Globalization; +using System.Reflection; + +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.MethodRecorders +{ + /// + /// Hold an expectation for a method call on an object + /// + public class ProxyMethodExpectationTriplet + { + private object proxy; + private MethodInfo method; + private IExpectation expectation; + + /// + /// Creates a new instance. + /// + /// Proxy. + /// Method. + /// Expectation. + public ProxyMethodExpectationTriplet(object proxy, MethodInfo method, IExpectation expectation) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + Validate.IsNotNull(expectation, "expectation"); + this.proxy = proxy; + this.method = method; + this.expectation = expectation; + } + + /// + /// Gets the proxy. + /// + /// + public object Proxy + { + get { return proxy; } + } + + /// + /// Gets the method. + /// + /// + public MethodInfo Method + { + get { return method; } + } + + /// + /// Gets the expectation. + /// + /// + public IExpectation Expectation + { + get { return expectation; } + set { expectation = value; } + } + + /// + /// Determines if the object equal to this instance + /// + /// Obj. + /// + public override bool Equals(object obj) + { + ProxyMethodExpectationTriplet other = obj as ProxyMethodExpectationTriplet; + if (other == null) + return false; + return method == other.method && + MockedObjectsEquality.Instance.Compare(proxy, other.proxy) == 0 && + expectation == other.expectation; + } + + /// + /// Gets the hash code. + /// + /// + public override int GetHashCode() + { + return method.GetHashCode() + MockedObjectsEquality.Instance.GetHashCode(proxy) + expectation.GetHashCode(); + } + } +} diff --git a/Rhino.Mocks/MethodRecorders/ProxyMethodPair.cs b/Rhino.Mocks/MethodRecorders/ProxyMethodPair.cs index 5669dda1..881b7741 100644 --- a/Rhino.Mocks/MethodRecorders/ProxyMethodPair.cs +++ b/Rhino.Mocks/MethodRecorders/ProxyMethodPair.cs @@ -1,106 +1,106 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Globalization; -using System.Reflection; - -using Rhino.Mocks.Impl; - -namespace Rhino.Mocks.MethodRecorders -{ - /// - /// 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()... - /// - public class ProxyMethodPair - { - private object proxy; - private MethodInfo method; - - /// - /// Creates a new instance. - /// - /// Proxy. - /// Method. - public ProxyMethodPair(object proxy, MethodInfo method) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - this.proxy = proxy; - this.method = method; - } - - /// - /// Gets the proxy. - /// - /// - public object Proxy - { - get { return proxy; } - } - - /// - /// Gets the method. - /// - /// - public MethodInfo Method - { - get { return 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. - /// - public override bool Equals(object obj) - { - ProxyMethodPair other = obj as ProxyMethodPair; - if (other == null) - return false; - return MockedObjectsEquality.Instance.Compare(other.proxy, proxy) == 0 && - other.method == method; - - } - - /// - /// Gets the hash code. - /// - /// - public override int GetHashCode() - { - return MockedObjectsEquality.Instance.GetHashCode(proxy) + method.GetHashCode(); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Globalization; +using System.Reflection; + +using Rhino.Mocks.Impl; + +namespace Rhino.Mocks.MethodRecorders +{ + /// + /// 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()... + /// + public class ProxyMethodPair + { + private object proxy; + private MethodInfo method; + + /// + /// Creates a new instance. + /// + /// Proxy. + /// Method. + public ProxyMethodPair(object proxy, MethodInfo method) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + this.proxy = proxy; + this.method = method; + } + + /// + /// Gets the proxy. + /// + /// + public object Proxy + { + get { return proxy; } + } + + /// + /// Gets the method. + /// + /// + public MethodInfo Method + { + get { return 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. + /// + public override bool Equals(object obj) + { + ProxyMethodPair other = obj as ProxyMethodPair; + if (other == null) + return false; + return MockedObjectsEquality.Instance.Compare(other.proxy, proxy) == 0 && + other.method == method; + + } + + /// + /// Gets the hash code. + /// + /// + public override int GetHashCode() + { + return MockedObjectsEquality.Instance.GetHashCode(proxy) + method.GetHashCode(); + } + } +} diff --git a/Rhino.Mocks/MethodRecorders/RecorderChanger.cs b/Rhino.Mocks/MethodRecorders/RecorderChanger.cs index a6bfbe28..7ddfbd21 100644 --- a/Rhino.Mocks/MethodRecorders/RecorderChanger.cs +++ b/Rhino.Mocks/MethodRecorders/RecorderChanger.cs @@ -1,64 +1,64 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.MethodRecorders -{ - /// - /// Change the recorder from ordered to unordered and vice versa - /// - public class RecorderChanger : IDisposable - { - private IMethodRecorder recorder; - private readonly MockRepository repository; - - /// - /// Creates a new instance. - /// - public RecorderChanger(MockRepository repository, IMethodRecorder recorder, IMethodRecorder newRecorder) - { - this.recorder = recorder; - this.repository = repository; - repository.PushRecorder(newRecorder); - this.recorder.AddRecorder(newRecorder); - } - - - /// - /// Disposes this instance. - /// - public void Dispose() - { - this.recorder.MoveToPreviousRecorder(); - repository.PopRecorder(); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.MethodRecorders +{ + /// + /// Change the recorder from ordered to unordered and vice versa + /// + public class RecorderChanger : IDisposable + { + private IMethodRecorder recorder; + private readonly MockRepository repository; + + /// + /// Creates a new instance. + /// + public RecorderChanger(MockRepository repository, IMethodRecorder recorder, IMethodRecorder newRecorder) + { + this.recorder = recorder; + this.repository = repository; + repository.PushRecorder(newRecorder); + this.recorder.AddRecorder(newRecorder); + } + + + /// + /// Disposes this instance. + /// + public void Dispose() + { + this.recorder.MoveToPreviousRecorder(); + repository.PopRecorder(); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/MethodRecorders/UnorderedMethodRecorder.cs b/Rhino.Mocks/MethodRecorders/UnorderedMethodRecorder.cs index 6c349546..2e4d78a6 100644 --- a/Rhino.Mocks/MethodRecorders/UnorderedMethodRecorder.cs +++ b/Rhino.Mocks/MethodRecorders/UnorderedMethodRecorder.cs @@ -1,437 +1,437 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System.Collections; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.Generated; -using Rhino.Mocks.Utilities; - -namespace Rhino.Mocks.MethodRecorders -{ - /// - /// Unordered collection of method records, any expectation that exist - /// will be matched. - /// - public class UnorderedMethodRecorder : MethodRecorderBase - { - /// - /// The parent recorder we have redirected to. - /// Useful for certain edge cases in orderring. - /// See: FieldProblem_Entropy for the details. - /// - protected IMethodRecorder parentRecorderRedirection = null; - - /// - /// Creates a new instance. - /// - /// Parent recorder. - /// Repeatable methods - public UnorderedMethodRecorder(IMethodRecorder parentRecorder, ProxyMethodExpectationsDictionary repeatableMethods) - : base(parentRecorder,repeatableMethods) - { - } - - /// - /// Creates a new instance. - /// - public UnorderedMethodRecorder(ProxyMethodExpectationsDictionary repeatableMethods) - : base(repeatableMethods) - { - } - - /// - /// Records the specified call with the specified args on the mocked object. - /// - /// Mocked object. - /// Method. - /// Expectation. - protected override void DoRecord(object proxy, MethodInfo method, IExpectation expectation) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - Validate.IsNotNull(expectation, "expectation"); - ProxyMethodExpectationTriplet entry = new ProxyMethodExpectationTriplet(proxy, method, expectation); - recordedActions.Add(entry); - } - - /// - /// 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 - protected override IExpectation DoGetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args) - { - IExpectation expectation = GetRecordedExpectationOrNull(proxy, method, args); - if (expectation == null) - { - RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Unexpected method call error"); - ExpectationViolationException expectationViolationException = UnexpectedMethodCall(invocation, proxy, method, args); - MockRepository.SetExceptionToBeThrownOnVerify(proxy, expectationViolationException); - throw expectationViolationException; - } - return expectation; - } - - /// - /// 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 - public override ExpectationsList GetAllExpectationsForProxyAndMethod(object proxy, MethodInfo method) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - - ExpectationsList expectations = new ExpectationsList(); - foreach (object action in recordedActions) - { - ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (MockedObjectsEquality.Instance.Equals( triplet.Proxy , proxy ) && - MethodsEquals(method, triplet)) - { - expectations.Add(triplet.Expectation); - } - } - else //Action is another recorder - { - IMethodRecorder innerRecorder = (IMethodRecorder) action; - expectations.AddRange(innerRecorder.GetAllExpectationsForProxyAndMethod(proxy, method)); - } - } - return expectations; - } - - private static bool MethodsEquals(MethodInfo method, ProxyMethodExpectationTriplet triplet) - { - if(method.IsGenericMethod==false) - return triplet.Method == method; - return triplet.Method.GetGenericMethodDefinition() == method.GetGenericMethodDefinition(); - } - - /// - /// Gets the all expectations for proxy. - /// - /// Mocked object. - /// List of all relevant expectation - protected override ExpectationsList DoGetAllExpectationsForProxy(object proxy) - { - Validate.IsNotNull(proxy, "proxy"); - - ExpectationsList expectations = new ExpectationsList(); - foreach (object action in recordedActions) - { - ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (MockedObjectsEquality.Instance.Equals( triplet.Proxy , proxy)) - { - expectations.Add(triplet.Expectation); - } - } - else //Action is another recorder - { - IMethodRecorder innerRecorder = (IMethodRecorder) action; - ExpectationsList expectationsForProxy = innerRecorder.GetAllExpectationsForProxy(proxy); - expectations.AddRange(expectationsForProxy); - } - } - return expectations; - } - - /// - /// 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. - protected override void DoReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - Validate.IsNotNull(oldExpectation, "oldExpectation"); - Validate.IsNotNull(newExpectation, "newExpectation"); - foreach (object action in recordedActions) - { - ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (MockedObjectsEquality.Instance.Equals( triplet.Proxy , proxy ) && - triplet.Method == method && - triplet.Expectation == oldExpectation) - { - triplet.Expectation = newExpectation; - } - } - //Action cannot be another recorder, since then the RemoveExpectation would've - //passed us to the top most recorder. - } - } - - /// - /// Gets a value indicating whether this instance has expectations that weren't satisfied yet. - /// - /// - /// true if this instance has expectations; otherwise, false. - /// - protected override bool DoHasExpectations - { - get - { - foreach (object action in recordedActions) - { - ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (triplet.Expectation.CanAcceptCalls) - return true; - } - else //Action is another recorder - { - IMethodRecorder innerRecorder = (IMethodRecorder) action; - if (innerRecorder.HasExpectations) - return true; - } - } - return false; - } - } - - /// - /// Handle the real execution of this method for the derived class - /// - protected override void DoRemoveExpectation(IExpectation expectation) - { - for (int i = 0; i < recordedActions.Count; i++) - { - ProxyMethodExpectationTriplet triplet = recordedActions[i] as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (triplet.Expectation == expectation) - recordedActions.RemoveAt(i); - } - //Action cannot be another recorder, since then the RemoveExpectation would've - //passed us to the top most recorder. - } - } - - /// - /// Handles the real getting of the recorded expectation or null. - /// - protected override IExpectation DoGetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args) - { - Validate.IsNotNull(proxy, "proxy"); - Validate.IsNotNull(method, "method"); - Validate.IsNotNull(args, "args"); - // Need this because we may want to modify the recordedAction list as we traverse it - // See: ClearReplayerToCall(); - ArrayList traversalSafeCopy = new ArrayList(recordedActions); - bool allSatisfied = true; - foreach (object action in traversalSafeCopy) - { - ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; - if (triplet != null) - { - if (MockedObjectsEquality.Instance.Equals(triplet.Proxy, proxy) && - triplet.Method == method && - triplet.Expectation.CanAcceptCalls && - triplet.Expectation.IsExpected(args)) - { - triplet.Expectation.AddActualCall(); - return triplet.Expectation; - } - if(!triplet.Expectation.ExpectationSatisfied) - allSatisfied = false; - } - else //Action is another recorder - { - IMethodRecorder innerRecorder = (IMethodRecorder) action; - if(ShouldConsiderThisReplayer(innerRecorder)==false) - continue; - IExpectation expectation = innerRecorder.GetRecordedExpectationOrNull(proxy, method, args); - if (expectation != null) - { - replayerToCall = innerRecorder; - return expectation; - } - if(innerRecorder.HasExpectations) - allSatisfied = false; - } - } - // We still have unsatisifed expectation or we don't have a parent recorder - if (!allSatisfied || parentRecorder==null) - return null; - // We only reach this place if we still has valid expectations, but they are not - // mandatory, (AtLeastOnce(), etc). In this case, the recorder (and its children) cannot satisfy the - // expectation, so we move to the parent recorder and let it handle it. - parentRecorder.ClearReplayerToCall(this); - // We need this to give the correct exception if the method is an unepxected one. - // Check the redirection in UnexpectedMethodCall() - parentRecorderRedirection = parentRecorder; - return parentRecorder.GetRecordedExpectationOrNull(proxy, method, args); - } - - /// - /// Handle the real execution of this method for the derived class - /// - protected override void DoAddRecorder(IMethodRecorder recorder) - { - recordedActions.Add(recorder); - } - - /// - /// Gets the next expected calls string. - /// - public override string GetExpectedCallsMessage() - { - StringBuilder sb = new StringBuilder(); - sb.Append("Unordered: { "); - foreach (object action in recordedActions) - { - ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; - if (triplet != null) - { - sb.Append(triplet.Expectation.ErrorMessage); - } - else - { - string nested = ((IMethodRecorder)action).GetExpectedCallsMessage(); - sb.Append(nested); - } - } - sb.Append(" }"); - return sb.ToString(); - } - - /// - /// Create an exception for an unexpected method call. - /// - public override ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args) - { - // We have move to the parent recorder, we need to pass the call to it. - if (parentRecorderRedirection != null) - return parentRecorderRedirection.UnexpectedMethodCall(invocation, proxy, method, args); - StringBuilder sb = new StringBuilder(); - CalcExpectedAndActual calc = new CalcExpectedAndActual(this, proxy, method, args); - string methodAsString = MethodCallUtil.StringPresentation(invocation, method, args); - sb.Append(methodAsString); - sb.Append(" Expected #"); - if (calc.ExpectedMax == calc.ExpectedMin) - sb.Append(calc.ExpectedMin); - else - sb.Append(calc.ExpectedMin).Append(" - ").Append(calc.ExpectedMax); - sb.Append(", Actual #").Append(calc.Actual).Append('.'); - ExpectationsList list = GetAllExpectationsForProxyAndMethod(proxy, method); - if (list.Count > 0) - { - string message = list[0].Message; - if (message != null) - { - - sb.Append(System.Environment.NewLine) - .Append("Message: ") - .Append(message); - } - } - AppendNextExpected(proxy, method, sb); - return new ExpectationViolationException(sb.ToString()); - } - - private class CalcExpectedAndActual - { - private int actual = 1; - private int expectedMin = 0, expectedMax; - private UnorderedMethodRecorder parent; - - public int Actual - { - get { return actual; } - } - - - public int ExpectedMin - { - get { return expectedMin; } - } - - public int ExpectedMax - { - get { return expectedMax; } - } - - public CalcExpectedAndActual(UnorderedMethodRecorder parent, object proxy, MethodInfo method, object[] args) - { - this.parent = parent; - Calculate(proxy, method, args); - } - - private void Calculate(object proxy, MethodInfo method, object[] args) - { - ExpectationsList list = parent.GetAllExpectationsForProxyAndMethod(proxy, method); - foreach (IExpectation expectation in list) - { - if (expectation.IsExpected(args)) - { - expectedMin+= expectation.Expected.Min; - expectedMax += expectation.Expected.Max ?? expectation.Expected.Min; - actual += expectation.ActualCallsCount; - } - } - } - } - - private void AppendNextExpected(object proxy, MethodInfo method, StringBuilder sb) - { - ExpectationsList list = GetAllExpectationsForProxyAndMethod(proxy, method); - if (list.Count > 0) - { - IExpectation expectation = list[0]; - if (expectation.ExpectationSatisfied) - return; //avoid showing methods that were completed. - sb.Append("\r\n"); - sb.Append(expectation.ErrorMessage).Append(" Expected #"); - sb.Append(expectation.Expected).Append(", Actual #"); - sb.Append(expectation.ActualCallsCount).Append("."); - } - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System.Collections; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.Generated; +using Rhino.Mocks.Utilities; + +namespace Rhino.Mocks.MethodRecorders +{ + /// + /// Unordered collection of method records, any expectation that exist + /// will be matched. + /// + public class UnorderedMethodRecorder : MethodRecorderBase + { + /// + /// The parent recorder we have redirected to. + /// Useful for certain edge cases in orderring. + /// See: FieldProblem_Entropy for the details. + /// + protected IMethodRecorder parentRecorderRedirection = null; + + /// + /// Creates a new instance. + /// + /// Parent recorder. + /// Repeatable methods + public UnorderedMethodRecorder(IMethodRecorder parentRecorder, ProxyMethodExpectationsDictionary repeatableMethods) + : base(parentRecorder,repeatableMethods) + { + } + + /// + /// Creates a new instance. + /// + public UnorderedMethodRecorder(ProxyMethodExpectationsDictionary repeatableMethods) + : base(repeatableMethods) + { + } + + /// + /// Records the specified call with the specified args on the mocked object. + /// + /// Mocked object. + /// Method. + /// Expectation. + protected override void DoRecord(object proxy, MethodInfo method, IExpectation expectation) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + Validate.IsNotNull(expectation, "expectation"); + ProxyMethodExpectationTriplet entry = new ProxyMethodExpectationTriplet(proxy, method, expectation); + recordedActions.Add(entry); + } + + /// + /// 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 + protected override IExpectation DoGetRecordedExpectation(IInvocation invocation, object proxy, MethodInfo method, object[] args) + { + IExpectation expectation = GetRecordedExpectationOrNull(proxy, method, args); + if (expectation == null) + { + RhinoMocks.Logger.LogUnexpectedMethodCall(invocation, "Unexpected method call error"); + ExpectationViolationException expectationViolationException = UnexpectedMethodCall(invocation, proxy, method, args); + MockRepository.SetExceptionToBeThrownOnVerify(proxy, expectationViolationException); + throw expectationViolationException; + } + return expectation; + } + + /// + /// 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 + public override ExpectationsList GetAllExpectationsForProxyAndMethod(object proxy, MethodInfo method) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + + ExpectationsList expectations = new ExpectationsList(); + foreach (object action in recordedActions) + { + ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (MockedObjectsEquality.Instance.Equals( triplet.Proxy , proxy ) && + MethodsEquals(method, triplet)) + { + expectations.Add(triplet.Expectation); + } + } + else //Action is another recorder + { + IMethodRecorder innerRecorder = (IMethodRecorder) action; + expectations.AddRange(innerRecorder.GetAllExpectationsForProxyAndMethod(proxy, method)); + } + } + return expectations; + } + + private static bool MethodsEquals(MethodInfo method, ProxyMethodExpectationTriplet triplet) + { + if(method.IsGenericMethod==false) + return triplet.Method == method; + return triplet.Method.GetGenericMethodDefinition() == method.GetGenericMethodDefinition(); + } + + /// + /// Gets the all expectations for proxy. + /// + /// Mocked object. + /// List of all relevant expectation + protected override ExpectationsList DoGetAllExpectationsForProxy(object proxy) + { + Validate.IsNotNull(proxy, "proxy"); + + ExpectationsList expectations = new ExpectationsList(); + foreach (object action in recordedActions) + { + ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (MockedObjectsEquality.Instance.Equals( triplet.Proxy , proxy)) + { + expectations.Add(triplet.Expectation); + } + } + else //Action is another recorder + { + IMethodRecorder innerRecorder = (IMethodRecorder) action; + ExpectationsList expectationsForProxy = innerRecorder.GetAllExpectationsForProxy(proxy); + expectations.AddRange(expectationsForProxy); + } + } + return expectations; + } + + /// + /// 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. + protected override void DoReplaceExpectation(object proxy, MethodInfo method, IExpectation oldExpectation, IExpectation newExpectation) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + Validate.IsNotNull(oldExpectation, "oldExpectation"); + Validate.IsNotNull(newExpectation, "newExpectation"); + foreach (object action in recordedActions) + { + ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (MockedObjectsEquality.Instance.Equals( triplet.Proxy , proxy ) && + triplet.Method == method && + triplet.Expectation == oldExpectation) + { + triplet.Expectation = newExpectation; + } + } + //Action cannot be another recorder, since then the RemoveExpectation would've + //passed us to the top most recorder. + } + } + + /// + /// Gets a value indicating whether this instance has expectations that weren't satisfied yet. + /// + /// + /// true if this instance has expectations; otherwise, false. + /// + protected override bool DoHasExpectations + { + get + { + foreach (object action in recordedActions) + { + ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (triplet.Expectation.CanAcceptCalls) + return true; + } + else //Action is another recorder + { + IMethodRecorder innerRecorder = (IMethodRecorder) action; + if (innerRecorder.HasExpectations) + return true; + } + } + return false; + } + } + + /// + /// Handle the real execution of this method for the derived class + /// + protected override void DoRemoveExpectation(IExpectation expectation) + { + for (int i = 0; i < recordedActions.Count; i++) + { + ProxyMethodExpectationTriplet triplet = recordedActions[i] as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (triplet.Expectation == expectation) + recordedActions.RemoveAt(i); + } + //Action cannot be another recorder, since then the RemoveExpectation would've + //passed us to the top most recorder. + } + } + + /// + /// Handles the real getting of the recorded expectation or null. + /// + protected override IExpectation DoGetRecordedExpectationOrNull(object proxy, MethodInfo method, object[] args) + { + Validate.IsNotNull(proxy, "proxy"); + Validate.IsNotNull(method, "method"); + Validate.IsNotNull(args, "args"); + // Need this because we may want to modify the recordedAction list as we traverse it + // See: ClearReplayerToCall(); + ArrayList traversalSafeCopy = new ArrayList(recordedActions); + bool allSatisfied = true; + foreach (object action in traversalSafeCopy) + { + ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; + if (triplet != null) + { + if (MockedObjectsEquality.Instance.Equals(triplet.Proxy, proxy) && + triplet.Method == method && + triplet.Expectation.CanAcceptCalls && + triplet.Expectation.IsExpected(args)) + { + triplet.Expectation.AddActualCall(); + return triplet.Expectation; + } + if(!triplet.Expectation.ExpectationSatisfied) + allSatisfied = false; + } + else //Action is another recorder + { + IMethodRecorder innerRecorder = (IMethodRecorder) action; + if(ShouldConsiderThisReplayer(innerRecorder)==false) + continue; + IExpectation expectation = innerRecorder.GetRecordedExpectationOrNull(proxy, method, args); + if (expectation != null) + { + replayerToCall = innerRecorder; + return expectation; + } + if(innerRecorder.HasExpectations) + allSatisfied = false; + } + } + // We still have unsatisifed expectation or we don't have a parent recorder + if (!allSatisfied || parentRecorder==null) + return null; + // We only reach this place if we still has valid expectations, but they are not + // mandatory, (AtLeastOnce(), etc). In this case, the recorder (and its children) cannot satisfy the + // expectation, so we move to the parent recorder and let it handle it. + parentRecorder.ClearReplayerToCall(this); + // We need this to give the correct exception if the method is an unepxected one. + // Check the redirection in UnexpectedMethodCall() + parentRecorderRedirection = parentRecorder; + return parentRecorder.GetRecordedExpectationOrNull(proxy, method, args); + } + + /// + /// Handle the real execution of this method for the derived class + /// + protected override void DoAddRecorder(IMethodRecorder recorder) + { + recordedActions.Add(recorder); + } + + /// + /// Gets the next expected calls string. + /// + public override string GetExpectedCallsMessage() + { + StringBuilder sb = new StringBuilder(); + sb.Append("Unordered: { "); + foreach (object action in recordedActions) + { + ProxyMethodExpectationTriplet triplet = action as ProxyMethodExpectationTriplet; + if (triplet != null) + { + sb.Append(triplet.Expectation.ErrorMessage); + } + else + { + string nested = ((IMethodRecorder)action).GetExpectedCallsMessage(); + sb.Append(nested); + } + } + sb.Append(" }"); + return sb.ToString(); + } + + /// + /// Create an exception for an unexpected method call. + /// + public override ExpectationViolationException UnexpectedMethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args) + { + // We have move to the parent recorder, we need to pass the call to it. + if (parentRecorderRedirection != null) + return parentRecorderRedirection.UnexpectedMethodCall(invocation, proxy, method, args); + StringBuilder sb = new StringBuilder(); + CalcExpectedAndActual calc = new CalcExpectedAndActual(this, proxy, method, args); + string methodAsString = MethodCallUtil.StringPresentation(invocation, method, args); + sb.Append(methodAsString); + sb.Append(" Expected #"); + if (calc.ExpectedMax == calc.ExpectedMin) + sb.Append(calc.ExpectedMin); + else + sb.Append(calc.ExpectedMin).Append(" - ").Append(calc.ExpectedMax); + sb.Append(", Actual #").Append(calc.Actual).Append('.'); + ExpectationsList list = GetAllExpectationsForProxyAndMethod(proxy, method); + if (list.Count > 0) + { + string message = list[0].Message; + if (message != null) + { + + sb.Append(System.Environment.NewLine) + .Append("Message: ") + .Append(message); + } + } + AppendNextExpected(proxy, method, sb); + return new ExpectationViolationException(sb.ToString()); + } + + private class CalcExpectedAndActual + { + private int actual = 1; + private int expectedMin = 0, expectedMax; + private UnorderedMethodRecorder parent; + + public int Actual + { + get { return actual; } + } + + + public int ExpectedMin + { + get { return expectedMin; } + } + + public int ExpectedMax + { + get { return expectedMax; } + } + + public CalcExpectedAndActual(UnorderedMethodRecorder parent, object proxy, MethodInfo method, object[] args) + { + this.parent = parent; + Calculate(proxy, method, args); + } + + private void Calculate(object proxy, MethodInfo method, object[] args) + { + ExpectationsList list = parent.GetAllExpectationsForProxyAndMethod(proxy, method); + foreach (IExpectation expectation in list) + { + if (expectation.IsExpected(args)) + { + expectedMin+= expectation.Expected.Min; + expectedMax += expectation.Expected.Max ?? expectation.Expected.Min; + actual += expectation.ActualCallsCount; + } + } + } + } + + private void AppendNextExpected(object proxy, MethodInfo method, StringBuilder sb) + { + ExpectationsList list = GetAllExpectationsForProxyAndMethod(proxy, method); + if (list.Count > 0) + { + IExpectation expectation = list[0]; + if (expectation.ExpectationSatisfied) + return; //avoid showing methods that were completed. + sb.Append("\r\n"); + sb.Append(expectation.ErrorMessage).Append(" Expected #"); + sb.Append(expectation.Expected).Append(", Actual #"); + sb.Append(expectation.ActualCallsCount).Append("."); + } + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/MockRepository.cs b/Rhino.Mocks/MockRepository.cs index afc23ef5..e91bf84e 100644 --- a/Rhino.Mocks/MockRepository.cs +++ b/Rhino.Mocks/MockRepository.cs @@ -1,1275 +1,1275 @@ -#region license - -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Castle.DynamicProxy; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Generated; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Impl.RemotingMock; -using Rhino.Mocks.Interfaces; -using Rhino.Mocks.MethodRecorders; - -namespace Rhino.Mocks -{ - /* - * class: MockRepository - * The MockRepository is the main interaction point with Rhino Mocks. - * - * Common usage pattern is to create the on [SetUp] - * and then create mock objects using either or - * and setup expectations on the mock object(s) by - * callling their methods. A call to would move the mock - * object(s) to replay state, a call to is made from the - * [TearDown] method. - * - * Thread Safety: - * MockRepository is capable of verifying in multiply threads, but recording in multiply threads - * is not recommended. If you need to do so you _must_ use the and - * methods and not and - * 's various methods. - * - * Code Sample: - * - * (start code) - * MockRepository mocks; - * - * [SetUp] - * public void Setup() - * { - * mocks = new MockRepository(); - * } - * - * [Test] - * public void CallMethodOnObject() - * { - * - * IDemo demo = (IDemo)mocks.CreateMock(typeof(IDemo)); - * // Setting up an expectation for a call to IDemo.VoidNoArg - * demo.VoidNoArg(); - * mocks.ReplayAll(); - * // Fullifying the expectation for call to IDemo.VoidNoArg - * demo.VoidNoArg(); - * } - * - * [TearDown] - * public void Teardown() - * { - * mocks.VerifyAll(); - * } - * (end) - * - * Class Responsbilities: - * - * - Create and manage mock object throughout their life time - * - * See Also: - * - - * - - * - - * - - */ - - /// - /// Creates proxied instances of types. - /// - public partial class MockRepository - { - /// - /// Delegate: CreateMockState - /// This is used internally to cleanly handle the creation of different - /// RecordMockStates. - /// - protected delegate IMockState CreateMockState(IMockedObject mockedObject); - - #region Variables - - /* - * Variable: generatorMap - * A static variable that is used to hold a map of Types to ProxyGenerators - * - */ - - /// - /// This is a map of types to ProxyGenerators. - /// - private static readonly IDictionary generatorMap = new Dictionary(); - - /* - * Variable: lastRepository - * A static variable that is used to hold the repository that last had a method call - * on one of its mock objects. - * - */ - - /// - /// This is used to record the last repository that has a method called on it. - /// - internal static MockRepository lastRepository; - - /* - * Var: lastProxy - * The last proxy that had a method call for _this_ repository - */ - - /// - /// this is used to get to the last proxy on this repository. - /// - internal IMockedObject lastMockedObject; - - private static readonly DelegateTargetInterfaceCreator delegateTargetInterfaceCreator = - new DelegateTargetInterfaceCreator(); - - /// - /// For mock delegates, maps the proxy instance from intercepted invocations - /// back to the delegate that was originally returned to client code, if any. - /// - protected IDictionary delegateProxies; - - /// - /// All the proxies in the mock repositories - /// - protected ProxyStateDictionary proxies; - - private readonly Stack recorders; - private readonly IMethodRecorder rootRecorder; - /// - /// 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. - /// - private readonly ProxyMethodExpectationsDictionary repeatableMethods; - - private ProxyGenerationOptions proxyGenerationOptions; - - #endregion - - #region Properties - - /* - * Property: Recorder - * Gets the current recorder for the repository. - */ - - /// - /// Gets the recorder. - /// - /// - internal IMethodRecorder Recorder - { - get { return recorders.Peek() as IMethodRecorder; } - } - - #endregion - - #region c'tors - - /* function: MockRepository - * Create a new instance of MockRepository - */ - - /// - /// Creates a new instance. - /// - public MockRepository() - { - proxyGenerationOptions = new ProxyGenerationOptions - { - AttributesToAddToGeneratedTypes = - { - new __ProtectAttribute() - } - }; - recorders = new Stack(); - repeatableMethods = new ProxyMethodExpectationsDictionary(); - rootRecorder = new UnorderedMethodRecorder(repeatableMethods); - recorders.Push(rootRecorder); - proxies = new ProxyStateDictionary(); - delegateProxies = new Hashtable(MockedObjectsEquality.Instance); - - // clean up Arg data to avoid the static data to be carried from one unit test - // to another. - ArgManager.Clear(); - } - - #endregion - - #region Methods - - /* - * Method: Ordered - * Moves the _entire_ to use ordered recording. - * - * This call is only valid during the recording phase. - * This call affects all mock objects that were created from this repository. - * - * The orderring is ended when the returned IDisposable's Dispose() method is called. - * (start code) - * [Test] - * public void CallMethodOnObject() - * { - * IDemo demo = (IDemo)mocks.CreateMock(typeof(IDemo)); - * //Moving to ordered mocking. - * using(mocks.Ordered() - * { - * demo.VoidNoArg(); - * demo.IntNoArg(); - * } - * //Must exit the ordering before calling - * mocks.ReplayAll(); - * //If we would try to call them in any other order, the test would fail - * demo.VoidNoArg(); - * demo.IntNoArg(); - * } - * (end) - * - */ - - /// - /// Move the repository to ordered mode - /// - public IDisposable Ordered() - { - return new RecorderChanger(this, Recorder, new OrderedMethodRecorder(Recorder, repeatableMethods)); - } - - /* - * Method: Unordered - * Moves the _entire_ to use unordered recording (the default). - * - * This call is only valid during the recording phase. - * This call affects all mock objects that were created from this repository. - * - * (start code) - * [Test] - * public void CallMethodOnObject() - * { - * IDemo demo = (IDemo)mocks.CreateMock(typeof(IDemo)); - * //Moving to ordered mocking. - * using(mocks.Ordered() - * { - * demo.VoidNoArg(); - * using(mocks.Unordered() - * { - * demo.VoidNoArg(); - * demo.IntNoArg(); - * } - * demo.IntNoArg(); - * } - * //Must exit the ordering before calling - * mocks.ReplayAll(); - * //The expectations we set up is: - * // 1. demo.VoidNoArgs(); - * // 2. in any order: - * // 1. demo.VoidNoArg(); - * // 2. demo.IntNoArg(); - * // 3. demo.IntNoArg(); - * demo.VoidNoArg(); - * demo.IntNoArg(); - * demo.VoidNoArg(); - * demo.IntNoArg(); - * } - */ - - /// - /// Move the repository to un-ordered mode - /// - public IDisposable Unordered() - { - return new RecorderChanger(this, Recorder, new UnorderedMethodRecorder(Recorder, repeatableMethods)); - } - - /* - * Method: CreateMock - * Create a mock object with strict semantics. - * Strict semantics means that any call that wasn't explicitly recorded is considered an - * error and would cause an exception to be thrown. - */ - - /// - /// Creates a mock for the specified type. - /// - /// Type. - /// Arguments for the class' constructor, if mocking a concrete class - [Obsolete("Use StrictMock instead")] - public object CreateMock(Type type, params object[] argumentsForConstructor) - { - return StrictMock(type, argumentsForConstructor); - } - - /// - /// Creates a strict mock for the specified type. - /// - /// Type. - /// Arguments for the class' constructor, if mocking a concrete class - public object StrictMock(Type type, params object[] argumentsForConstructor) - { - if (ShouldUseRemotingProxy(type, argumentsForConstructor)) - return RemotingMock(type, CreateRecordState); - return StrictMultiMock(type, new Type[0], argumentsForConstructor); - } - - /// - /// Creates a remoting mock for the specified type. - /// - /// Type. - /// Arguments for the class' constructor, if mocking a concrete class - [Obsolete("Use StrictMockWithRemoting instead")] - public object CreateMockWithRemoting(Type type, params object[] argumentsForConstructor) - { - return StrictMockWithRemoting(type, argumentsForConstructor); - } - - /// - /// Creates a strict remoting mock for the specified type. - /// - /// Type. - /// Arguments for the class' constructor, if mocking a concrete class - public object StrictMockWithRemoting(Type type, params object[] argumentsForConstructor) - { - return RemotingMock(type, CreateRecordState); - } - - /// - /// Creates a remoting mock for the specified type. - /// - /// - /// Arguments for the class' constructor, if mocking a concrete class - /// - [Obsolete("Use StrictMockWithRemoting instead")] - public T CreateMockWithRemoting(params object[] argumentsForConstructor) - { - return StrictMockWithRemoting(argumentsForConstructor); - } - - /// - /// Creates a strict remoting mock for the specified type. - /// - /// - /// Arguments for the class' constructor, if mocking a concrete class - /// - public T StrictMockWithRemoting(params object[] argumentsForConstructor) - { - return (T)RemotingMock(typeof(T), CreateRecordState); - } - - /// - /// Creates a mock from several types, with strict semantics. - /// Only may be a class. - /// - [Obsolete("Use StrictMultiMock instead")] - public object CreateMultiMock(Type mainType, params Type[] extraTypes) - { - return StrictMultiMock(mainType, extraTypes); - } - - /// - /// Creates a strict mock from several types, with strict semantics. - /// Only may be a class. - /// - public object StrictMultiMock(Type mainType, params Type[] extraTypes) - { - return StrictMultiMock(mainType, extraTypes, new object[0]); - } - - /// - /// 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. - [Obsolete("Use StrictMultiMock instead")] - public object CreateMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor) - { - return StrictMultiMock(mainType, extraTypes, argumentsForConstructor); - } - - /// - /// 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. - public object StrictMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor) - { - if (argumentsForConstructor == null) argumentsForConstructor = new object[0]; - return CreateMockObject(mainType, CreateRecordState, extraTypes, argumentsForConstructor); - } - - /// - /// Creates a mock from several types, with dynamic semantics. - /// Only may be a class. - /// - /// The main type to mock. - /// Extra interface types to mock. - public object DynamicMultiMock(Type mainType, params Type[] extraTypes) - { - return DynamicMultiMock(mainType, extraTypes, new object[0]); - } - - /// - /// 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. - public object DynamicMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor) - { - return CreateMockObject(mainType, CreateDynamicRecordState, extraTypes, argumentsForConstructor); - } - - /* - * Method: DynamicMock - * Create a mock object with dynamic semantics. - * Dynamic semantics means that any call that wasn't explicitly recorded is accepted and a - * null or zero is returned (if there is a return value). - */ - - /// Creates a dynamic mock for the specified type. - /// Type. - /// Arguments for the class' constructor, if mocking a concrete class - public object DynamicMock(Type type, params object[] argumentsForConstructor) - { - if (ShouldUseRemotingProxy(type, argumentsForConstructor)) - return RemotingMock(type, CreateDynamicRecordState); - return DynamicMultiMock(type, new Type[0], argumentsForConstructor); - } - - /// Creates a dynamic mock for the specified type. - /// Type. - /// Arguments for the class' constructor, if mocking a concrete class - public object DynamicMockWithRemoting(Type type, params object[] argumentsForConstructor) - { - return RemotingMock(type, CreateDynamicRecordState); - } - - /// Creates a dynamic mock for the specified type. - /// - /// Arguments for the class' constructor, if mocking a concrete class - /// - public T DynamicMockWithRemoting(params object[] argumentsForConstructor) - { - return (T)RemotingMock(typeof(T), CreateDynamicRecordState); - } - - /// 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. - public object PartialMock(Type type, params object[] argumentsForConstructor) - { - return PartialMultiMock(type, new Type[0], argumentsForConstructor); - } - - /// Creates a mock object that defaults to calling the class methods. - /// Type. - /// Extra interface types to mock. - public object PartialMultiMock(Type type, params Type[] extraTypes) - { - return PartialMultiMock(type, extraTypes, new object[0]); - } - - /// Creates a mock object that defaults to calling the class methods. - /// Type. - /// Extra interface types to mock. - /// Arguments for the class' constructor. - public object PartialMultiMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) - { - if (type.IsInterface) - throw new InvalidOperationException("Can't create a partial mock from an interface"); - List extraTypesWithMarker = new List(extraTypes); - extraTypesWithMarker.Add(typeof(IPartialMockMarker)); - return CreateMockObject(type, CreatePartialRecordState, extraTypesWithMarker.ToArray(), argumentsForConstructor); - } - - /// 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 - private object RemotingMock(Type type, CreateMockState factory) - { - ProxyInstance rhinoProxy = new ProxyInstance(this, type); - RhinoInterceptor interceptor = new RhinoInterceptor(this, rhinoProxy); - object transparentProxy = new RemotingMockGenerator().CreateRemotingMock(type, interceptor, rhinoProxy); - IMockState value = factory(rhinoProxy); - proxies.Add(transparentProxy, value); - return transparentProxy; - } - - /// - /// 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 - public void Replay(object obj) - { - ReplayCore(obj, true); - } - - /// - /// 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 - /// - protected internal void ReplayCore(object obj, bool checkInsideOrdering) - { - if (checkInsideOrdering) - NotInsideOrderring(); - - IsMockObjectFromThisRepository(obj); - ClearLastProxy(obj); - IMockState state = proxies[obj]; - proxies[obj] = state.Replay(); - foreach (IMockedObject dependentMock in GetMockedObject(obj).DependentMocks) - { - ReplayCore(dependentMock, checkInsideOrdering); - } - } - - /// 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! - public void BackToRecord(object obj) - { - BackToRecord(obj, BackToRecordOptions.All); - } - - /// - /// 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. - /// - public void BackToRecord(object obj, BackToRecordOptions options) - { - IsMockObjectFromThisRepository(obj); - - if ((options & BackToRecordOptions.Expectations) == BackToRecordOptions.Expectations) - { - foreach (IExpectation expectation in rootRecorder.GetAllExpectationsForProxy(obj)) - { - rootRecorder.RemoveExpectation(expectation); - } - rootRecorder.RemoveAllRepeatableExpectationsForProxy(obj); - } - - GetMockedObject(obj).ClearState(options); - - proxies[obj] = proxies[obj].BackToRecord(); - foreach (IMockedObject dependentMock in GetMockedObject(obj).DependentMocks) - { - BackToRecord(dependentMock, options); - } - } - - /* - * Method: Verify - * Verifies that all expectations has been met for a single mock object. - * After calling this method and action taken on the mock object would result in an - * exception even if the object is a dynamic mock. - */ - - /// - /// Verify that all the expectations for this object were fulfilled. - /// - /// the object to verify the expectations for - public void Verify(object obj) - { - IsMockObjectFromThisRepository(obj); - try - { - proxies[obj].Verify(); - foreach (IMockedObject dependentMock in GetMockedObject(obj).DependentMocks) - { - Verify(dependentMock); - } - } - finally - { - //This is needed because there might be an exception in verifying - //and I still need the mock state to move to verified. - proxies[obj] = proxies[obj].VerifyState; - } - } - - /* - * Method: LastMethodCall - * Gets the method options for the last call on mockedInstance - */ - - /// - /// Get the method options for the last call on - /// mockedInstance. - /// - /// The mock object - /// Method options for the last call - internal IMethodOptions LastMethodCall(object mockedInstance) - { - object mock = GetMockObjectFromInvocationProxy(mockedInstance); - IsMockObjectFromThisRepository(mock); - return proxies[mock].GetLastMethodOptions(); - } - - #endregion - - #region Implementation Details - - /* - * Method: MethodCall - * Handles a method call for a mock object. - */ - - internal object MethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args) - { - //This can happen only if a vritual method call originated from - //the constructor, before Rhino Mocks knows about the existance - //of this proxy. Those type of calls will be ignored and not count - //as expectations, since there is not way to relate them to the - //proper state. - if (proxies.ContainsKey(proxy) == false) - { - //We allow calls to virtual methods from the ctor only for partial mocks. - if (proxy is IPartialMockMarker) - { - invocation.Proceed(); - return invocation.ReturnValue; - } - return null; - } - IMockState state = proxies[proxy]; - GetMockedObject(proxy).MethodCall(method, args); - return state.MethodCall(invocation, method, args); - } - - /// - /// 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 - internal object GetMockObjectFromInvocationProxy(object invocationProxy) - { - object proxy = delegateProxies[invocationProxy]; - if (proxy != null) return proxy; - return invocationProxy; - } - - private IMockState CreateRecordState(IMockedObject mockedObject) - { - return new RecordMockState(mockedObject, this); - } - - private IMockState CreateDynamicRecordState(IMockedObject mockedObject) - { - return new RecordDynamicMockState(mockedObject, this); - } - - private IMockState CreatePartialRecordState(IMockedObject mockedObject) - { - return new RecordPartialMockState(mockedObject, this); - } - - private void NotInsideOrderring() - { - if (Recorder != rootRecorder) - throw new InvalidOperationException( - "Can't start replaying because Ordered or Unordered properties were call and not yet disposed."); - } - - private void ClearLastProxy(object obj) - { - if (GetMockedObjectOrNull(obj) == lastMockedObject) - lastMockedObject = null; - } - - private object MockClass(CreateMockState mockStateFactory, Type type, Type[] extras, object[] argumentsForConstructor) - { - if (type.IsSealed) - throw new NotSupportedException("Can't create mocks of sealed classes"); - List implementedTypesForGenericInvocationDiscoverability = new List(extras); - implementedTypesForGenericInvocationDiscoverability.Add(type); - RhinoInterceptor interceptor = new RhinoInterceptor(this, new ProxyInstance(this, implementedTypesForGenericInvocationDiscoverability.ToArray())); - ArrayList types = new ArrayList(); - types.AddRange(extras); - types.Add(typeof(IMockedObject)); - object proxy; - try - { - proxyGenerationOptions = ProxyGenerationOptions.Default; - proxy = GetProxyGenerator(type).CreateClassProxy(type, (Type[])types.ToArray(typeof(Type)), - proxyGenerationOptions, - argumentsForConstructor, interceptor); - } - catch (MissingMethodException mme) - { - throw new MissingMethodException("Can't find a constructor with matching arguments", mme); - } - catch (TargetInvocationException tie) - { - throw new Exception("Exception in constructor: " + tie.InnerException, tie.InnerException); - } - IMockedObject mockedObject = (IMockedObject)proxy; - mockedObject.ConstructorArguments = argumentsForConstructor; - IMockState value = mockStateFactory(mockedObject); - proxies.Add(proxy, value); - GC.SuppressFinalize(proxy);//avoid issues with expectations created/validated on the finalizer thread - return proxy; - } - - private object MockInterface(CreateMockState mockStateFactory, Type type, Type[] extras) - { - object proxy; - List implementedTypesForGenericInvocationDiscoverability = new List(extras); - implementedTypesForGenericInvocationDiscoverability.Add(type); - RhinoInterceptor interceptor = new RhinoInterceptor(this, new ProxyInstance(this, - implementedTypesForGenericInvocationDiscoverability - .ToArray())); - - List types = new List(); - types.AddRange(extras); - types.Add(typeof(IMockedObject)); - proxy = - GetProxyGenerator(type).CreateInterfaceProxyWithoutTarget(type, types.ToArray(), proxyGenerationOptions, interceptor); - IMockState value = mockStateFactory((IMockedObject)proxy); - proxies.Add(proxy, value); - return proxy; - } - - private object MockDelegate(CreateMockState mockStateFactory, Type type) - { - if (typeof(Delegate).Equals(type)) - throw new InvalidOperationException("Cannot mock the Delegate base type."); - - object proxy; - - ProxyInstance proxyInstance = new ProxyInstance(this, type); - RhinoInterceptor interceptor = new RhinoInterceptor(this, proxyInstance); - - Type[] types = new Type[] { typeof(IMockedObject) }; - var delegateTargetInterface = delegateTargetInterfaceCreator.GetDelegateTargetInterface(type); - object target = GetProxyGenerator(type).CreateInterfaceProxyWithoutTarget( - delegateTargetInterface, - types, proxyGenerationOptions, interceptor); - - proxy = Delegate.CreateDelegate(type, target, delegateTargetInterface.Name+ ".Invoke"); - delegateProxies.Add(target, proxy); - - IMockState value = mockStateFactory(GetMockedObject(proxy)); - proxies.Add(proxy, value); - return proxy; - } - - /// 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 - /// - protected object CreateMockObject(Type type, CreateMockState factory, Type[] extras, params object[] argumentsForConstructor) - { - foreach (Type extraType in extras) - { - if (!extraType.IsInterface) - { - throw new ArgumentException("Extra types must all be interfaces", "extras"); - } - } - - if (type.IsInterface) - { - if (argumentsForConstructor != null && argumentsForConstructor.Length > 0) - { - throw new ArgumentException( - "Constructor arguments should not be supplied when mocking an interface", - "argumentsForConstructor"); - } - return MockInterface(factory, type, extras); - } - else if (typeof(Delegate).IsAssignableFrom(type)) - { - if (argumentsForConstructor != null && argumentsForConstructor.Length > 0) - { - throw new ArgumentException("Constructor arguments should not be supplied when mocking a delegate", - "argumentsForConstructor"); - } - return MockDelegate(factory, type); - } - else - return MockClass(factory, type, extras, argumentsForConstructor); - } - - private void IsMockObjectFromThisRepository(object obj) - { - if (proxies.ContainsKey(obj) == false) - throw new ObjectNotMockFromThisRepositoryException( - "The object is not a mock object that belong to this repository."); - } - - /// - /// Method: GetMockedObject - /// Get an IProxy from a mocked object instance, or throws if the - /// object is not a mock object. - /// - protected internal static IMockedObject GetMockedObject(object mockedInstance) - { - IMockedObject mockedObj = GetMockedObjectOrNull(mockedInstance); - if (mockedObj == null) - throw new InvalidOperationException("The object '" + mockedInstance + - "' is not a mocked object."); - return mockedObj; - } - - /// - /// Method: GetMockedObjectOrNull - /// Get an IProxy from a mocked object instance, or null if the - /// object is not a mock object. - /// - protected internal static IMockedObject GetMockedObjectOrNull(object mockedInstance) - { - Delegate mockedDelegate = mockedInstance as Delegate; - - if (mockedDelegate != null) - { - mockedInstance = mockedDelegate.Target; - } - - // must be careful not to call any methods on mocked objects, - // or it may cause infinite recursion - if (mockedInstance is IMockedObject) - { - return (IMockedObject)mockedInstance; - } - - if (RemotingMockGenerator.IsRemotingProxy(mockedInstance)) - { - return RemotingMockGenerator.GetMockedObjectFromProxy(mockedInstance); - } - - return null; - } - - /// Pops the recorder. - internal void PopRecorder() - { - if (recorders.Count > 1) - recorders.Pop(); - } - - /// Pushes the recorder. - /// New recorder. - internal void PushRecorder(IMethodRecorder newRecorder) - { - recorders.Push(newRecorder); - } - - #endregion - - #region Convenience Methods - - /// - /// All the mock objects in this repository will be moved - /// to record state. - /// - public void BackToRecordAll() - { - BackToRecordAll(BackToRecordOptions.All); - } - - /// - /// All the mock objects in this repository will be moved - /// to record state. - /// - public void BackToRecordAll(BackToRecordOptions options) - { - if (proxies.Count == 0) - return; - foreach (object key in new ArrayList(proxies.Keys)) - { - BackToRecord(key, options); - } - } - - /* - * Method: ReplayAll - * Moves all the mock objects in the repository to replay state. - * - * Note: - * This method will skip any mock object that you've manually moved to replay state - * by calling - */ - - /// - /// Replay all the mocks from this repository - /// - public void ReplayAll() - { - if (proxies.Count == 0) - return; - foreach (object key in new ArrayList(proxies.Keys)) - { - if (proxies[key] is RecordMockState) - Replay(key); - } - } - - /* - * Method: VerifyAll - * Verifies that all the expectations on all mock objects in the repository are met. - * - * Note: - * This method skip any mock objects that you've manually verified using - * - * Exception safety: - * If an unexpected exception has been thrown (which would fail the test) and the Repository - * still have unsatisfied expectations, this method will cause _another_ exception, that may - * mask the real cause. - * If this happens to you, you may need to avoid the using statement until you figure out what is wrong: - * The using statement: - * (start code) - * using(MockRepository mocks = new MockRepository()) - * { - * // Some action that cause an unexpected exception - * // which would cause unsatisfied expectation and cause - * // VerifyAll() to fail. - * } - * (end) - * - * The unrolled using statement: - * (start code) - * MockRepository mocks = new MockRepository()) - * //The afore mentioned action - * mocks.VerifyAll()//won't occur if an exception is thrown - * (end) - * - * This way you can get the real exception from the unit testing framework. - */ - - /// - /// Verify all the mocks from this repository - /// - public void VerifyAll() - { - if (lastRepository == this) - lastRepository = null; - if (proxies.Keys.Count == 0) - return; - StringCollection validationErrors = new StringCollection(); - foreach (object key in new ArrayList(proxies.Keys)) - { - if (proxies[key] is VerifiedMockState) - continue; - try - { - Verify(key); - } - catch (ExpectationViolationException e) - { - validationErrors.Add(e.Message); - } - } - if (validationErrors.Count == 0) - return; - if (validationErrors.Count == 1) - throw new ExpectationViolationException(validationErrors[0]); - StringBuilder sb = new StringBuilder(); - foreach (string validationError in validationErrors) - { - sb.AppendLine(validationError); - } - throw new ExpectationViolationException(sb.ToString()); - } - - /// - /// Gets the replayer for this repository. - /// - /// - internal IMethodRecorder Replayer - { - get { return rootRecorder; } - } - - /// - /// Gets the last proxy which had a method call. - /// - internal static IMockedObject LastMockedObject - { - get - { - if (lastRepository == null) - return null; - return lastRepository.lastMockedObject; - } - } - - /// - /// 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. - /// - protected virtual ProxyGenerator GetProxyGenerator(Type type) - { - if (!generatorMap.ContainsKey(type)) - { - generatorMap[type] = new ProxyGenerator(); - } - - return generatorMap[type]; - } - - - - /// Set the exception to be thrown when verified is called. - protected internal static void SetExceptionToBeThrownOnVerify(object proxy, ExpectationViolationException expectationViolationException) - { - MockRepository repository = GetMockedObject(proxy).Repository; - if (repository.proxies.ContainsKey(proxy) == false) - return; - repository.proxies[proxy].SetExceptionToThrowOnVerify(expectationViolationException); - } - - #endregion - - /// - /// 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 - [Obsolete("Use StrictMock instead")] - public T CreateMock(params object[] argumentsForConstructor) - { - return StrictMock(argumentsForConstructor); - } - - /// - /// 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 - public T StrictMock(params object[] argumentsForConstructor) - { - if (ShouldUseRemotingProxy(typeof(T), argumentsForConstructor)) - return (T)RemotingMock(typeof(T), CreateRecordState); - return (T)CreateMockObject(typeof(T), CreateRecordState, new Type[0], argumentsForConstructor); - } - - private static bool ShouldUseRemotingProxy(Type type, object[] argumentsForConstructor) - { - return typeof(MarshalByRefObject).IsAssignableFrom(type) && - (argumentsForConstructor == null || argumentsForConstructor.Length == 0); - } - - /* - * Method: DynamicMock - * Create a mock object of type T with dynamic semantics. - * Dynamic semantics means that any call that wasn't explicitly recorded is accepted and a - * null or zero is returned (if there is a return value). - */ - - /// - /// Creates a dynamic mock for the specified type. - /// - /// Arguments for the class' constructor, if mocking a concrete class - public T DynamicMock(params object[] argumentsForConstructor) - where T : class - { - if (ShouldUseRemotingProxy(typeof(T), argumentsForConstructor)) - return (T)RemotingMock(typeof(T), CreateDynamicRecordState); - return (T)CreateMockObject(typeof(T), CreateDynamicRecordState, new Type[0], argumentsForConstructor); - } - - /// - /// Creates a mock object from several types. - /// - [Obsolete("Use StrictMultiMock instead")] - public T CreateMultiMock(params Type[] extraTypes) - { - return StrictMultiMock(extraTypes); - } - - /// - /// Creates a strict mock object from several types. - /// - public T StrictMultiMock(params Type[] extraTypes) - { - return (T)StrictMultiMock(typeof(T), extraTypes); - } - - /// - /// Create a mock object from several types with dynamic semantics. - /// - public T DynamicMultiMock(params Type[] extraTypes) - { - return (T)DynamicMultiMock(typeof(T), extraTypes); - } - - /// - /// Create a mock object from several types with partial semantics. - /// - public T PartialMultiMock(params Type[] extraTypes) - { - return (T)PartialMultiMock(typeof(T), extraTypes); - } - - /// - /// 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 - [Obsolete("Use StrictMultiMock instead")] - public T CreateMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) - { - return StrictMultiMock(extraTypes, argumentsForConstructor); - } - - - /// - /// 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 - public T StrictMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) - { - return (T)StrictMultiMock(typeof(T), extraTypes, argumentsForConstructor); - } - - /// - /// 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 - public T DynamicMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) - { - return (T)DynamicMultiMock(typeof(T), extraTypes, argumentsForConstructor); - } - - /// - /// 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 - public T PartialMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) - { - return (T)PartialMultiMock(typeof(T), extraTypes, argumentsForConstructor); - } - - /* - * Method: PartialMock - * Create a mock object with from a class that defaults to calling the class methods - * if no expectation is set on the method. - * - */ - - /// - /// 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 - public T PartialMock(params object[] argumentsForConstructor) where T : class - { - return (T)PartialMock(typeof(T), argumentsForConstructor); - } - - /// - /// 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. - public T Stub(params object[] argumentsForConstructor) - { - return (T)Stub(typeof(T), argumentsForConstructor); - } - - /// - /// 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 - public object Stub(Type type, params object[] argumentsForConstructor) - { - CreateMockState createStub = mockedObject => new StubRecordMockState(mockedObject, this); - if (ShouldUseRemotingProxy(type, argumentsForConstructor)) - return RemotingMock(type, createStub); - return CreateMockObject(type, createStub, new Type[0], argumentsForConstructor); - } - - /// - /// 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. - public bool IsInReplayMode(object mock) - { - if (mock == null) - throw new ArgumentNullException("mock"); - - if (proxies.ContainsKey(mock)) - { - return proxies[mock] is ReplayMockState; - } - - throw new ArgumentException(mock + " is not a mock.", "mock"); - } - - /// - /// Determines whether the specified proxy is a stub. - /// - /// The proxy. - protected internal static bool IsStub(object proxy) - { - MockRepository repository = GetMockedObject(proxy).Repository; - IMockState mockState = repository.proxies[proxy]; - return mockState is StubRecordMockState || mockState is StubReplayMockState; - } - - /// - /// Register a call on a prperty behavior - /// - /// - protected internal void RegisterPropertyBehaviorOn(IMockedObject instance) - { - lastRepository = this; - lastMockedObject = instance; - proxies[instance].NotifyCallOnPropertyBehavior(); - } - } -} +#region license + +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Castle.DynamicProxy; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Generated; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Impl.RemotingMock; +using Rhino.Mocks.Interfaces; +using Rhino.Mocks.MethodRecorders; + +namespace Rhino.Mocks +{ + /* + * class: MockRepository + * The MockRepository is the main interaction point with Rhino Mocks. + * + * Common usage pattern is to create the on [SetUp] + * and then create mock objects using either or + * and setup expectations on the mock object(s) by + * callling their methods. A call to would move the mock + * object(s) to replay state, a call to is made from the + * [TearDown] method. + * + * Thread Safety: + * MockRepository is capable of verifying in multiply threads, but recording in multiply threads + * is not recommended. If you need to do so you _must_ use the and + * methods and not and + * 's various methods. + * + * Code Sample: + * + * (start code) + * MockRepository mocks; + * + * [SetUp] + * public void Setup() + * { + * mocks = new MockRepository(); + * } + * + * [Test] + * public void CallMethodOnObject() + * { + * + * IDemo demo = (IDemo)mocks.CreateMock(typeof(IDemo)); + * // Setting up an expectation for a call to IDemo.VoidNoArg + * demo.VoidNoArg(); + * mocks.ReplayAll(); + * // Fullifying the expectation for call to IDemo.VoidNoArg + * demo.VoidNoArg(); + * } + * + * [TearDown] + * public void Teardown() + * { + * mocks.VerifyAll(); + * } + * (end) + * + * Class Responsbilities: + * + * - Create and manage mock object throughout their life time + * + * See Also: + * - + * - + * - + * - + */ + + /// + /// Creates proxied instances of types. + /// + public partial class MockRepository + { + /// + /// Delegate: CreateMockState + /// This is used internally to cleanly handle the creation of different + /// RecordMockStates. + /// + protected delegate IMockState CreateMockState(IMockedObject mockedObject); + + #region Variables + + /* + * Variable: generatorMap + * A static variable that is used to hold a map of Types to ProxyGenerators + * + */ + + /// + /// This is a map of types to ProxyGenerators. + /// + private static readonly IDictionary generatorMap = new Dictionary(); + + /* + * Variable: lastRepository + * A static variable that is used to hold the repository that last had a method call + * on one of its mock objects. + * + */ + + /// + /// This is used to record the last repository that has a method called on it. + /// + internal static MockRepository lastRepository; + + /* + * Var: lastProxy + * The last proxy that had a method call for _this_ repository + */ + + /// + /// this is used to get to the last proxy on this repository. + /// + internal IMockedObject lastMockedObject; + + private static readonly DelegateTargetInterfaceCreator delegateTargetInterfaceCreator = + new DelegateTargetInterfaceCreator(); + + /// + /// For mock delegates, maps the proxy instance from intercepted invocations + /// back to the delegate that was originally returned to client code, if any. + /// + protected IDictionary delegateProxies; + + /// + /// All the proxies in the mock repositories + /// + protected ProxyStateDictionary proxies; + + private readonly Stack recorders; + private readonly IMethodRecorder rootRecorder; + /// + /// 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. + /// + private readonly ProxyMethodExpectationsDictionary repeatableMethods; + + private ProxyGenerationOptions proxyGenerationOptions; + + #endregion + + #region Properties + + /* + * Property: Recorder + * Gets the current recorder for the repository. + */ + + /// + /// Gets the recorder. + /// + /// + internal IMethodRecorder Recorder + { + get { return recorders.Peek() as IMethodRecorder; } + } + + #endregion + + #region c'tors + + /* function: MockRepository + * Create a new instance of MockRepository + */ + + /// + /// Creates a new instance. + /// + public MockRepository() + { + proxyGenerationOptions = new ProxyGenerationOptions + { + AttributesToAddToGeneratedTypes = + { + new __ProtectAttribute() + } + }; + recorders = new Stack(); + repeatableMethods = new ProxyMethodExpectationsDictionary(); + rootRecorder = new UnorderedMethodRecorder(repeatableMethods); + recorders.Push(rootRecorder); + proxies = new ProxyStateDictionary(); + delegateProxies = new Hashtable(MockedObjectsEquality.Instance); + + // clean up Arg data to avoid the static data to be carried from one unit test + // to another. + ArgManager.Clear(); + } + + #endregion + + #region Methods + + /* + * Method: Ordered + * Moves the _entire_ to use ordered recording. + * + * This call is only valid during the recording phase. + * This call affects all mock objects that were created from this repository. + * + * The orderring is ended when the returned IDisposable's Dispose() method is called. + * (start code) + * [Test] + * public void CallMethodOnObject() + * { + * IDemo demo = (IDemo)mocks.CreateMock(typeof(IDemo)); + * //Moving to ordered mocking. + * using(mocks.Ordered() + * { + * demo.VoidNoArg(); + * demo.IntNoArg(); + * } + * //Must exit the ordering before calling + * mocks.ReplayAll(); + * //If we would try to call them in any other order, the test would fail + * demo.VoidNoArg(); + * demo.IntNoArg(); + * } + * (end) + * + */ + + /// + /// Move the repository to ordered mode + /// + public IDisposable Ordered() + { + return new RecorderChanger(this, Recorder, new OrderedMethodRecorder(Recorder, repeatableMethods)); + } + + /* + * Method: Unordered + * Moves the _entire_ to use unordered recording (the default). + * + * This call is only valid during the recording phase. + * This call affects all mock objects that were created from this repository. + * + * (start code) + * [Test] + * public void CallMethodOnObject() + * { + * IDemo demo = (IDemo)mocks.CreateMock(typeof(IDemo)); + * //Moving to ordered mocking. + * using(mocks.Ordered() + * { + * demo.VoidNoArg(); + * using(mocks.Unordered() + * { + * demo.VoidNoArg(); + * demo.IntNoArg(); + * } + * demo.IntNoArg(); + * } + * //Must exit the ordering before calling + * mocks.ReplayAll(); + * //The expectations we set up is: + * // 1. demo.VoidNoArgs(); + * // 2. in any order: + * // 1. demo.VoidNoArg(); + * // 2. demo.IntNoArg(); + * // 3. demo.IntNoArg(); + * demo.VoidNoArg(); + * demo.IntNoArg(); + * demo.VoidNoArg(); + * demo.IntNoArg(); + * } + */ + + /// + /// Move the repository to un-ordered mode + /// + public IDisposable Unordered() + { + return new RecorderChanger(this, Recorder, new UnorderedMethodRecorder(Recorder, repeatableMethods)); + } + + /* + * Method: CreateMock + * Create a mock object with strict semantics. + * Strict semantics means that any call that wasn't explicitly recorded is considered an + * error and would cause an exception to be thrown. + */ + + /// + /// Creates a mock for the specified type. + /// + /// Type. + /// Arguments for the class' constructor, if mocking a concrete class + [Obsolete("Use StrictMock instead")] + public object CreateMock(Type type, params object[] argumentsForConstructor) + { + return StrictMock(type, argumentsForConstructor); + } + + /// + /// Creates a strict mock for the specified type. + /// + /// Type. + /// Arguments for the class' constructor, if mocking a concrete class + public object StrictMock(Type type, params object[] argumentsForConstructor) + { + if (ShouldUseRemotingProxy(type, argumentsForConstructor)) + return RemotingMock(type, CreateRecordState); + return StrictMultiMock(type, new Type[0], argumentsForConstructor); + } + + /// + /// Creates a remoting mock for the specified type. + /// + /// Type. + /// Arguments for the class' constructor, if mocking a concrete class + [Obsolete("Use StrictMockWithRemoting instead")] + public object CreateMockWithRemoting(Type type, params object[] argumentsForConstructor) + { + return StrictMockWithRemoting(type, argumentsForConstructor); + } + + /// + /// Creates a strict remoting mock for the specified type. + /// + /// Type. + /// Arguments for the class' constructor, if mocking a concrete class + public object StrictMockWithRemoting(Type type, params object[] argumentsForConstructor) + { + return RemotingMock(type, CreateRecordState); + } + + /// + /// Creates a remoting mock for the specified type. + /// + /// + /// Arguments for the class' constructor, if mocking a concrete class + /// + [Obsolete("Use StrictMockWithRemoting instead")] + public T CreateMockWithRemoting(params object[] argumentsForConstructor) + { + return StrictMockWithRemoting(argumentsForConstructor); + } + + /// + /// Creates a strict remoting mock for the specified type. + /// + /// + /// Arguments for the class' constructor, if mocking a concrete class + /// + public T StrictMockWithRemoting(params object[] argumentsForConstructor) + { + return (T)RemotingMock(typeof(T), CreateRecordState); + } + + /// + /// Creates a mock from several types, with strict semantics. + /// Only may be a class. + /// + [Obsolete("Use StrictMultiMock instead")] + public object CreateMultiMock(Type mainType, params Type[] extraTypes) + { + return StrictMultiMock(mainType, extraTypes); + } + + /// + /// Creates a strict mock from several types, with strict semantics. + /// Only may be a class. + /// + public object StrictMultiMock(Type mainType, params Type[] extraTypes) + { + return StrictMultiMock(mainType, extraTypes, new object[0]); + } + + /// + /// 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. + [Obsolete("Use StrictMultiMock instead")] + public object CreateMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor) + { + return StrictMultiMock(mainType, extraTypes, argumentsForConstructor); + } + + /// + /// 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. + public object StrictMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor) + { + if (argumentsForConstructor == null) argumentsForConstructor = new object[0]; + return CreateMockObject(mainType, CreateRecordState, extraTypes, argumentsForConstructor); + } + + /// + /// Creates a mock from several types, with dynamic semantics. + /// Only may be a class. + /// + /// The main type to mock. + /// Extra interface types to mock. + public object DynamicMultiMock(Type mainType, params Type[] extraTypes) + { + return DynamicMultiMock(mainType, extraTypes, new object[0]); + } + + /// + /// 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. + public object DynamicMultiMock(Type mainType, Type[] extraTypes, params object[] argumentsForConstructor) + { + return CreateMockObject(mainType, CreateDynamicRecordState, extraTypes, argumentsForConstructor); + } + + /* + * Method: DynamicMock + * Create a mock object with dynamic semantics. + * Dynamic semantics means that any call that wasn't explicitly recorded is accepted and a + * null or zero is returned (if there is a return value). + */ + + /// Creates a dynamic mock for the specified type. + /// Type. + /// Arguments for the class' constructor, if mocking a concrete class + public object DynamicMock(Type type, params object[] argumentsForConstructor) + { + if (ShouldUseRemotingProxy(type, argumentsForConstructor)) + return RemotingMock(type, CreateDynamicRecordState); + return DynamicMultiMock(type, new Type[0], argumentsForConstructor); + } + + /// Creates a dynamic mock for the specified type. + /// Type. + /// Arguments for the class' constructor, if mocking a concrete class + public object DynamicMockWithRemoting(Type type, params object[] argumentsForConstructor) + { + return RemotingMock(type, CreateDynamicRecordState); + } + + /// Creates a dynamic mock for the specified type. + /// + /// Arguments for the class' constructor, if mocking a concrete class + /// + public T DynamicMockWithRemoting(params object[] argumentsForConstructor) + { + return (T)RemotingMock(typeof(T), CreateDynamicRecordState); + } + + /// 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. + public object PartialMock(Type type, params object[] argumentsForConstructor) + { + return PartialMultiMock(type, new Type[0], argumentsForConstructor); + } + + /// Creates a mock object that defaults to calling the class methods. + /// Type. + /// Extra interface types to mock. + public object PartialMultiMock(Type type, params Type[] extraTypes) + { + return PartialMultiMock(type, extraTypes, new object[0]); + } + + /// Creates a mock object that defaults to calling the class methods. + /// Type. + /// Extra interface types to mock. + /// Arguments for the class' constructor. + public object PartialMultiMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) + { + if (type.IsInterface) + throw new InvalidOperationException("Can't create a partial mock from an interface"); + List extraTypesWithMarker = new List(extraTypes); + extraTypesWithMarker.Add(typeof(IPartialMockMarker)); + return CreateMockObject(type, CreatePartialRecordState, extraTypesWithMarker.ToArray(), argumentsForConstructor); + } + + /// 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 + private object RemotingMock(Type type, CreateMockState factory) + { + ProxyInstance rhinoProxy = new ProxyInstance(this, type); + RhinoInterceptor interceptor = new RhinoInterceptor(this, rhinoProxy); + object transparentProxy = new RemotingMockGenerator().CreateRemotingMock(type, interceptor, rhinoProxy); + IMockState value = factory(rhinoProxy); + proxies.Add(transparentProxy, value); + return transparentProxy; + } + + /// + /// 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 + public void Replay(object obj) + { + ReplayCore(obj, true); + } + + /// + /// 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 + /// + protected internal void ReplayCore(object obj, bool checkInsideOrdering) + { + if (checkInsideOrdering) + NotInsideOrderring(); + + IsMockObjectFromThisRepository(obj); + ClearLastProxy(obj); + IMockState state = proxies[obj]; + proxies[obj] = state.Replay(); + foreach (IMockedObject dependentMock in GetMockedObject(obj).DependentMocks) + { + ReplayCore(dependentMock, checkInsideOrdering); + } + } + + /// 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! + public void BackToRecord(object obj) + { + BackToRecord(obj, BackToRecordOptions.All); + } + + /// + /// 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. + /// + public void BackToRecord(object obj, BackToRecordOptions options) + { + IsMockObjectFromThisRepository(obj); + + if ((options & BackToRecordOptions.Expectations) == BackToRecordOptions.Expectations) + { + foreach (IExpectation expectation in rootRecorder.GetAllExpectationsForProxy(obj)) + { + rootRecorder.RemoveExpectation(expectation); + } + rootRecorder.RemoveAllRepeatableExpectationsForProxy(obj); + } + + GetMockedObject(obj).ClearState(options); + + proxies[obj] = proxies[obj].BackToRecord(); + foreach (IMockedObject dependentMock in GetMockedObject(obj).DependentMocks) + { + BackToRecord(dependentMock, options); + } + } + + /* + * Method: Verify + * Verifies that all expectations has been met for a single mock object. + * After calling this method and action taken on the mock object would result in an + * exception even if the object is a dynamic mock. + */ + + /// + /// Verify that all the expectations for this object were fulfilled. + /// + /// the object to verify the expectations for + public void Verify(object obj) + { + IsMockObjectFromThisRepository(obj); + try + { + proxies[obj].Verify(); + foreach (IMockedObject dependentMock in GetMockedObject(obj).DependentMocks) + { + Verify(dependentMock); + } + } + finally + { + //This is needed because there might be an exception in verifying + //and I still need the mock state to move to verified. + proxies[obj] = proxies[obj].VerifyState; + } + } + + /* + * Method: LastMethodCall + * Gets the method options for the last call on mockedInstance + */ + + /// + /// Get the method options for the last call on + /// mockedInstance. + /// + /// The mock object + /// Method options for the last call + internal IMethodOptions LastMethodCall(object mockedInstance) + { + object mock = GetMockObjectFromInvocationProxy(mockedInstance); + IsMockObjectFromThisRepository(mock); + return proxies[mock].GetLastMethodOptions(); + } + + #endregion + + #region Implementation Details + + /* + * Method: MethodCall + * Handles a method call for a mock object. + */ + + internal object MethodCall(IInvocation invocation, object proxy, MethodInfo method, object[] args) + { + //This can happen only if a vritual method call originated from + //the constructor, before Rhino Mocks knows about the existance + //of this proxy. Those type of calls will be ignored and not count + //as expectations, since there is not way to relate them to the + //proper state. + if (proxies.ContainsKey(proxy) == false) + { + //We allow calls to virtual methods from the ctor only for partial mocks. + if (proxy is IPartialMockMarker) + { + invocation.Proceed(); + return invocation.ReturnValue; + } + return null; + } + IMockState state = proxies[proxy]; + GetMockedObject(proxy).MethodCall(method, args); + return state.MethodCall(invocation, method, args); + } + + /// + /// 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 + internal object GetMockObjectFromInvocationProxy(object invocationProxy) + { + object proxy = delegateProxies[invocationProxy]; + if (proxy != null) return proxy; + return invocationProxy; + } + + private IMockState CreateRecordState(IMockedObject mockedObject) + { + return new RecordMockState(mockedObject, this); + } + + private IMockState CreateDynamicRecordState(IMockedObject mockedObject) + { + return new RecordDynamicMockState(mockedObject, this); + } + + private IMockState CreatePartialRecordState(IMockedObject mockedObject) + { + return new RecordPartialMockState(mockedObject, this); + } + + private void NotInsideOrderring() + { + if (Recorder != rootRecorder) + throw new InvalidOperationException( + "Can't start replaying because Ordered or Unordered properties were call and not yet disposed."); + } + + private void ClearLastProxy(object obj) + { + if (GetMockedObjectOrNull(obj) == lastMockedObject) + lastMockedObject = null; + } + + private object MockClass(CreateMockState mockStateFactory, Type type, Type[] extras, object[] argumentsForConstructor) + { + if (type.IsSealed) + throw new NotSupportedException("Can't create mocks of sealed classes"); + List implementedTypesForGenericInvocationDiscoverability = new List(extras); + implementedTypesForGenericInvocationDiscoverability.Add(type); + RhinoInterceptor interceptor = new RhinoInterceptor(this, new ProxyInstance(this, implementedTypesForGenericInvocationDiscoverability.ToArray())); + ArrayList types = new ArrayList(); + types.AddRange(extras); + types.Add(typeof(IMockedObject)); + object proxy; + try + { + proxyGenerationOptions = ProxyGenerationOptions.Default; + proxy = GetProxyGenerator(type).CreateClassProxy(type, (Type[])types.ToArray(typeof(Type)), + proxyGenerationOptions, + argumentsForConstructor, interceptor); + } + catch (MissingMethodException mme) + { + throw new MissingMethodException("Can't find a constructor with matching arguments", mme); + } + catch (TargetInvocationException tie) + { + throw new Exception("Exception in constructor: " + tie.InnerException, tie.InnerException); + } + IMockedObject mockedObject = (IMockedObject)proxy; + mockedObject.ConstructorArguments = argumentsForConstructor; + IMockState value = mockStateFactory(mockedObject); + proxies.Add(proxy, value); + GC.SuppressFinalize(proxy);//avoid issues with expectations created/validated on the finalizer thread + return proxy; + } + + private object MockInterface(CreateMockState mockStateFactory, Type type, Type[] extras) + { + object proxy; + List implementedTypesForGenericInvocationDiscoverability = new List(extras); + implementedTypesForGenericInvocationDiscoverability.Add(type); + RhinoInterceptor interceptor = new RhinoInterceptor(this, new ProxyInstance(this, + implementedTypesForGenericInvocationDiscoverability + .ToArray())); + + List types = new List(); + types.AddRange(extras); + types.Add(typeof(IMockedObject)); + proxy = + GetProxyGenerator(type).CreateInterfaceProxyWithoutTarget(type, types.ToArray(), proxyGenerationOptions, interceptor); + IMockState value = mockStateFactory((IMockedObject)proxy); + proxies.Add(proxy, value); + return proxy; + } + + private object MockDelegate(CreateMockState mockStateFactory, Type type) + { + if (typeof(Delegate).Equals(type)) + throw new InvalidOperationException("Cannot mock the Delegate base type."); + + object proxy; + + ProxyInstance proxyInstance = new ProxyInstance(this, type); + RhinoInterceptor interceptor = new RhinoInterceptor(this, proxyInstance); + + Type[] types = new Type[] { typeof(IMockedObject) }; + var delegateTargetInterface = delegateTargetInterfaceCreator.GetDelegateTargetInterface(type); + object target = GetProxyGenerator(type).CreateInterfaceProxyWithoutTarget( + delegateTargetInterface, + types, proxyGenerationOptions, interceptor); + + proxy = Delegate.CreateDelegate(type, target, delegateTargetInterface.Name+ ".Invoke"); + delegateProxies.Add(target, proxy); + + IMockState value = mockStateFactory(GetMockedObject(proxy)); + proxies.Add(proxy, value); + return proxy; + } + + /// 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 + /// + protected object CreateMockObject(Type type, CreateMockState factory, Type[] extras, params object[] argumentsForConstructor) + { + foreach (Type extraType in extras) + { + if (!extraType.IsInterface) + { + throw new ArgumentException("Extra types must all be interfaces", "extras"); + } + } + + if (type.IsInterface) + { + if (argumentsForConstructor != null && argumentsForConstructor.Length > 0) + { + throw new ArgumentException( + "Constructor arguments should not be supplied when mocking an interface", + "argumentsForConstructor"); + } + return MockInterface(factory, type, extras); + } + else if (typeof(Delegate).IsAssignableFrom(type)) + { + if (argumentsForConstructor != null && argumentsForConstructor.Length > 0) + { + throw new ArgumentException("Constructor arguments should not be supplied when mocking a delegate", + "argumentsForConstructor"); + } + return MockDelegate(factory, type); + } + else + return MockClass(factory, type, extras, argumentsForConstructor); + } + + private void IsMockObjectFromThisRepository(object obj) + { + if (proxies.ContainsKey(obj) == false) + throw new ObjectNotMockFromThisRepositoryException( + "The object is not a mock object that belong to this repository."); + } + + /// + /// Method: GetMockedObject + /// Get an IProxy from a mocked object instance, or throws if the + /// object is not a mock object. + /// + protected internal static IMockedObject GetMockedObject(object mockedInstance) + { + IMockedObject mockedObj = GetMockedObjectOrNull(mockedInstance); + if (mockedObj == null) + throw new InvalidOperationException("The object '" + mockedInstance + + "' is not a mocked object."); + return mockedObj; + } + + /// + /// Method: GetMockedObjectOrNull + /// Get an IProxy from a mocked object instance, or null if the + /// object is not a mock object. + /// + protected internal static IMockedObject GetMockedObjectOrNull(object mockedInstance) + { + Delegate mockedDelegate = mockedInstance as Delegate; + + if (mockedDelegate != null) + { + mockedInstance = mockedDelegate.Target; + } + + // must be careful not to call any methods on mocked objects, + // or it may cause infinite recursion + if (mockedInstance is IMockedObject) + { + return (IMockedObject)mockedInstance; + } + + if (RemotingMockGenerator.IsRemotingProxy(mockedInstance)) + { + return RemotingMockGenerator.GetMockedObjectFromProxy(mockedInstance); + } + + return null; + } + + /// Pops the recorder. + internal void PopRecorder() + { + if (recorders.Count > 1) + recorders.Pop(); + } + + /// Pushes the recorder. + /// New recorder. + internal void PushRecorder(IMethodRecorder newRecorder) + { + recorders.Push(newRecorder); + } + + #endregion + + #region Convenience Methods + + /// + /// All the mock objects in this repository will be moved + /// to record state. + /// + public void BackToRecordAll() + { + BackToRecordAll(BackToRecordOptions.All); + } + + /// + /// All the mock objects in this repository will be moved + /// to record state. + /// + public void BackToRecordAll(BackToRecordOptions options) + { + if (proxies.Count == 0) + return; + foreach (object key in new ArrayList(proxies.Keys)) + { + BackToRecord(key, options); + } + } + + /* + * Method: ReplayAll + * Moves all the mock objects in the repository to replay state. + * + * Note: + * This method will skip any mock object that you've manually moved to replay state + * by calling + */ + + /// + /// Replay all the mocks from this repository + /// + public void ReplayAll() + { + if (proxies.Count == 0) + return; + foreach (object key in new ArrayList(proxies.Keys)) + { + if (proxies[key] is RecordMockState) + Replay(key); + } + } + + /* + * Method: VerifyAll + * Verifies that all the expectations on all mock objects in the repository are met. + * + * Note: + * This method skip any mock objects that you've manually verified using + * + * Exception safety: + * If an unexpected exception has been thrown (which would fail the test) and the Repository + * still have unsatisfied expectations, this method will cause _another_ exception, that may + * mask the real cause. + * If this happens to you, you may need to avoid the using statement until you figure out what is wrong: + * The using statement: + * (start code) + * using(MockRepository mocks = new MockRepository()) + * { + * // Some action that cause an unexpected exception + * // which would cause unsatisfied expectation and cause + * // VerifyAll() to fail. + * } + * (end) + * + * The unrolled using statement: + * (start code) + * MockRepository mocks = new MockRepository()) + * //The afore mentioned action + * mocks.VerifyAll()//won't occur if an exception is thrown + * (end) + * + * This way you can get the real exception from the unit testing framework. + */ + + /// + /// Verify all the mocks from this repository + /// + public void VerifyAll() + { + if (lastRepository == this) + lastRepository = null; + if (proxies.Keys.Count == 0) + return; + StringCollection validationErrors = new StringCollection(); + foreach (object key in new ArrayList(proxies.Keys)) + { + if (proxies[key] is VerifiedMockState) + continue; + try + { + Verify(key); + } + catch (ExpectationViolationException e) + { + validationErrors.Add(e.Message); + } + } + if (validationErrors.Count == 0) + return; + if (validationErrors.Count == 1) + throw new ExpectationViolationException(validationErrors[0]); + StringBuilder sb = new StringBuilder(); + foreach (string validationError in validationErrors) + { + sb.AppendLine(validationError); + } + throw new ExpectationViolationException(sb.ToString()); + } + + /// + /// Gets the replayer for this repository. + /// + /// + internal IMethodRecorder Replayer + { + get { return rootRecorder; } + } + + /// + /// Gets the last proxy which had a method call. + /// + internal static IMockedObject LastMockedObject + { + get + { + if (lastRepository == null) + return null; + return lastRepository.lastMockedObject; + } + } + + /// + /// 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. + /// + protected virtual ProxyGenerator GetProxyGenerator(Type type) + { + if (!generatorMap.ContainsKey(type)) + { + generatorMap[type] = new ProxyGenerator(); + } + + return generatorMap[type]; + } + + + + /// Set the exception to be thrown when verified is called. + protected internal static void SetExceptionToBeThrownOnVerify(object proxy, ExpectationViolationException expectationViolationException) + { + MockRepository repository = GetMockedObject(proxy).Repository; + if (repository.proxies.ContainsKey(proxy) == false) + return; + repository.proxies[proxy].SetExceptionToThrowOnVerify(expectationViolationException); + } + + #endregion + + /// + /// 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 + [Obsolete("Use StrictMock instead")] + public T CreateMock(params object[] argumentsForConstructor) + { + return StrictMock(argumentsForConstructor); + } + + /// + /// 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 + public T StrictMock(params object[] argumentsForConstructor) + { + if (ShouldUseRemotingProxy(typeof(T), argumentsForConstructor)) + return (T)RemotingMock(typeof(T), CreateRecordState); + return (T)CreateMockObject(typeof(T), CreateRecordState, new Type[0], argumentsForConstructor); + } + + private static bool ShouldUseRemotingProxy(Type type, object[] argumentsForConstructor) + { + return typeof(MarshalByRefObject).IsAssignableFrom(type) && + (argumentsForConstructor == null || argumentsForConstructor.Length == 0); + } + + /* + * Method: DynamicMock + * Create a mock object of type T with dynamic semantics. + * Dynamic semantics means that any call that wasn't explicitly recorded is accepted and a + * null or zero is returned (if there is a return value). + */ + + /// + /// Creates a dynamic mock for the specified type. + /// + /// Arguments for the class' constructor, if mocking a concrete class + public T DynamicMock(params object[] argumentsForConstructor) + where T : class + { + if (ShouldUseRemotingProxy(typeof(T), argumentsForConstructor)) + return (T)RemotingMock(typeof(T), CreateDynamicRecordState); + return (T)CreateMockObject(typeof(T), CreateDynamicRecordState, new Type[0], argumentsForConstructor); + } + + /// + /// Creates a mock object from several types. + /// + [Obsolete("Use StrictMultiMock instead")] + public T CreateMultiMock(params Type[] extraTypes) + { + return StrictMultiMock(extraTypes); + } + + /// + /// Creates a strict mock object from several types. + /// + public T StrictMultiMock(params Type[] extraTypes) + { + return (T)StrictMultiMock(typeof(T), extraTypes); + } + + /// + /// Create a mock object from several types with dynamic semantics. + /// + public T DynamicMultiMock(params Type[] extraTypes) + { + return (T)DynamicMultiMock(typeof(T), extraTypes); + } + + /// + /// Create a mock object from several types with partial semantics. + /// + public T PartialMultiMock(params Type[] extraTypes) + { + return (T)PartialMultiMock(typeof(T), extraTypes); + } + + /// + /// 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 + [Obsolete("Use StrictMultiMock instead")] + public T CreateMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) + { + return StrictMultiMock(extraTypes, argumentsForConstructor); + } + + + /// + /// 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 + public T StrictMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) + { + return (T)StrictMultiMock(typeof(T), extraTypes, argumentsForConstructor); + } + + /// + /// 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 + public T DynamicMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) + { + return (T)DynamicMultiMock(typeof(T), extraTypes, argumentsForConstructor); + } + + /// + /// 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 + public T PartialMultiMock(Type[] extraTypes, params object[] argumentsForConstructor) + { + return (T)PartialMultiMock(typeof(T), extraTypes, argumentsForConstructor); + } + + /* + * Method: PartialMock + * Create a mock object with from a class that defaults to calling the class methods + * if no expectation is set on the method. + * + */ + + /// + /// 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 + public T PartialMock(params object[] argumentsForConstructor) where T : class + { + return (T)PartialMock(typeof(T), argumentsForConstructor); + } + + /// + /// 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. + public T Stub(params object[] argumentsForConstructor) + { + return (T)Stub(typeof(T), argumentsForConstructor); + } + + /// + /// 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 + public object Stub(Type type, params object[] argumentsForConstructor) + { + CreateMockState createStub = mockedObject => new StubRecordMockState(mockedObject, this); + if (ShouldUseRemotingProxy(type, argumentsForConstructor)) + return RemotingMock(type, createStub); + return CreateMockObject(type, createStub, new Type[0], argumentsForConstructor); + } + + /// + /// 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. + public bool IsInReplayMode(object mock) + { + if (mock == null) + throw new ArgumentNullException("mock"); + + if (proxies.ContainsKey(mock)) + { + return proxies[mock] is ReplayMockState; + } + + throw new ArgumentException(mock + " is not a mock.", "mock"); + } + + /// + /// Determines whether the specified proxy is a stub. + /// + /// The proxy. + protected internal static bool IsStub(object proxy) + { + MockRepository repository = GetMockedObject(proxy).Repository; + IMockState mockState = repository.proxies[proxy]; + return mockState is StubRecordMockState || mockState is StubReplayMockState; + } + + /// + /// Register a call on a prperty behavior + /// + /// + protected internal void RegisterPropertyBehaviorOn(IMockedObject instance) + { + lastRepository = this; + lastMockedObject = instance; + proxies[instance].NotifyCallOnPropertyBehavior(); + } + } +} diff --git a/Rhino.Mocks/MockRepositoryAAA.cs b/Rhino.Mocks/MockRepositoryAAA.cs index c3a714cb..e751a3cb 100644 --- a/Rhino.Mocks/MockRepositoryAAA.cs +++ b/Rhino.Mocks/MockRepositoryAAA.cs @@ -1,191 +1,191 @@ -using System; - -namespace Rhino.Mocks -{ - // Static methods for working with RhinoMocks using AAA syntax - public partial class MockRepository - { - /// Generates a stub without needing a - /// Arguments for 's constructor - /// The of stub to create. - /// The stub - /// - public static T GenerateStub(params object[] argumentsForConstructor) where T : class - { - return CreateMockInReplay(repo => (T)repo.Stub(typeof(T), argumentsForConstructor)); - } - - /// Generates a stub without needing a - /// The of stub. - /// Arguments for the 's constructor. - /// The stub - /// - public static object GenerateStub(Type type, params object[] argumentsForConstructor) - { - return CreateMockInReplay(repo => repo.Stub(type, argumentsForConstructor)); - } - - /// Generate a mock object without needing a - /// type of mock object to create. - /// Arguments for 's constructor - /// the mock object - /// - public static T GenerateMock(params object[] argumentsForConstructor) where T : class - { - return CreateMockInReplay(r => r.DynamicMock(argumentsForConstructor)); - } - - /// 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 - /// - public static T GenerateMock(params object[] argumentsForConstructor) - { - return (T) GenerateMock(typeof (T), new Type[] {typeof (TMultiMockInterface1)}, argumentsForConstructor); - } - - /// 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 - /// - public static T GenerateMock(params object[] argumentsForConstructor) - { - return (T) GenerateMock(typeof (T), new Type[] {typeof (TMultiMockInterface1), typeof (TMultiMockInterface2)}, argumentsForConstructor); - } - - /// 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 - /// - public static object GenerateMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) - { - return CreateMockInReplay(r => r.DynamicMultiMock(type, extraTypes, argumentsForConstructor)); - } - - ///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 - /// - public static T GenerateStrictMock(params object[] argumentsForConstructor) - { - return CreateMockInReplay(r => r.StrictMock(argumentsForConstructor)); - } - - ///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 - /// - public static T GenerateStrictMock(params object[] argumentsForConstructor) - { - return (T)GenerateStrictMock(typeof(T), new Type[] { typeof(TMultiMockInterface1) }, argumentsForConstructor); - } - - ///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 - /// - public static T GenerateStrictMock(params object[] argumentsForConstructor) - { - return (T)GenerateStrictMock(typeof(T), new Type[] { typeof(TMultiMockInterface1), typeof(TMultiMockInterface2) }, argumentsForConstructor); - } - - ///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 - /// - public static object GenerateStrictMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) - { - if (extraTypes == null) extraTypes = new Type[0]; - if (argumentsForConstructor == null) argumentsForConstructor = new object[0]; - - return CreateMockInReplay(r => r.StrictMultiMock(type, extraTypes, argumentsForConstructor)); - } - - /// - /// - /// - /// - /// - public static T GeneratePartialMock(params object[] argumentsForConstructor) - { - return (T)GeneratePartialMock(typeof(T), new Type[0], argumentsForConstructor); - } - - /// - /// - /// - /// - /// - /// - public static T GeneratePartialMock(params object[] argumentsForConstructor) - { - return (T)GeneratePartialMock(typeof(T), new Type[] { typeof(TMultiMockInterface1) }, argumentsForConstructor); - } - - /// - /// - /// - /// - /// - /// - /// - public static T GeneratePartialMock(params object[] argumentsForConstructor) - { - return (T)GeneratePartialMock(typeof(T), new Type[] { typeof(TMultiMockInterface1), typeof(TMultiMockInterface2) }, argumentsForConstructor); - } - - /// - /// - /// - /// - /// - /// - public static object GeneratePartialMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) - { - return CreateMockInReplay(r => r.PartialMultiMock(type, extraTypes, argumentsForConstructor)); - } - - /// - /// Generate a mock object with dynamic replay semantics and remoting without needing the mock repository - /// - public static T GenerateDynamicMockWithRemoting(params object[] argumentsForConstructor) - { - return CreateMockInReplay(r => r.DynamicMockWithRemoting(argumentsForConstructor)); - } - - /// - /// Generate a mock object with strict replay semantics and remoting without needing the mock repository - /// - public static T GenerateStrictMockWithRemoting(params object[] argumentsForConstructor) where T : class - { - return CreateMockInReplay(r => r.StrictMockWithRemoting(argumentsForConstructor)); - } - - /// 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. - private static T CreateMockInReplay(Func createMock) - { - var repository = new MockRepository(); - var mockObject = createMock(repository); - repository.Replay(mockObject); - return mockObject; - } - } +using System; + +namespace Rhino.Mocks +{ + // Static methods for working with RhinoMocks using AAA syntax + public partial class MockRepository + { + /// Generates a stub without needing a + /// Arguments for 's constructor + /// The of stub to create. + /// The stub + /// + public static T GenerateStub(params object[] argumentsForConstructor) where T : class + { + return CreateMockInReplay(repo => (T)repo.Stub(typeof(T), argumentsForConstructor)); + } + + /// Generates a stub without needing a + /// The of stub. + /// Arguments for the 's constructor. + /// The stub + /// + public static object GenerateStub(Type type, params object[] argumentsForConstructor) + { + return CreateMockInReplay(repo => repo.Stub(type, argumentsForConstructor)); + } + + /// Generate a mock object without needing a + /// type of mock object to create. + /// Arguments for 's constructor + /// the mock object + /// + public static T GenerateMock(params object[] argumentsForConstructor) where T : class + { + return CreateMockInReplay(r => r.DynamicMock(argumentsForConstructor)); + } + + /// 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 + /// + public static T GenerateMock(params object[] argumentsForConstructor) + { + return (T) GenerateMock(typeof (T), new Type[] {typeof (TMultiMockInterface1)}, argumentsForConstructor); + } + + /// 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 + /// + public static T GenerateMock(params object[] argumentsForConstructor) + { + return (T) GenerateMock(typeof (T), new Type[] {typeof (TMultiMockInterface1), typeof (TMultiMockInterface2)}, argumentsForConstructor); + } + + /// 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 + /// + public static object GenerateMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) + { + return CreateMockInReplay(r => r.DynamicMultiMock(type, extraTypes, argumentsForConstructor)); + } + + ///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 + /// + public static T GenerateStrictMock(params object[] argumentsForConstructor) + { + return CreateMockInReplay(r => r.StrictMock(argumentsForConstructor)); + } + + ///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 + /// + public static T GenerateStrictMock(params object[] argumentsForConstructor) + { + return (T)GenerateStrictMock(typeof(T), new Type[] { typeof(TMultiMockInterface1) }, argumentsForConstructor); + } + + ///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 + /// + public static T GenerateStrictMock(params object[] argumentsForConstructor) + { + return (T)GenerateStrictMock(typeof(T), new Type[] { typeof(TMultiMockInterface1), typeof(TMultiMockInterface2) }, argumentsForConstructor); + } + + ///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 + /// + public static object GenerateStrictMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) + { + if (extraTypes == null) extraTypes = new Type[0]; + if (argumentsForConstructor == null) argumentsForConstructor = new object[0]; + + return CreateMockInReplay(r => r.StrictMultiMock(type, extraTypes, argumentsForConstructor)); + } + + /// + /// + /// + /// + /// + public static T GeneratePartialMock(params object[] argumentsForConstructor) + { + return (T)GeneratePartialMock(typeof(T), new Type[0], argumentsForConstructor); + } + + /// + /// + /// + /// + /// + /// + public static T GeneratePartialMock(params object[] argumentsForConstructor) + { + return (T)GeneratePartialMock(typeof(T), new Type[] { typeof(TMultiMockInterface1) }, argumentsForConstructor); + } + + /// + /// + /// + /// + /// + /// + /// + public static T GeneratePartialMock(params object[] argumentsForConstructor) + { + return (T)GeneratePartialMock(typeof(T), new Type[] { typeof(TMultiMockInterface1), typeof(TMultiMockInterface2) }, argumentsForConstructor); + } + + /// + /// + /// + /// + /// + /// + public static object GeneratePartialMock(Type type, Type[] extraTypes, params object[] argumentsForConstructor) + { + return CreateMockInReplay(r => r.PartialMultiMock(type, extraTypes, argumentsForConstructor)); + } + + /// + /// Generate a mock object with dynamic replay semantics and remoting without needing the mock repository + /// + public static T GenerateDynamicMockWithRemoting(params object[] argumentsForConstructor) + { + return CreateMockInReplay(r => r.DynamicMockWithRemoting(argumentsForConstructor)); + } + + /// + /// Generate a mock object with strict replay semantics and remoting without needing the mock repository + /// + public static T GenerateStrictMockWithRemoting(params object[] argumentsForConstructor) where T : class + { + return CreateMockInReplay(r => r.StrictMockWithRemoting(argumentsForConstructor)); + } + + /// 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. + private static T CreateMockInReplay(Func createMock) + { + var repository = new MockRepository(); + var mockObject = createMock(repository); + repository.Replay(mockObject); + return mockObject; + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/MockRepositoryRecordPlayback.cs b/Rhino.Mocks/MockRepositoryRecordPlayback.cs index 9d1d4b65..c3036947 100644 --- a/Rhino.Mocks/MockRepositoryRecordPlayback.cs +++ b/Rhino.Mocks/MockRepositoryRecordPlayback.cs @@ -1,116 +1,116 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Runtime.InteropServices; - -namespace Rhino.Mocks -{ - /// - /// 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 - /// - public partial class MockRepository - { - /// - /// - /// - public IDisposable Record() - { - return new RecordModeChanger(this); - } - - /// - /// - /// - public IDisposable Playback() - { - return new PlaybackModeChanger(this); - } - } - - internal class PlaybackModeChanger : IDisposable - { - private readonly MockRepository m_repository; - - public PlaybackModeChanger(MockRepository repository) - { - m_repository = repository; - } - - public void Dispose() - { - if (DisposableActionsHelper.ExceptionWasThrownAndDisposableActionShouldNotBeCalled()) - return; - m_repository.VerifyAll(); - } - } - - internal static class DisposableActionsHelper - { - internal static bool ExceptionWasThrownAndDisposableActionShouldNotBeCalled() - { - //If we're running under Mono, then we don't want to call Marshall.GetExceptionCode as it - // currently is not implemented - Type t = Type.GetType("Mono.Runtime"); - if (t == null) - { - // Probably running the .NET Framework - if (Marshal.GetExceptionCode() != 0) - { - return true; - } - } - return false; - } - } - - internal class RecordModeChanger : IDisposable - { - private readonly MockRepository m_repository; - - public RecordModeChanger(MockRepository repository) - { - m_repository = repository; - } - - public void Dispose() - { - if (DisposableActionsHelper.ExceptionWasThrownAndDisposableActionShouldNotBeCalled()) - return; - m_repository.ReplayAll(); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.Runtime.InteropServices; + +namespace Rhino.Mocks +{ + /// + /// 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 + /// + public partial class MockRepository + { + /// + /// + /// + public IDisposable Record() + { + return new RecordModeChanger(this); + } + + /// + /// + /// + public IDisposable Playback() + { + return new PlaybackModeChanger(this); + } + } + + internal class PlaybackModeChanger : IDisposable + { + private readonly MockRepository m_repository; + + public PlaybackModeChanger(MockRepository repository) + { + m_repository = repository; + } + + public void Dispose() + { + if (DisposableActionsHelper.ExceptionWasThrownAndDisposableActionShouldNotBeCalled()) + return; + m_repository.VerifyAll(); + } + } + + internal static class DisposableActionsHelper + { + internal static bool ExceptionWasThrownAndDisposableActionShouldNotBeCalled() + { + //If we're running under Mono, then we don't want to call Marshall.GetExceptionCode as it + // currently is not implemented + Type t = Type.GetType("Mono.Runtime"); + if (t == null) + { + // Probably running the .NET Framework + if (Marshal.GetExceptionCode() != 0) + { + return true; + } + } + return false; + } + } + + internal class RecordModeChanger : IDisposable + { + private readonly MockRepository m_repository; + + public RecordModeChanger(MockRepository repository) + { + m_repository = repository; + } + + public void Dispose() + { + if (DisposableActionsHelper.ExceptionWasThrownAndDisposableActionShouldNotBeCalled()) + return; + m_repository.ReplayAll(); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Mocker.cs b/Rhino.Mocks/Mocker.cs index 500be4e9..4ca20a21 100644 --- a/Rhino.Mocks/Mocker.cs +++ b/Rhino.Mocks/Mocker.cs @@ -1,57 +1,57 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections.Generic; -using System.Text; - -namespace Rhino.Mocks -{ - /// - /// Accessor for the current mocker - /// - public static class Mocker - { - static MockRepository current; - - /// - /// The current mocker - /// - public static MockRepository Current - { - get - { - if (current == null) - throw new InvalidOperationException("You cannot use Mocker.Current outside of a With.Mocks block"); - return current; - } - internal set { current = value; } - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rhino.Mocks +{ + /// + /// Accessor for the current mocker + /// + public static class Mocker + { + static MockRepository current; + + /// + /// The current mocker + /// + public static MockRepository Current + { + get + { + if (current == null) + throw new InvalidOperationException("You cannot use Mocker.Current outside of a With.Mocks block"); + return current; + } + internal set { current = value; } + } + } +} diff --git a/Rhino.Mocks/Rhino.Mocks 2.0.csproj b/Rhino.Mocks/Rhino.Mocks 2.0.csproj index cde4a0b1..0b5b929c 100644 --- a/Rhino.Mocks/Rhino.Mocks 2.0.csproj +++ b/Rhino.Mocks/Rhino.Mocks 2.0.csproj @@ -1,267 +1,267 @@ - - - Local - 8.0.50727 - 2.0 - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} - Debug - AnyCPU - Rhino.Mocks - JScript - Grid - IE50 - false - Library - Rhino.Mocks - OnBuildSuccess - true - ..\..\ayende-open-source.snk - - - bin\debug\ - false - 285212672 - false - TRACE;DEBUG;dotNet2 - Rhino.Mocks.xml - true - 4096 - false - false - false - false - true - 4 - true - - - bin\Release\ - false - 285212672 - false - TRACE;dotNet2 - true - 4096 - false - true - false - false - false - 4 - pdbonly - Rhino.Mocks.XML - - - - False - ..\..\SharedLibs\Castle\Castle.Core.dll - - - False - ..\..\SharedLibs\Castle\Castle.DynamicProxy2.dll - - - System - - - System.Data - - - System.XML - - - - - - - - Code - - - Code - - - - - - - - Code - - - Code - - - Code - - - Code - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - - Code - - - Code - - - Code - - - - ayende-open-source.snk - - - - - - - - + + + Local + 8.0.50727 + 2.0 + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} + Debug + AnyCPU + Rhino.Mocks + JScript + Grid + IE50 + false + Library + Rhino.Mocks + OnBuildSuccess + true + ..\..\ayende-open-source.snk + + + bin\debug\ + false + 285212672 + false + TRACE;DEBUG;dotNet2 + Rhino.Mocks.xml + true + 4096 + false + false + false + false + true + 4 + true + + + bin\Release\ + false + 285212672 + false + TRACE;dotNet2 + true + 4096 + false + true + false + false + false + 4 + pdbonly + Rhino.Mocks.XML + + + + False + ..\..\SharedLibs\Castle\Castle.Core.dll + + + False + ..\..\SharedLibs\Castle\Castle.DynamicProxy2.dll + + + System + + + System.Data + + + System.XML + + + + + + + + Code + + + Code + + + + + + + + Code + + + Code + + + Code + + + Code + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + + + + + + + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + + Code + + + Code + + + Code + + + + ayende-open-source.snk + + + + + + + + diff --git a/Rhino.Mocks/Rhino.Mocks.csproj b/Rhino.Mocks/Rhino.Mocks.csproj index d8e3d3d4..bf7a6388 100644 --- a/Rhino.Mocks/Rhino.Mocks.csproj +++ b/Rhino.Mocks/Rhino.Mocks.csproj @@ -1,280 +1,280 @@ - - - Local - 9.0.30729 - 2.0 - {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} - Debug - AnyCPU - Rhino.Mocks - JScript - Grid - IE50 - false - Library - Rhino.Mocks - OnBuildSuccess - true - ..\ayende-open-source.snk - - - 2.0 - - - v3.5 - - - bin\debug\ - false - 285212672 - false - TRACE;DEBUG;DOTNET35 - bin\debug\Rhino.Mocks.XML - true - 4096 - false - false - false - false - true - 4 - true - - - bin\Release\ - false - 285212672 - false - TRACE;dotNet2 - true - 4096 - false - true - false - false - false - 4 - pdbonly - Rhino.Mocks.XML - - - - False - ..\SharedLibs\Castle.Core.dll - - - False - ..\SharedLibs\Castle.DynamicProxy2.dll - - - System - - - 3.5 - - - - - - - - Code - - - Code - - - - - - - - Code - - - Code - - - Code - - - Code - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - Code - - - - Code - - - - Code - - - Code - - - Code - - - - - - ayende-open-source.snk - - - - - - - - - - - + + + Local + 9.0.30729 + 2.0 + {1E8FECC7-9E9B-4275-A938-D956F5E5D4F8} + Debug + AnyCPU + Rhino.Mocks + JScript + Grid + IE50 + false + Library + Rhino.Mocks + OnBuildSuccess + true + ..\ayende-open-source.snk + + + 2.0 + + + v3.5 + + + bin\debug\ + false + 285212672 + false + TRACE;DEBUG;DOTNET35 + bin\debug\Rhino.Mocks.XML + true + 4096 + false + false + false + false + true + 4 + true + + + bin\Release\ + false + 285212672 + false + TRACE;dotNet2 + true + 4096 + false + true + false + false + false + 4 + pdbonly + Rhino.Mocks.XML + + + + False + ..\SharedLibs\Castle.Core.dll + + + False + ..\SharedLibs\Castle.DynamicProxy2.dll + + + System + + + 3.5 + + + + + + + + Code + + + Code + + + + + + + + Code + + + Code + + + Code + + + Code + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + + + + + + + + + + + + + + + + + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + Code + + + + Code + + + + Code + + + Code + + + Code + + + + + + ayende-open-source.snk + + + + + + + + + + + \ No newline at end of file diff --git a/Rhino.Mocks/Rhino.Mocks.csproj.user b/Rhino.Mocks/Rhino.Mocks.csproj.user index e1e6e1c0..5a2e8d60 100644 --- a/Rhino.Mocks/Rhino.Mocks.csproj.user +++ b/Rhino.Mocks/Rhino.Mocks.csproj.user @@ -1,57 +1,57 @@ - - - 7.10.3077 - Debug - AnyCPU - D:\Code\rhino-mocks\vendor\;D:\Code\rhino-mocks\vendor\net-1.1\;C:\Code\rhino-mocks\vendor\net-1.1\ - - - - - 0 - ProjectFiles - 0 - - - false - false - false - false - false - - - Project - - - - - - - - - - - false - - - false - false - false - false - false - - - Project - - - - - - - - - - - false - + + + 7.10.3077 + Debug + AnyCPU + D:\Code\rhino-mocks\vendor\;D:\Code\rhino-mocks\vendor\net-1.1\;C:\Code\rhino-mocks\vendor\net-1.1\ + + + + + 0 + ProjectFiles + 0 + + + false + false + false + false + false + + + Project + + + + + + + + + + + false + + + false + false + false + false + false + + + Project + + + + + + + + + + + false + \ No newline at end of file diff --git a/Rhino.Mocks/RhinoMocks.cs b/Rhino.Mocks/RhinoMocks.cs index 53023bfd..cd099fd9 100644 --- a/Rhino.Mocks/RhinoMocks.cs +++ b/Rhino.Mocks/RhinoMocks.cs @@ -1,61 +1,61 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.IO; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks -{ - /* class: RhinoMocks - * Used for [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] - */ - - /// - /// Used for [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] - /// Used for [assembly: InternalsVisibleTo(RhinoMocks.NormalName)] - /// - public static class RhinoMocks - { - /// - /// Strong name for the Dynamic Proxy assemblies. Used for InternalsVisibleTo specification. - /// - public const string StrongName = - "DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7"; - - /// - /// Normal name for dynamic proxy assemblies. Used for InternalsVisibleTo specification. - /// - public const string NormalName = "DynamicProxyGenAssembly2"; - - /// - /// Logs all method calls for methods - /// - public static IExpectationLogger Logger = new NullLogger(); - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System.IO; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks +{ + /* class: RhinoMocks + * Used for [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] + */ + + /// + /// Used for [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] + /// Used for [assembly: InternalsVisibleTo(RhinoMocks.NormalName)] + /// + public static class RhinoMocks + { + /// + /// Strong name for the Dynamic Proxy assemblies. Used for InternalsVisibleTo specification. + /// + public const string StrongName = + "DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7"; + + /// + /// Normal name for dynamic proxy assemblies. Used for InternalsVisibleTo specification. + /// + public const string NormalName = "DynamicProxyGenAssembly2"; + + /// + /// Logs all method calls for methods + /// + public static IExpectationLogger Logger = new NullLogger(); + } } \ No newline at end of file diff --git a/Rhino.Mocks/RhinoMocksExtensions.cs b/Rhino.Mocks/RhinoMocksExtensions.cs index 51355735..4fc2ecd0 100644 --- a/Rhino.Mocks/RhinoMocksExtensions.cs +++ b/Rhino.Mocks/RhinoMocksExtensions.cs @@ -1,489 +1,489 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - -#if DOTNET35 -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using Rhino.Mocks.Exceptions; -using Rhino.Mocks.Generated; -using Rhino.Mocks.Interfaces; - - -namespace Rhino.Mocks -{ - /// - /// A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks - /// - public static class RhinoMocksExtensions - { - /// - /// Create an expectation on this mock for this action to occur - /// - /// - /// The mock. - /// The action. - /// - public static IMethodOptions Expect(this T mock, Action action) - where T : class - { - return Expect(mock, t => - { - action(t); - return null; - }); - } - - /// - /// Reset all expectations on this mock object - /// - /// - /// The mock. - public static void BackToRecord(this T mock) - { - BackToRecord(mock, BackToRecordOptions.All); - } - - /// - /// Reset the selected expectation on this mock object - /// - /// - /// The mock. - /// The options to reset the expectations on this mock. - public static void BackToRecord(this T mock, BackToRecordOptions options) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mock); - var mocks = mockedObject.Repository; - mocks.BackToRecord(mock, options); - } - - /// - /// 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 - public static void Replay(this T mock) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mock); - var mocks = mockedObject.Repository; - - if (mocks.IsInReplayMode(mock) != true) - mocks.Replay(mockedObject); - } - - /// - /// Gets the mock repository for this specificied mock object - /// - /// - /// The mock. - /// - public static MockRepository GetMockRepository(this T mock) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mock); - return mockedObject.Repository; - } - - /// - /// Create an expectation on this mock for this action to occur - /// - /// - /// - /// The mock. - /// The action. - /// - public static IMethodOptions Expect(this T mock, Function action) - where T : class - { - if (mock == null) - throw new ArgumentNullException("mock", "You cannot mock a null instance"); - - IMockedObject mockedObject = MockRepository.GetMockedObject(mock); - MockRepository mocks = mockedObject.Repository; - var isInReplayMode = mocks.IsInReplayMode(mock); - mocks.BackToRecord(mock, BackToRecordOptions.None); - action(mock); - IMethodOptions options = LastCall.GetOptions(); - options.TentativeReturn(); - if (isInReplayMode) - mocks.ReplayCore(mock, false); - return options; - } - - /// - /// 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. - /// - public static IMethodOptions Stub(this T mock, Action action) - where T : class - { - return Stub(mock, t => - { - action(t); - return null; - }); - } - - /// - /// 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. - /// - public static IMethodOptions Stub(this T mock, Function action) - where T : class - { - return Expect(mock, action).Repeat.Times(0, int.MaxValue); - } - - /// - /// 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)) - /// - /// - public static IList GetArgumentsForCallsMadeOn(this T mock, Action action) - { - return GetArgumentsForCallsMadeOn(mock, action, DefaultConstraintSetup); - } - - /// - /// 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)) - /// - /// - public static IList GetArgumentsForCallsMadeOn(this T mock, Action action, Action> setupConstraints) - { - return GetExpectationsToVerify(mock, action, setupConstraints).ArgumentsForAllCalls; - } - - /// - /// Asserts that a particular method was called on this mock object - /// - /// - /// The mock. - /// The action. - public static void AssertWasCalled(this T mock, Action action) - { - AssertWasCalled(mock, action, DefaultConstraintSetup); - } - - private static void DefaultConstraintSetup(IMethodOptions options) - { - } - - /// - /// Asserts that a particular method was called on this mock object that match - /// a particular constraint set. - /// - /// - /// The mock. - /// The action. - /// The setup constraints. - public static void AssertWasCalled(this T mock, Action action, Action> setupConstraints) - { - ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints); - - foreach (var args in verificationInformation.ArgumentsForAllCalls) - { - if (verificationInformation.Expected.IsExpected(args)) - { - verificationInformation.Expected.AddActualCall(); - } - } - if (verificationInformation.Expected.ExpectationSatisfied) - return; - throw new ExpectationViolationException(verificationInformation.Expected.BuildVerificationFailureMessage()); - } - - /// - /// Asserts that a particular method was called on this mock object that match - /// a particular constraint set. - /// - /// - /// The mock. - /// The action. - public static void AssertWasCalled(this T mock, Func action) - { - var newAction = new Action(t => action(t)); - AssertWasCalled(mock, newAction, DefaultConstraintSetup); - } - - /// - /// Asserts that a particular method was called on this mock object that match - /// a particular constraint set. - /// - /// - /// The mock. - /// The action. - /// The setup constraints. - public static void AssertWasCalled(this T mock, Func action, Action> setupConstraints) - { - var newAction = new Action(t => action(t)); - AssertWasCalled(mock, newAction, setupConstraints); - } - - - /// - /// Asserts that a particular method was NOT called on this mock object - /// - /// - /// The mock. - /// The action. - public static void AssertWasNotCalled(this T mock, Action action) - { - AssertWasNotCalled(mock, action, DefaultConstraintSetup); - } - - /// - /// 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. - public static void AssertWasNotCalled(this T mock, Action action, Action> setupConstraints) - { - ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints); - - foreach (var args in verificationInformation.ArgumentsForAllCalls) - { - if (verificationInformation.Expected.IsExpected(args)) - throw new ExpectationViolationException("Expected that " + - verificationInformation.Expected.ErrorMessage + - " would not be called, but it was found on the actual calls made on the mocked object."); - } - } - - /// - /// Asserts that a particular method was NOT called on this mock object - /// - /// - /// The mock. - /// The action. - public static void AssertWasNotCalled(this T mock, Func action) - { - var newAction = new Action(t => action(t)); - AssertWasNotCalled(mock, newAction, DefaultConstraintSetup); - } - - /// - /// Asserts that a particular method was NOT called on this mock object - /// - /// - /// The mock. - /// The action. - /// The setup constraints. - public static void AssertWasNotCalled(this T mock, Func action, Action> setupConstraints) - { - var newAction = new Action(t => action(t)); - AssertWasNotCalled(mock, newAction, setupConstraints); - } - - private static ExpectationVerificationInformation GetExpectationsToVerify(T mock, Action action, - Action> - setupConstraints) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mock); - MockRepository mocks = mockedObject.Repository; - - if (mocks.IsInReplayMode(mockedObject) == false) - { - throw new InvalidOperationException( - "Cannot assert on an object that is not in replay mode. Did you forget to call ReplayAll() ?"); - } - - var mockToRecordExpectation = - (T)mocks.DynamicMock(FindAppropriteType(mockedObject), mockedObject.ConstructorArguments); - action(mockToRecordExpectation); - - AssertExactlySingleExpectaton(mocks, mockToRecordExpectation); - - IMethodOptions lastMethodCall = mocks.LastMethodCall(mockToRecordExpectation); - lastMethodCall.TentativeReturn(); - if (setupConstraints != null) - { - setupConstraints(lastMethodCall); - } - ExpectationsList expectationsToVerify = mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation); - if (expectationsToVerify.Count == 0) - throw new InvalidOperationException( - "The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()"); - IExpectation expected = expectationsToVerify[0]; - ICollection argumentsForAllCalls = mockedObject.GetCallArgumentsFor(expected.Method); - return new ExpectationVerificationInformation - { - ArgumentsForAllCalls = new List(argumentsForAllCalls), - Expected = expected - }; - } - - /// - /// Finds the approprite implementation type of this item. - /// This is the class or an interface outside of the rhino mocks. - /// - /// The mocked obj. - /// - private static Type FindAppropriteType(IMockedObject mockedObj) - { - foreach (var type in mockedObj.ImplementedTypes) - { - if(type.IsClass && typeof(T).IsAssignableFrom(type)) - return type; - } - foreach (var type in mockedObj.ImplementedTypes) - { - if(type.Assembly==typeof(IMockedObject).Assembly || !typeof(T).IsAssignableFrom(type)) - continue; - return type; - } - return mockedObj.ImplementedTypes[0]; - } - - /// - /// Verifies all expectations on this mock object - /// - /// The mock object. - public static void VerifyAllExpectations(this object mockObject) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mockObject); - mockedObject.Repository.Verify(mockedObject); - } - - - /// - /// 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. - /// - public static IEventRaiser GetEventRaiser(this TEventSource mockObject, Action eventSubscription) - where TEventSource : class - { - return mockObject - .Stub(eventSubscription) - .IgnoreArguments() - .GetEventRaiser(); - } - - /// - /// 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. - public static void Raise(this TEventSource mockObject, Action eventSubscription, object sender, EventArgs args) - where TEventSource : class - { - var eventRaiser = GetEventRaiser(mockObject, eventSubscription); - eventRaiser.Raise(sender, args); - } - - /// - /// 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. - public static void Raise(this TEventSource mockObject, Action eventSubscription, params object[] args) - where TEventSource : class - { - var eventRaiser = GetEventRaiser(mockObject, eventSubscription); - eventRaiser.Raise(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. - private static void AssertExactlySingleExpectaton(MockRepository mocks, T mockToRecordExpectation) - { - if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count == 0) - throw new InvalidOperationException( - "No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call"); - - if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count > 1) - throw new InvalidOperationException( - "You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations"); - } - - #region Nested type: VoidType - - /// - /// Fake type that disallow creating it. - /// Should have been System.Type, but we can't use it. - /// - public class VoidType - { - private VoidType() - { - } - } - - #endregion - } -} -#endif +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + +#if DOTNET35 +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using Rhino.Mocks.Exceptions; +using Rhino.Mocks.Generated; +using Rhino.Mocks.Interfaces; + + +namespace Rhino.Mocks +{ + /// + /// A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks + /// + public static class RhinoMocksExtensions + { + /// + /// Create an expectation on this mock for this action to occur + /// + /// + /// The mock. + /// The action. + /// + public static IMethodOptions Expect(this T mock, Action action) + where T : class + { + return Expect(mock, t => + { + action(t); + return null; + }); + } + + /// + /// Reset all expectations on this mock object + /// + /// + /// The mock. + public static void BackToRecord(this T mock) + { + BackToRecord(mock, BackToRecordOptions.All); + } + + /// + /// Reset the selected expectation on this mock object + /// + /// + /// The mock. + /// The options to reset the expectations on this mock. + public static void BackToRecord(this T mock, BackToRecordOptions options) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mock); + var mocks = mockedObject.Repository; + mocks.BackToRecord(mock, options); + } + + /// + /// 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 + public static void Replay(this T mock) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mock); + var mocks = mockedObject.Repository; + + if (mocks.IsInReplayMode(mock) != true) + mocks.Replay(mockedObject); + } + + /// + /// Gets the mock repository for this specificied mock object + /// + /// + /// The mock. + /// + public static MockRepository GetMockRepository(this T mock) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mock); + return mockedObject.Repository; + } + + /// + /// Create an expectation on this mock for this action to occur + /// + /// + /// + /// The mock. + /// The action. + /// + public static IMethodOptions Expect(this T mock, Function action) + where T : class + { + if (mock == null) + throw new ArgumentNullException("mock", "You cannot mock a null instance"); + + IMockedObject mockedObject = MockRepository.GetMockedObject(mock); + MockRepository mocks = mockedObject.Repository; + var isInReplayMode = mocks.IsInReplayMode(mock); + mocks.BackToRecord(mock, BackToRecordOptions.None); + action(mock); + IMethodOptions options = LastCall.GetOptions(); + options.TentativeReturn(); + if (isInReplayMode) + mocks.ReplayCore(mock, false); + return options; + } + + /// + /// 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. + /// + public static IMethodOptions Stub(this T mock, Action action) + where T : class + { + return Stub(mock, t => + { + action(t); + return null; + }); + } + + /// + /// 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. + /// + public static IMethodOptions Stub(this T mock, Function action) + where T : class + { + return Expect(mock, action).Repeat.Times(0, int.MaxValue); + } + + /// + /// 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)) + /// + /// + public static IList GetArgumentsForCallsMadeOn(this T mock, Action action) + { + return GetArgumentsForCallsMadeOn(mock, action, DefaultConstraintSetup); + } + + /// + /// 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)) + /// + /// + public static IList GetArgumentsForCallsMadeOn(this T mock, Action action, Action> setupConstraints) + { + return GetExpectationsToVerify(mock, action, setupConstraints).ArgumentsForAllCalls; + } + + /// + /// Asserts that a particular method was called on this mock object + /// + /// + /// The mock. + /// The action. + public static void AssertWasCalled(this T mock, Action action) + { + AssertWasCalled(mock, action, DefaultConstraintSetup); + } + + private static void DefaultConstraintSetup(IMethodOptions options) + { + } + + /// + /// Asserts that a particular method was called on this mock object that match + /// a particular constraint set. + /// + /// + /// The mock. + /// The action. + /// The setup constraints. + public static void AssertWasCalled(this T mock, Action action, Action> setupConstraints) + { + ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints); + + foreach (var args in verificationInformation.ArgumentsForAllCalls) + { + if (verificationInformation.Expected.IsExpected(args)) + { + verificationInformation.Expected.AddActualCall(); + } + } + if (verificationInformation.Expected.ExpectationSatisfied) + return; + throw new ExpectationViolationException(verificationInformation.Expected.BuildVerificationFailureMessage()); + } + + /// + /// Asserts that a particular method was called on this mock object that match + /// a particular constraint set. + /// + /// + /// The mock. + /// The action. + public static void AssertWasCalled(this T mock, Func action) + { + var newAction = new Action(t => action(t)); + AssertWasCalled(mock, newAction, DefaultConstraintSetup); + } + + /// + /// Asserts that a particular method was called on this mock object that match + /// a particular constraint set. + /// + /// + /// The mock. + /// The action. + /// The setup constraints. + public static void AssertWasCalled(this T mock, Func action, Action> setupConstraints) + { + var newAction = new Action(t => action(t)); + AssertWasCalled(mock, newAction, setupConstraints); + } + + + /// + /// Asserts that a particular method was NOT called on this mock object + /// + /// + /// The mock. + /// The action. + public static void AssertWasNotCalled(this T mock, Action action) + { + AssertWasNotCalled(mock, action, DefaultConstraintSetup); + } + + /// + /// 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. + public static void AssertWasNotCalled(this T mock, Action action, Action> setupConstraints) + { + ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints); + + foreach (var args in verificationInformation.ArgumentsForAllCalls) + { + if (verificationInformation.Expected.IsExpected(args)) + throw new ExpectationViolationException("Expected that " + + verificationInformation.Expected.ErrorMessage + + " would not be called, but it was found on the actual calls made on the mocked object."); + } + } + + /// + /// Asserts that a particular method was NOT called on this mock object + /// + /// + /// The mock. + /// The action. + public static void AssertWasNotCalled(this T mock, Func action) + { + var newAction = new Action(t => action(t)); + AssertWasNotCalled(mock, newAction, DefaultConstraintSetup); + } + + /// + /// Asserts that a particular method was NOT called on this mock object + /// + /// + /// The mock. + /// The action. + /// The setup constraints. + public static void AssertWasNotCalled(this T mock, Func action, Action> setupConstraints) + { + var newAction = new Action(t => action(t)); + AssertWasNotCalled(mock, newAction, setupConstraints); + } + + private static ExpectationVerificationInformation GetExpectationsToVerify(T mock, Action action, + Action> + setupConstraints) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mock); + MockRepository mocks = mockedObject.Repository; + + if (mocks.IsInReplayMode(mockedObject) == false) + { + throw new InvalidOperationException( + "Cannot assert on an object that is not in replay mode. Did you forget to call ReplayAll() ?"); + } + + var mockToRecordExpectation = + (T)mocks.DynamicMock(FindAppropriteType(mockedObject), mockedObject.ConstructorArguments); + action(mockToRecordExpectation); + + AssertExactlySingleExpectaton(mocks, mockToRecordExpectation); + + IMethodOptions lastMethodCall = mocks.LastMethodCall(mockToRecordExpectation); + lastMethodCall.TentativeReturn(); + if (setupConstraints != null) + { + setupConstraints(lastMethodCall); + } + ExpectationsList expectationsToVerify = mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation); + if (expectationsToVerify.Count == 0) + throw new InvalidOperationException( + "The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()"); + IExpectation expected = expectationsToVerify[0]; + ICollection argumentsForAllCalls = mockedObject.GetCallArgumentsFor(expected.Method); + return new ExpectationVerificationInformation + { + ArgumentsForAllCalls = new List(argumentsForAllCalls), + Expected = expected + }; + } + + /// + /// Finds the approprite implementation type of this item. + /// This is the class or an interface outside of the rhino mocks. + /// + /// The mocked obj. + /// + private static Type FindAppropriteType(IMockedObject mockedObj) + { + foreach (var type in mockedObj.ImplementedTypes) + { + if(type.IsClass && typeof(T).IsAssignableFrom(type)) + return type; + } + foreach (var type in mockedObj.ImplementedTypes) + { + if(type.Assembly==typeof(IMockedObject).Assembly || !typeof(T).IsAssignableFrom(type)) + continue; + return type; + } + return mockedObj.ImplementedTypes[0]; + } + + /// + /// Verifies all expectations on this mock object + /// + /// The mock object. + public static void VerifyAllExpectations(this object mockObject) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mockObject); + mockedObject.Repository.Verify(mockedObject); + } + + + /// + /// 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. + /// + public static IEventRaiser GetEventRaiser(this TEventSource mockObject, Action eventSubscription) + where TEventSource : class + { + return mockObject + .Stub(eventSubscription) + .IgnoreArguments() + .GetEventRaiser(); + } + + /// + /// 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. + public static void Raise(this TEventSource mockObject, Action eventSubscription, object sender, EventArgs args) + where TEventSource : class + { + var eventRaiser = GetEventRaiser(mockObject, eventSubscription); + eventRaiser.Raise(sender, args); + } + + /// + /// 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. + public static void Raise(this TEventSource mockObject, Action eventSubscription, params object[] args) + where TEventSource : class + { + var eventRaiser = GetEventRaiser(mockObject, eventSubscription); + eventRaiser.Raise(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. + private static void AssertExactlySingleExpectaton(MockRepository mocks, T mockToRecordExpectation) + { + if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count == 0) + throw new InvalidOperationException( + "No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call"); + + if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count > 1) + throw new InvalidOperationException( + "You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations"); + } + + #region Nested type: VoidType + + /// + /// Fake type that disallow creating it. + /// Should have been System.Type, but we can't use it. + /// + public class VoidType + { + private VoidType() + { + } + } + + #endregion + } +} +#endif diff --git a/Rhino.Mocks/SetupResult.cs b/Rhino.Mocks/SetupResult.cs index b20cd4e9..547b41fe 100644 --- a/Rhino.Mocks/SetupResult.cs +++ b/Rhino.Mocks/SetupResult.cs @@ -1,93 +1,93 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks -{ - /// - /// Setup method calls to repeat any number of times. - /// - public static class SetupResult - { - /* - * Method: For - * Sets the last method call to repeat any number of times and return the method options - * for the last method call, which usually will be a method call - * or property that is located inside the . - * See Expected Usage. - * - * Expected usage: - * (start code) - * SetupResult.For(mockObject.SomeCall()).Return(new Something()); - * SetupResult.For(mockList.Count).Return(50); - * (end) - * - * Thread safety: - * This method is *not* safe for multi threading scenarios! - * If you need to record in a multi threading environment, use the method, which _can_ - * handle multi threading scenarios. - * - */ - /// - /// 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 - /// - public static IMethodOptions For(T ignored) - { - return LastCall.GetOptions().Repeat.Any(); - } - - /* - * Method: On - * Sets the last method call to repeat any number of times and return the method options - * for the last method call on the mockInstance. - * Unless you're recording in multiply threads, you are probably better off - * using - * - * Expected usage: - * SetupResult.On(mockList).Call(mockList.Count).Return(50); - * - * Thread safety: - * This method can be used in mutli threading scenarios. - */ - /// - /// 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 - /// - public static ICreateMethodExpectation On(object mockedInstace) - { - IMockedObject mockedObject = MockRepository.GetMockedObject(mockedInstace); - return new CreateMethodExpectationForSetupResult(mockedObject, mockedInstace); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks +{ + /// + /// Setup method calls to repeat any number of times. + /// + public static class SetupResult + { + /* + * Method: For + * Sets the last method call to repeat any number of times and return the method options + * for the last method call, which usually will be a method call + * or property that is located inside the . + * See Expected Usage. + * + * Expected usage: + * (start code) + * SetupResult.For(mockObject.SomeCall()).Return(new Something()); + * SetupResult.For(mockList.Count).Return(50); + * (end) + * + * Thread safety: + * This method is *not* safe for multi threading scenarios! + * If you need to record in a multi threading environment, use the method, which _can_ + * handle multi threading scenarios. + * + */ + /// + /// 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 + /// + public static IMethodOptions For(T ignored) + { + return LastCall.GetOptions().Repeat.Any(); + } + + /* + * Method: On + * Sets the last method call to repeat any number of times and return the method options + * for the last method call on the mockInstance. + * Unless you're recording in multiply threads, you are probably better off + * using + * + * Expected usage: + * SetupResult.On(mockList).Call(mockList.Count).Return(50); + * + * Thread safety: + * This method can be used in mutli threading scenarios. + */ + /// + /// 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 + /// + public static ICreateMethodExpectation On(object mockedInstace) + { + IMockedObject mockedObject = MockRepository.GetMockedObject(mockedInstace); + return new CreateMethodExpectationForSetupResult(mockedObject, mockedInstace); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/Utilities/GenericsUtil.cs b/Rhino.Mocks/Utilities/GenericsUtil.cs index 8f560d12..f6652af2 100644 --- a/Rhino.Mocks/Utilities/GenericsUtil.cs +++ b/Rhino.Mocks/Utilities/GenericsUtil.cs @@ -1,135 +1,135 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections.Generic; -using Castle.Core.Interceptor; - -namespace Rhino.Mocks.Utilities -{ - /// - /// Utility class for dealing with messing generics scenarios. - /// - public static class GenericsUtil - { - /// - /// 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. - /// - public static bool HasOpenGenericParam(Type returnType) - { - //not bound to particular type, only way I know of doing this, since IsGeneric and IsGenericTypeDefination will both lie - //when used with generic method parameters - if (returnType.FullName == null) - return true; - foreach (Type genericArgument in returnType.GetGenericArguments()) - { - if (genericArgument.FullName == null) - return true; - if (genericArgument.IsGenericType) - { - if (HasOpenGenericParam(genericArgument)) - return true; - } - } - return false; - } - - /// - /// Gets the real type, including de-constructing and constructing the type of generic - /// methods parameters. - /// - /// The type. - /// The invocation. - /// - public static Type GetRealType(Type type, IInvocation invocation) - { - if (!HasOpenGenericParam(type)) - return type; - Dictionary nameToType = CreateTypesTableFromInvocation(invocation); - string typeName = type.AssemblyQualifiedName ?? type.Name; // if the AssemblyQualifiedName is null, we have an open type - if (nameToType.ContainsKey(typeName)) - return nameToType[typeName]; - Type[] types = new List(nameToType.Values).ToArray(); - return ReconstructGenericType(type, nameToType); - } - - /// - /// 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]] - /// - private static Type ReconstructGenericType(Type type, Dictionary nameToType) - { - Type genericTypeDef = type.GetGenericTypeDefinition(); - List genericArgs = new List(); - foreach (Type genericArgument in type.GetGenericArguments()) - { - if(nameToType.ContainsKey(genericArgument.Name)) - { - genericArgs.Add(nameToType[genericArgument.Name]); - } - else - { - genericArgs.Add( ReconstructGenericType(genericArgument, nameToType)); - } - } - return genericTypeDef.MakeGenericType(genericArgs.ToArray()); - } - - private static Dictionary CreateTypesTableFromInvocation(IInvocation invocation) - { - Dictionary nameToType = new Dictionary(); - Type genericType = GetTypeWithGenericArgumentsForMethodParameters(invocation); - Type[] genericArguments = genericType.GetGenericTypeDefinition().GetGenericArguments(); - Type[] types = genericType.GetGenericArguments(); - for (int i = 0; i < genericArguments.Length; i++) - { - string genericName = genericArguments[i].Name; - nameToType[genericName] = types[i]; - } - return nameToType; - } - - private static Type GetTypeWithGenericArgumentsForMethodParameters(IInvocation invocation) - { - Type genericType = invocation.GetType(); - if (genericType.IsGenericType) //generic method - return genericType; - //Generic class: - - Type type = MockRepository.GetMockedObject(invocation.Proxy).GetDeclaringType(invocation.Method); - if (type == null) - throw new InvalidOperationException("BUG: Could not find a declaring type for method " + invocation.Method); - return type; - } - - - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections.Generic; +using Castle.Core.Interceptor; + +namespace Rhino.Mocks.Utilities +{ + /// + /// Utility class for dealing with messing generics scenarios. + /// + public static class GenericsUtil + { + /// + /// 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. + /// + public static bool HasOpenGenericParam(Type returnType) + { + //not bound to particular type, only way I know of doing this, since IsGeneric and IsGenericTypeDefination will both lie + //when used with generic method parameters + if (returnType.FullName == null) + return true; + foreach (Type genericArgument in returnType.GetGenericArguments()) + { + if (genericArgument.FullName == null) + return true; + if (genericArgument.IsGenericType) + { + if (HasOpenGenericParam(genericArgument)) + return true; + } + } + return false; + } + + /// + /// Gets the real type, including de-constructing and constructing the type of generic + /// methods parameters. + /// + /// The type. + /// The invocation. + /// + public static Type GetRealType(Type type, IInvocation invocation) + { + if (!HasOpenGenericParam(type)) + return type; + Dictionary nameToType = CreateTypesTableFromInvocation(invocation); + string typeName = type.AssemblyQualifiedName ?? type.Name; // if the AssemblyQualifiedName is null, we have an open type + if (nameToType.ContainsKey(typeName)) + return nameToType[typeName]; + Type[] types = new List(nameToType.Values).ToArray(); + return ReconstructGenericType(type, nameToType); + } + + /// + /// 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]] + /// + private static Type ReconstructGenericType(Type type, Dictionary nameToType) + { + Type genericTypeDef = type.GetGenericTypeDefinition(); + List genericArgs = new List(); + foreach (Type genericArgument in type.GetGenericArguments()) + { + if(nameToType.ContainsKey(genericArgument.Name)) + { + genericArgs.Add(nameToType[genericArgument.Name]); + } + else + { + genericArgs.Add( ReconstructGenericType(genericArgument, nameToType)); + } + } + return genericTypeDef.MakeGenericType(genericArgs.ToArray()); + } + + private static Dictionary CreateTypesTableFromInvocation(IInvocation invocation) + { + Dictionary nameToType = new Dictionary(); + Type genericType = GetTypeWithGenericArgumentsForMethodParameters(invocation); + Type[] genericArguments = genericType.GetGenericTypeDefinition().GetGenericArguments(); + Type[] types = genericType.GetGenericArguments(); + for (int i = 0; i < genericArguments.Length; i++) + { + string genericName = genericArguments[i].Name; + nameToType[genericName] = types[i]; + } + return nameToType; + } + + private static Type GetTypeWithGenericArgumentsForMethodParameters(IInvocation invocation) + { + Type genericType = invocation.GetType(); + if (genericType.IsGenericType) //generic method + return genericType; + //Generic class: + + Type type = MockRepository.GetMockedObject(invocation.Proxy).GetDeclaringType(invocation.Method); + if (type == null) + throw new InvalidOperationException("BUG: Could not find a declaring type for method " + invocation.Method); + return type; + } + + + } } \ No newline at end of file diff --git a/Rhino.Mocks/Utilities/MethodCallUtil.cs b/Rhino.Mocks/Utilities/MethodCallUtil.cs index 61471dc1..b5d5b76f 100644 --- a/Rhino.Mocks/Utilities/MethodCallUtil.cs +++ b/Rhino.Mocks/Utilities/MethodCallUtil.cs @@ -1,144 +1,144 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Reflection; -using System.Text; -using Castle.Core.Interceptor; -using Rhino.Mocks.Impl; -using Rhino.Mocks.Interfaces; - -namespace Rhino.Mocks.Utilities -{ - /// - /// Utility class for working with method calls. - /// - public static class MethodCallUtil - { - /// - /// Delegate to format the argument for the string representation of - /// the method call. - /// - public delegate string FormatArgumnet(Array args, int i); - - /// - /// 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 - public static string StringPresentation(IInvocation invocation, FormatArgumnet format, MethodInfo method, object[] args) - { - Validate.IsNotNull(format, "format"); - Validate.IsNotNull(method, "method"); - Validate.IsNotNull(args, "args"); - StringBuilder sb = new StringBuilder(); - sb.Append(method.DeclaringType.Name).Append(".").Append(method.Name); - if (invocation != null) - { - if (method.IsGenericMethod) - { - sb.Append("<"); - foreach (Type genericArgument in invocation.GenericArguments) - { - sb.Append(genericArgument); - sb.Append(", "); - } - sb.Remove(sb.Length - 2, 2); //remove last ", " - sb.Append(">"); - } - } - sb.Append("("); - int numberOfParameters = method.GetParameters().Length; - for (int i = 0; i < numberOfParameters; i++) - { - sb.Append(format(args, i)); - if (i < numberOfParameters - 1) - sb.Append(", "); - } - sb.Append(");"); - return sb.ToString(); - } - - /// - /// 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 - public static string StringPresentation(IInvocation invocation, MethodInfo method, object[] args) - { - return StringPresentation(invocation, new FormatArgumnet(DefaultFormatArgument), method, args); - } - - #region Private Methods - - private static string DefaultFormatArgument(Array args, int i) - { - if (args.Length <= i) - return "missing parameter"; - object arg = args.GetValue(i); - if (arg is Array) - { - Array arr = (Array) arg; - StringBuilder sb = new StringBuilder(); - sb.Append('['); - for (int j = 0; j < arr.Length; j++) - { - sb.Append(DefaultFormatArgument(arr, j)); - if (j < arr.Length - 1) - sb.Append(", "); - } - sb.Append("]"); - return sb.ToString(); - } - if (arg is string) - return "\"" + arg.ToString() + "\""; - else if (arg == null) - return "null"; - else - return MockingSafeToString(arg); - } - - // we need to ensure that we won't re-eenterant into the repository - // if the parameter is a mock object - private static string MockingSafeToString(object arg) - { - IMockedObject mock = arg as IMockedObject; - if(mock==null) - return arg.ToString(); - return mock.GetType().BaseType.FullName; - } - - #endregion - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Reflection; +using System.Text; +using Castle.Core.Interceptor; +using Rhino.Mocks.Impl; +using Rhino.Mocks.Interfaces; + +namespace Rhino.Mocks.Utilities +{ + /// + /// Utility class for working with method calls. + /// + public static class MethodCallUtil + { + /// + /// Delegate to format the argument for the string representation of + /// the method call. + /// + public delegate string FormatArgumnet(Array args, int i); + + /// + /// 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 + public static string StringPresentation(IInvocation invocation, FormatArgumnet format, MethodInfo method, object[] args) + { + Validate.IsNotNull(format, "format"); + Validate.IsNotNull(method, "method"); + Validate.IsNotNull(args, "args"); + StringBuilder sb = new StringBuilder(); + sb.Append(method.DeclaringType.Name).Append(".").Append(method.Name); + if (invocation != null) + { + if (method.IsGenericMethod) + { + sb.Append("<"); + foreach (Type genericArgument in invocation.GenericArguments) + { + sb.Append(genericArgument); + sb.Append(", "); + } + sb.Remove(sb.Length - 2, 2); //remove last ", " + sb.Append(">"); + } + } + sb.Append("("); + int numberOfParameters = method.GetParameters().Length; + for (int i = 0; i < numberOfParameters; i++) + { + sb.Append(format(args, i)); + if (i < numberOfParameters - 1) + sb.Append(", "); + } + sb.Append(");"); + return sb.ToString(); + } + + /// + /// 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 + public static string StringPresentation(IInvocation invocation, MethodInfo method, object[] args) + { + return StringPresentation(invocation, new FormatArgumnet(DefaultFormatArgument), method, args); + } + + #region Private Methods + + private static string DefaultFormatArgument(Array args, int i) + { + if (args.Length <= i) + return "missing parameter"; + object arg = args.GetValue(i); + if (arg is Array) + { + Array arr = (Array) arg; + StringBuilder sb = new StringBuilder(); + sb.Append('['); + for (int j = 0; j < arr.Length; j++) + { + sb.Append(DefaultFormatArgument(arr, j)); + if (j < arr.Length - 1) + sb.Append(", "); + } + sb.Append("]"); + return sb.ToString(); + } + if (arg is string) + return "\"" + arg.ToString() + "\""; + else if (arg == null) + return "null"; + else + return MockingSafeToString(arg); + } + + // we need to ensure that we won't re-eenterant into the repository + // if the parameter is a mock object + private static string MockingSafeToString(object arg) + { + IMockedObject mock = arg as IMockedObject; + if(mock==null) + return arg.ToString(); + return mock.GetType().BaseType.FullName; + } + + #endregion + } } \ No newline at end of file diff --git a/Rhino.Mocks/Utilities/ReturnValueUtil.cs b/Rhino.Mocks/Utilities/ReturnValueUtil.cs index 740881a2..327158d7 100644 --- a/Rhino.Mocks/Utilities/ReturnValueUtil.cs +++ b/Rhino.Mocks/Utilities/ReturnValueUtil.cs @@ -1,59 +1,59 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using Castle.Core.Interceptor; - -namespace Rhino.Mocks.Utilities -{ - /// - /// Utility to get the default value for a type - /// - public class ReturnValueUtil - { - /// - /// 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 - public static object DefaultValue(Type type, IInvocation invocation) - { - type = GenericsUtil.GetRealType(type, invocation); - if (type.IsValueType == false || type==typeof(void)) - return null; - return Activator.CreateInstance(type); - } - } +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using Castle.Core.Interceptor; + +namespace Rhino.Mocks.Utilities +{ + /// + /// Utility to get the default value for a type + /// + public class ReturnValueUtil + { + /// + /// 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 + public static object DefaultValue(Type type, IInvocation invocation) + { + type = GenericsUtil.GetRealType(type, invocation); + if (type.IsValueType == false || type==typeof(void)) + return null; + return Activator.CreateInstance(type); + } + } } \ No newline at end of file diff --git a/Rhino.Mocks/With.cs b/Rhino.Mocks/With.cs index 8774b002..1fe3ef33 100644 --- a/Rhino.Mocks/With.cs +++ b/Rhino.Mocks/With.cs @@ -1,150 +1,150 @@ -#region license -// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// * Neither the name of Ayende Rahien nor the names of its -// contributors may be used to endorse or promote products derived from this -// software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#endregion - - -using System; -using System.Collections.Generic; -using System.Text; - -namespace Rhino.Mocks -{ - /// - /// 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. - /// - public static class With - { - /// - /// A method with no arguments and no return value that will be called under the mock context. - /// - public delegate void Proc(); - - /// - /// 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 - public static void Mocks(Proc methodCallThatHasMocks) - { - MockRepository mocks = new MockRepository(); - Mocks(mocks, methodCallThatHasMocks); - } - - /// - /// 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 - public static void Mocks(MockRepository mocks, Proc methodCallThatHasMocks) - { - Mocker.Current = mocks; - try - { - methodCallThatHasMocks(); - mocks.VerifyAll(); - } - finally - { - Mocker.Current = null; - } - } - - /// - /// Create a FluentMocker - /// - /// The mock repository to use. - public static FluentMocker Mocks(MockRepository mocks) - { - return new FluentMocker(mocks); - } - - /// - /// FluentMocker implements some kind of fluent interface attempt - /// for saying "With the Mocks [mocks], Expecting (in same order) [things] verify [that]." - /// - public class FluentMocker: IMockVerifier - { - private MockRepository _mocks; - - internal FluentMocker(MockRepository mocks) - { - _mocks = mocks; - } - - /// - /// Defines unordered expectations - /// - /// A delegate describing the expectations - /// an IMockVerifier - public IMockVerifier Expecting(Proc methodCallsDescribingExpectations) - { - methodCallsDescribingExpectations(); - _mocks.ReplayAll(); - return this; - } - /// - /// Defines ordered expectations - /// - /// A delegate describing the expectations - /// an IMockVerifier - public IMockVerifier ExpectingInSameOrder(Proc methodCallsDescribingExpectations) - { - using (_mocks.Ordered()) - { - methodCallsDescribingExpectations(); - } - _mocks.ReplayAll(); - return this; - } - - /// - /// Verifies previously defined expectations - /// - public void Verify(Proc methodCallsToBeVerified) - { - methodCallsToBeVerified(); - _mocks.VerifyAll(); - } - } - - /// - /// Interface to verify previously defined expectations - /// - public interface IMockVerifier - { - /// - /// Verifies if a piece of code - /// - void Verify(Proc methodCallsToBeVerified); - } - } -} +#region license +// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of Ayende Rahien nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#endregion + + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Rhino.Mocks +{ + /// + /// 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. + /// + public static class With + { + /// + /// A method with no arguments and no return value that will be called under the mock context. + /// + public delegate void Proc(); + + /// + /// 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 + public static void Mocks(Proc methodCallThatHasMocks) + { + MockRepository mocks = new MockRepository(); + Mocks(mocks, methodCallThatHasMocks); + } + + /// + /// 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 + public static void Mocks(MockRepository mocks, Proc methodCallThatHasMocks) + { + Mocker.Current = mocks; + try + { + methodCallThatHasMocks(); + mocks.VerifyAll(); + } + finally + { + Mocker.Current = null; + } + } + + /// + /// Create a FluentMocker + /// + /// The mock repository to use. + public static FluentMocker Mocks(MockRepository mocks) + { + return new FluentMocker(mocks); + } + + /// + /// FluentMocker implements some kind of fluent interface attempt + /// for saying "With the Mocks [mocks], Expecting (in same order) [things] verify [that]." + /// + public class FluentMocker: IMockVerifier + { + private MockRepository _mocks; + + internal FluentMocker(MockRepository mocks) + { + _mocks = mocks; + } + + /// + /// Defines unordered expectations + /// + /// A delegate describing the expectations + /// an IMockVerifier + public IMockVerifier Expecting(Proc methodCallsDescribingExpectations) + { + methodCallsDescribingExpectations(); + _mocks.ReplayAll(); + return this; + } + /// + /// Defines ordered expectations + /// + /// A delegate describing the expectations + /// an IMockVerifier + public IMockVerifier ExpectingInSameOrder(Proc methodCallsDescribingExpectations) + { + using (_mocks.Ordered()) + { + methodCallsDescribingExpectations(); + } + _mocks.ReplayAll(); + return this; + } + + /// + /// Verifies previously defined expectations + /// + public void Verify(Proc methodCallsToBeVerified) + { + methodCallsToBeVerified(); + _mocks.VerifyAll(); + } + } + + /// + /// Interface to verify previously defined expectations + /// + public interface IMockVerifier + { + /// + /// Verifies if a piece of code + /// + void Verify(Proc methodCallsToBeVerified); + } + } +} diff --git a/Rhino.Mocks/__ProtectAttribute.cs b/Rhino.Mocks/__ProtectAttribute.cs index 41938de7..0b7e84b1 100644 --- a/Rhino.Mocks/__ProtectAttribute.cs +++ b/Rhino.Mocks/__ProtectAttribute.cs @@ -1,13 +1,13 @@ -using System; - -/// -/// 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 -/// -[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] -[CLSCompliant(false)] -public class __ProtectAttribute : Attribute -{ - +using System; + +/// +/// 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 +/// +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +[CLSCompliant(false)] +public class __ProtectAttribute : Attribute +{ + } \ No newline at end of file diff --git a/SharedLibs/Microsoft.Practices.ObjectBuilder2.xml b/SharedLibs/Microsoft.Practices.ObjectBuilder2.xml index 3c2d56f7..6218caa3 100644 --- a/SharedLibs/Microsoft.Practices.ObjectBuilder2.xml +++ b/SharedLibs/Microsoft.Practices.ObjectBuilder2.xml @@ -1,3182 +1,3182 @@ - - - - Microsoft.Practices.ObjectBuilder2 - - - - - An implementation of . It contains all the default strategies shipped - with ObjectBuilder. - - - - - Represents the main interface for an object builder. - - - - - Performs a build operation. - - - This operation uses the strategies and permanent policies already configured - into the builder, combined with the optional transient policies, and starts a build - operation. Transient policies override any built-in policies, when present. - - The locator to be used for this build operation. - The to use for this build operation. - - The transient policies to apply to this build. These - policies take precedence over any permanent policies built into the builder. - - - The to use for this build operation. - - The key of the object to build. - - The existing object to run the build chain on, if one exists. - If null is passed, a new object instance will typically be created by some strategy - in the chain. - - The built object. - - - - Performs a build operation. - - - This operation uses the strategies and permanent policies already configured - into the builder, combined with the optional transient policies, and starts a build - operation. Transient policies override any built-in policies, when present. - - The type to build. - The locator to be used for this build operation. - The to use for this build operation. - - The transient policies to apply to this build. These - policies take precedence over any permanent policies built into the builder. - - - The to use for this build operation. - - The key of the object to build. - - The existing object to run the build chain on, if one exists. - If null is passed, a new object instance will typically be created by some strategy - in the chain. - - The built object. - - - - Performs an unbuild operation. - - The type to unbuild. If not provided, it will be inferred from the - type of item. - - The locator to be used for this build operation. - The to use for this build operation. - - The transient policies to apply to this build. These - policies take precedence over any permanent policies built into the builder. - - - The to use for this build operation. - - The item to tear down. - The torn down item. - - - - Performs a build operation. - - - This operation uses the strategies and permanent policies already configured - into the builder, combined with the optional transient policies, and starts a build - operation. Transient policies override any built-in policies, when present. - - The locator to be used for this build operation. - The to use for this build operation. - - The transient policies to apply to this build. These - policies take precedence over any permanent policies built into the builder. - - - The to use for this build operation. - - The key of the object to build. - - The existing object to run the build chain on, if one exists. - If null is passed, a new object instance will typically be created by some strategy - in the chain. - - The built object. - - - - Performs a build operation. - - - This operation uses the strategies and permanent policies already configured - into the builder, combined with the optional transient policies, and starts a build - operation. Transient policies override any built-in policies, when present. - - The type to build. - The locator to be used for this build operation. - The to use for this build operation. - - The transient policies to apply to this build. These - policies take precedence over any permanent policies built into the builder. - - - The to use for this build operation. - - The key of the object to build. - - The existing object to run the build chain on, if one exists. - If null is passed, a new object instance will typically be created by some strategy - in the chain. - - The built object. - - - - Performs an unbuild operation. - - The type to unbuild. If not provided, it will be inferred from the - type of item. - - The locator to be used for this build operation. - The to use for this build operation. - - The transient policies to apply to this build. These - policies take precedence over any permanent policies built into the builder. - - - The to use for this build operation. - - The item to tear down. - The torn down item. - - - - Represents the context in which a build-up or tear-down operation runs. - - - - - Represents the context in which a build-up or tear-down operation runs. - - - - - Create a new IBuilderContext which has the same strategies, locator, policies, and lifetime - but a new build key and existing object. Used to execute recursive calls when - building up dependencies. - - Build key for new buildup. - New exsting object for buildup. - The new context. - - - - Gets the head of the strategy chain. - - - The strategy that's first in the chain; returns null if there are no - strategies in the chain. - - - - - Gets the associated with the build. - - - The associated with the build. - - - - - Gets the locator available to the strategies. - - - The locator available to the strategies. - - - - - Gets the original build key for the build operation. - - - The original build key for the build operation. - - - - - The set of policies that were passed into this context. - - This returns the policies passed into the context. - Policies added here will remain after buildup completes. - The persistent policies for the current context. - - - - Gets the policies for the current context. - - Any policies added to this object are transient - and will be erased at the end of the buildup. - - The policies for the current context. - - - - - Gets the collection of objects - that need to execute in event of an exception. - - - - - Get the current build key for the current build operation. - - - - - The current object being built up or torn down. - - - The current object being manipulated by the build operation. May - be null if the object hasn't been created yet. - - - - Flag indicating if the build operation should continue. - - true means that building should not call any more - strategies, false means continue to the next strategy. - - - - Initialize a new instance of the class. - - - - - Initialize a new instance of the class with a , - , , and the - build key used to start this build operation. - - The to use for this context. - The to use for this context. - The to use for this context. - The to use for this context. - Build key to start building. - The existing object to build up. - - - - Create a new using the explicitly provided - values. - - The to use for this context. - The to use for this context. - The to use for this context. - The set of persistent policies to use for this context. - The set of transient policies to use for this context. It is - the caller's responsibility to ensure that the transient and persistent policies are properly - combined. - Build key for this context. - Existing object to build up. - - - - Create a new IBuilderContext which has the same strategies, locator, policies, and lifetime - but a new build key and existing object. Used to execute recursive calls when - building up dependencies. - - Build key for new buildup. - New exsting object for buildup. - The new context. - - - - A convenience method to do a new buildup operation on an existing context. - - This helper is specific to NamedTypeBuildKey. - Type to return from the buildup. - Existing context. - The built up object. - - - - Gets the head of the strategy chain. - - - The strategy that's first in the chain; returns null if there are no - strategies in the chain. - - - - - Get the current build key for the current build operation. - - - - - The current object being built up or torn down. - - - The current object being manipulated by the build operation. May - be null if the object hasn't been created yet. - - - - Gets the associated with the build. - - - The associated with the build. - - - - - Gets the locator available to the strategies. - - - The locator available to the strategies. - - - - - Gets the original build key for the build operation. - - - The original build key for the build operation. - - - - - The set of policies that were passed into this context. - - This returns the policies passed into the context. - Policies added here will remain after buildup completes. - The persistent policies for the current context. - - - - Gets the policies for the current context. - - - Any modifications will be transient (meaning, they will be forgotten when - the outer BuildUp for this context is finished executing). - - - The policies for the current context. - - - - - Gets the collection of objects - that need to execute in event of an exception. - - - - - Flag indicating if the build operation should continue. - - true means that building should not call any more - strategies, false means continue to the next strategy. - - - - The exception that gets thrown if a build or teardown operation fails. - - - - - Create a new instance containing - the information about the currently executing strategy that caused - the exception. - - The that was - executing at the time the exception was thrown. - The index of the current strategy in its - strategy chain. - The build key being built up. - Underlying exception. - - - - Create a new . Do not use this constructor, it - does not take any of the data that makes this type useful. - - - - - Create a new . Do not use this constructor, it - does not take any of the data that makes this type useful. - - Error message, ignored. - - - - Create a new . Do not use this constructor, it - does not take any of the data that makes this type useful. - - Error message, ignored. - Inner exception. - - - - Create a new from the serialized information. - - Serialization info. - Streaming context. - - - - When overridden in a derived class, sets the with information about the exception. - - - The that contains contextual information about the source or destination. - The that holds the serialized object data about the exception being thrown. - The info parameter is a null reference (Nothing in Visual Basic). 2 - - - - The strategy that was executing when the exception occurred. - - - - - The index of the currently executing strategy in the build chain. - - - - - The build key that was being built at the time of the exception. - - - - - Gets a message that describes the current exception. - - - - The error message that explains the reason for the exception, or an empty string(""). - - 1 - - - - Represents that a dependency could not be resolved. - - - Represents that a dependency could not be resolved. - - - - - Initializes a new instance of the class with no extra information. - - - - - Initializes a new instance of the class with the given message. - - Some random message. - - - - Initialize a new instance of the class with the given - message and inner exception. - - Some random message - Inner exception. - - - - Initializes a new instance of the class with the build key of the object begin built. - - The build key of the object begin built. - - - - Initializes a new instance of the class with serialized data. - - The that holds the serialized object data about the exception being thrown. - The that contains contextual information about the source or destination. - - - - Data structure that stores the set of - objects and executes them when requested. - - - - - Add a new object to this - list. - - Object to add. - - - - Execute the method - of everything in the recovery list. Recoveries will execute - in the opposite order of add - it's a stack. - - - - - Return the number of recovery objects currently in the stack. - - - - - This interface provides a hook for the builder context to - implement error recovery when a builder strategy throws - an exception. Since we can't get try/finally blocks onto - the call stack for later stages in the chain, we instead - add these objects to the context. If there's an exception, - all the current IRequiresRecovery instances will have - their Recover methods called. - - - - - A method that does whatever is needed to clean up - as part of cleaning up after an exception. - - - Don't do anything that could throw in this method, - it will cause later recover operations to get skipped - and play real havok with the stack trace. - - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to The type {0} has multiple constructors of length {1}. Unable to disambiguate.. - - - - - Looks up a localized string similar to The current build operation (build key {2}) failed: {3} (Strategy type {0}, index {1}). - - - - - Looks up a localized string similar to The current type, {0}, is an interface and cannot be constructed. Are you missing a type mapping?. - - - - - Looks up a localized string similar to Cannot extract type from build key {0}.. - - - - - Looks up a localized string similar to The method {1} on type {0} has an out parameter. Injection cannot be performed.. - - - - - Looks up a localized string similar to The method {1} on type {0} is marked for injection, but it is an open generic method. Injection cannot be performed.. - - - - - Looks up a localized string similar to The parameter {0} could not be resolved when attempting to call constructor {1}.. - - - - - Looks up a localized string similar to An item with the given key is already present in the dictionary.. - - - - - Looks up a localized string similar to The value for parameter "{1}" of method {0} could not be resolved. . - - - - - Looks up a localized string similar to Could not resolve dependency for build key {0}.. - - - - - Looks up a localized string similar to The type {0} has multiple constructors marked with the InjectionConstructor attribute. Unable to disambiguate.. - - - - - Looks up a localized string similar to The supplied type {0} must be an open generic type.. - - - - - Looks up a localized string similar to The supplied type {0} does not have the same number of generic arguments as the target type {1}.. - - - - - Looks up a localized string similar to The type {0} does not have an accessible constructor.. - - - - - Looks up a localized string similar to The value for the property "{0}" could not be resolved.. - - - - - Looks up a localized string similar to The provided string argument must not be empty.. - - - - - An implementation of . - - - - - Add a new object to this - list. - - Object to add. - - - - Execute the method - of everything in the recovery list. Recoveries will execute - in the opposite order of add - it's a stack. - - - - - Return the number of recovery objects currently in the stack. - - - - - Implementation of which will notify an object about - the completion of a operation, or start of a - operation. - - - This strategy checks the object that is passing through the builder chain to see if it - implements IBuilderAware and if it does, it will call - and . This strategy is meant to be used from the - stage. - - - - - Represents a strategy in the 's chain of responsibility. - Strategies are required to support both BuildUp and TearDown. - - - - - Represents a strategy in the 's chain of responsibility. - Strategies are required to support both BuildUp and TearDown. Although you - can implement this interface directly, you may also choose to use - as the base class for your strategies, as - this class provides useful helper methods and makes support BuildUp and TearDown - optional. - - - - - Called during the chain of responsibility for a build operation. The - PreBuildUp method is called when the chain is being executed in the - forward direction. - - Context of the build operation. - - - - Called during the chain of responsibility for a build operation. The - PostBuildUp method is called when the chain has finished the PreBuildUp - phase and executes in reverse order from the PreBuildUp calls. - - Context of the build operation. - - - - Called during the chain of responsibility for a teardown operation. The - PreTearDown method is called when the chain is being executed in the - forward direction. - - Context of the teardown operation. - - - - Called during the chain of responsibility for a teardown operation. The - PostTearDown method is called when the chain has finished the PreTearDown - phase and executes in reverse order from the PreTearDown calls. - - - - - - Called during the chain of responsibility for a build operation. The - PreBuildUp method is called when the chain is being executed in the - forward direction. - - Context of the build operation. - - - - Called during the chain of responsibility for a build operation. The - PostBuildUp method is called when the chain has finished the PreBuildUp - phase and executes in reverse order from the PreBuildUp calls. - - Context of the build operation. - - - - Called during the chain of responsibility for a teardown operation. The - PreTearDown method is called when the chain is being executed in the - forward direction. - - Context of the teardown operation. - - - - Called during the chain of responsibility for a teardown operation. The - PostTearDown method is called when the chain has finished the PreTearDown - phase and executes in reverse order from the PreTearDown calls. - - - - - - Called during the chain of responsibility for a build operation. The - PreBuildUp method is called when the chain is being executed in the - forward direction. - - Context of the build operation. - - - - Called during the chain of responsibility for a teardown operation. The - PreTearDown method is called when the chain is being executed in the - forward direction. - - Context of the teardown operation. - - - - Implemented on a class when it wants to receive notifications - about the build process. - - - - - Called by the when the object is being built up. - - The key of the object that was just built up. - - - - Called by the when the object is being torn down. - - - - - Enumeration to represent the object builder stages. - - - The order of the values in the enumeration is the order in which the stages are run. - - - - - Strategies in this stage run before creation. Typical work done in this stage might - include strategies that use reflection to set policies into the context that other - strategies would later use. - - - - - Strategies in this stage create objects. Typically you will only have a single policy-driven - creation strategy in this stage. - - - - - Strategies in this stage work on created objects. Typical work done in this stage might - include setter injection and method calls. - - - - - Strategies in this stage work on objects that are already initialized. Typical work done in - this stage might include looking to see if the object implements some notification interface - to discover when its initialization stage has been completed. - - - - - Represents a builder policy interface. Since there are no fixed requirements - for policies, it acts as a marker interface from which to derive all other - policy interfaces. - - - - - Represents a builder policy for mapping build keys. - - - - - Represents a builder policy for mapping build keys. - - - - - Maps the build key. - - The build key to map. - The new build key. - - - - Initialize a new instance of the with the new build key. - - - - - - Map the to a new build key. - - The build key to mapl - The new build key. - - - - Represents a strategy for mapping build keys in the build up operation. - - - - - Called during the chain of responsibility for a build operation. Looks for the - and if found maps the build key for the current operation. - - The context for the operation. - - - - An implementation of that can map - generic types. - - - - - Create a new instance - that will map generic types. - - Build key to map to. This must be or contain an open generic type. - - - - Maps the build key. - - The build key to map. - The new build key. - - - - A that will look for a build plan - in the current context. If it exists, it invokes it, otherwise - it creates one and stores it for later, and invokes it. - - - - - Called during the chain of responsibility for a build operation. - - The context for the operation. - - - - An implementation of that chooses - constructors based on these criteria: first, pick a constructor marked with the - attribute. If there - isn't one, then choose the constructor with the longest parameter list. If that is ambiguous, - then throw. - - Thrown when the constructor to choose is ambiguous. - Attribute used to mark the constructor to call. - - - - Base class that provides an implementation of - which lets you override how the parameter resolvers are created. - - - - - A that, when implemented, - will determine which constructor to call from the build plan. - - - - - Choose the constructor to call for the given type. - - Current build context - The chosen constructor. - - - - Choose the constructor to call for the given type. - - Current build context. - The chosen constructor. - Thrown when the constructor to choose is ambiguous. - - - - Create a instance for the given - . - - Parameter to create the resolver for. - The resolver object. - - - - Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. - - - - Value Condition Less than zerox is less than y.Zerox equals y.Greater than zerox is greater than y. - - - The second object to compare. - The first object to compare. - - - - Create a instance for the given - . - - Parameter to create the resolver for. - The resolver object. - - - - Objects of this type are the return value from . - It encapsulates the desired with the string keys - needed to look up the for each - parameter. - - - - - Base class for return values from selector policies that - return a memberinfo of some sort plus a list of parameter - keys to look up the parameter resolvers. - - - - - Base class for return of selector policies that need - to keep track of a set of parameter keys. - - - - - Add a new parameter key to this object. Keys are assumed - to be in the order of the parameters to the constructor. - - Key for the next parameter to look up. - - - - The set of keys for the constructor parameters. - - - - - Construct a new , storing - the given member info. - - Member info to store. - - - - The member info stored. - - - - - Create a new instance which - contains the given constructor. - - - - - - The constructor this object wraps. - - - - - A that emits IL to call constructors - as part of creating a build plan. - - - - - Called during the chain of responsibility for a build operation. - - Existing object is an instance of . - The context for the operation. - - - - A helper method used by the generated IL to throw an exception if - a dependency cannot be resolved. - - The currently being - used for the build of this object. - - - - A helper method used by the generated IL to throw an exception if a parameter - fails to resolve. - - Inner exception to throw. - Name of the parameter that was attempted to be resolved. - String describing which constructor we were calling. - Current build context. - - - - A helper method used by the generated IL to throw an exception if - no existing object is present, but the user is attempting to build - an interface (usually due to the lack of a type mapping). - - - - - - An implementation of that will - check for full trust and if we're building a class or an interface. If in full - trust, attach to the class or module of the interface respectively. If in partial - trust, attach to the OB2 module instead. - - - - - This interface defines a policy that manages creation of the dynamic methods - used by the ObjectBuilder code generation. This way, we can replace the details - of how the dynamic method is created to handle differences in CLR (like Silverlight - vs desktop) or security policies. - - - - - Create a builder method for the given type, using the given name. - - Type that will be built by the generated method. - Name to give to the method. - A object with the proper signature to use - as part of a build plan. - - - - Create a builder method for the given type, using the given name. - - Type that will be built by the generated method. - Name to give to the method. - A object with the proper signature to use - as part of a build plan. - - - - This object tracks the current state of the build plan generation, - accumulates the IL, provides the preamble & postamble for the dynamic - method, and tracks things like local variables in the generated IL - so that they can be reused across IL generation strategies. - - - - - Create a that is initialized - to handle creation of a dynamic method to build the given type. - - Type that we're trying to create a build plan for. - An object that actually - creates our object. - - - - Completes generation of the dynamic method and returns the - generated dynamic method delegate. - - The created - - - - Emit the IL to put the build context on top of the IL stack. - - - - - Emit the IL to put the current build key on top of the IL stack. - - - - - Emit the IL to put the current "existing" object on the top of the IL stack. - - - - - Emit the IL to make the top of the IL stack our current "existing" object. - - - - - Emit the IL to load the given object onto the top of the IL stack. - - Type to load on the stack. - - - - Emit the IL needed to look up an and - call it to get a value. - - Type of the dependency to resolve. - Key to look up the policy by. - - - - A reflection helper method to make it easier to grab a property getter - for the given property. - - Type that implements the property we want. - Type of the property. - Name of the property. - The property getter's . - - - - A reflection helper method that makes it easier to grab a - for a method. - - Type that implements the method we want. - Name of the method. - Types of arguments to the method. - The method's . - - - - The underlying that can be used to - emit IL into the generated dynamic method. - - - - - The type we're currently creating the method to build. - - - - - A delegate type that defines the signature of the - dynamic method created by the build plans. - - used to build up the object. - - - - An implementation of that runs the - given delegate to execute the plan. - - - - - A build plan is an object that, when invoked, will create a new object - or fill in a given existing one. It encapsulates all the information - gathered by the strategies to construct a particular object. - - - - - Creates an instance of this build plan's type, or fills - in the existing type if passed in. - - Context used to build up the object. - - - - An implementation - that constructs a build plan via dynamic IL emission. - - - - - A that can create and return an - for the given build key. - - - - - Create a build plan using the given context and build key. - - Current build context. - Current build key. - The build plan. - - - - Construct a that - uses the given strategy chain to construct the build plan. - - - - - - Construct a build plan. - - The current build context. - The current build key. - The created build plan. - - - - A that generates IL to call - chosen methods (as specified by the current ) - as part of object build up. - - - - - Called during the chain of responsibility for a build operation. The - PreBuildUp method is called when the chain is being executed in the - forward direction. - - Context of the build operation. - - - - A helper method used by the generated IL to throw an exception - when an injection method parameter could not be resolved. - - Exception that provides the failure info. - Name of the method that was going to be called. - Parameter that failed to resolve. - - - - A that generates IL to resolve properties - on an object being built. - - - - - Called during the chain of responsibility for a build operation. - - The context for the operation. - - - - A helper method called by the generated IL to throw an exception if a property's - value cannot be resolved. - - The actual exception that caused the resolution to fail. - Name of the property that didn't resolve. - - - - An that will examine the given - types and return a sequence of objects - that should be called as part of building the object. - - - - - Return the sequence of methods to call while building the target object. - - Current build context. - Sequence of methods to call. - - - - An implementation of that selects - methods by looking for the given - attribute on those methods. - - Type of attribute used to mark methods - to inject. - - - - Base class that provides an implementation of - which lets you override how the parameter resolvers are created. - - Attribute that marks methods that should - be called. - - - - Return the sequence of methods to call while building the target object. - - Current build context. - Sequence of methods to call. - - - - Create a instance for the given - . - - Parameter to create the resolver for. - The resolver object. - - - - Create a instance for the given - . - - Parameter to create the resolver for. - The resolver object. - - - - Objects of this type are the return value from . - It encapsulates the desired with the string keys - needed to look up the for each - parameter. - - - - - Create a new instance which - contains the given method. - - The method - - - - The constructor this object wraps. - - - - - An that returns a sequence - of properties that should be injected for the given type. - - - - - Returns sequence of properties on the given type that - should be set as part of building that object. - - Current build context. - Sequence of objects - that contain the properties to set. - - - - Base class that provides an implementation of - which lets you override how the parameter resolvers are created. - - - - - Returns sequence of properties on the given type that - should be set as part of building that object. - - current build context. - Sequence of objects - that contain the properties to set. - - - - Create a for the given - property. - - Property to create resolver for. - The resolver object. - - - - An implementation of that looks - for properties marked with the - attribute that are also settable and not indexers. - - - - - - Create a for the given - property. - - Property to create resolver for. - The resolver object. - - - - Objects of this type are returned from - . - This class combines the about - the property with the string key used to look up the resolver - for this property's value. - - - - - Create an instance of - with the given and key. - - The property. - Key to use to look up the resolver. - - - - PropertyInfo for this property. - - - - - Key to look up this property's resolver. - - - - - Implementation of . - - - - - A builder policy that lets you keep track of the current - resolvers and will remove them from the given policy set. - - - - - Add a new resolver to track by key. - - Key that was used to add the resolver to the policy set. - - - - Remove the currently tracked resolvers from the given policy list. - - Policy list to remove the resolvers from. - - - - Add a new resolver to track by key. - - Key that was used to add the resolver to the policy set. - - - - Remove the currently tracked resolvers from the given policy list. - - Policy list to remove the resolvers from. - - - - Get an instance that implements , - either the current one in the policy set or creating a new one if it doesn't - exist. - - Policy list to look up from. - Build key to track. - The resolver tracker. - - - - Add a key to be tracked to the current tracker. - - Policy list containing the resolvers and trackers. - Build key for the resolvers being tracked. - Key for the resolver. - - - - Remove the resolvers for the given build key. - - Policy list containing the build key. - Build key. - - - - An implementation of that - calls back into the build chain to build up the dependency, passing - a type given at compile time as its build key. - - - - - A that is used at build plan execution time - to resolve a dependent value. - - - - - Get the value for a dependency. - - Current build context. - The value for the dependency. - - - - Create a new instance storing the given type. - - Type to resolve. - - - - Get the value for a dependency. - - Current build context. - The value for the dependency. - - - - A custom collection over objects. - - - - - Removes an individual policy type for a build key. - - The type the policy was registered as. - The key the policy applies. - - - - Removes an individual policy type for a build key. - - The type of policy to remove. - The key the policy applies. - - - - Removes all policies from the list. - - - - - Removes a default policy. - - The type the policy was registered as. - - - - Removes a default policy. - - The type the policy was registered as. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - The policy in the list, if present; returns null otherwise. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - The policy in the list, if present; returns null otherwise. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Get the non default policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Get the non default policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Sets an individual policy. - - The interface the policy is registered under. - The policy to be registered. - The key the policy applies. - - - - Sets an individual policy. - - The of the policy. - The policy to be registered. - The key the policy applies. - - - - Sets a default policy. When checking for a policy, if no specific individual policy - is available, the default will be used. - - The interface to register the policy under. - The default policy to be registered. - - - - Sets a default policy. When checking for a policy, if no specific individual policy - is available, the default will be used. - - The interface to register the policy under. - The default policy to be registered. - - - - This interface defines a standard method to convert any - regardless - of the stage enum into a regular, flat strategy chain. - - - - - Convert this into - a flat . - - The flattened . - - - - Represents a chain of responsibility for builder strategies. - - - - - Reverse the order of the strategy chain. - - The reversed strategy chain. - - - - Execute this strategy chain against the given context, - calling the Buildup methods on the strategies. - - Context for the build process. - The build up object - - - - Execute this strategy chain against the given context, - calling the TearDown methods on the strategies. - - Context for the teardown process. - - - - Represents a build key based on type. - - - - - Construct a new build key object with the current type - replaced with the specified . - - This method creates a new build key object, the original is unchanged. - New type to place in the build key. - The new build key. - - - - Gets the that represents the key. - - - The that represents the key. - - - - - Represents a lifetime container. - - - A lifetime container tracks the lifetime of an object, and implements - IDisposable. When the container is disposed, any objects in the - container which implement IDisposable are also disposed. - - - - - Adds an object to the lifetime container. - - The item to be added to the lifetime container. - - - - Determine if a given object is in the lifetime container. - - - The item to locate in the lifetime container. - - - Returns true if the object is contained in the lifetime - container; returns false otherwise. - - - - - Removes an item from the lifetime container. The item is - not disposed. - - The item to be removed. - - - - Gets the number of references in the lifetime container - - - The number of references in the lifetime container - - - - - Represents a lifetime container. - - - A lifetime container tracks the lifetime of an object, and implements - IDisposable. When the container is disposed, any objects in the - container which implement IDisposable are also disposed. - - - - - Adds an object to the lifetime container. - - The item to be added to the lifetime container. - - - - Determine if a given object is in the lifetime container. - - - The item to locate in the lifetime container. - - - Returns true if the object is contained in the lifetime - container; returns false otherwise. - - - - - Releases the resources used by the . - - - - - Releases the managed resources used by the DbDataReader and optionally releases the unmanaged resources. - - - true to release managed and unmanaged resources; false to release only unmanaged resources. - - - - - Returns an enumerator that iterates through the lifetime container. - - - An object that can be used to iterate through the life time container. - - - - - Returns an enumerator that iterates through the lifetime container. - - - An object that can be used to iterate through the life time container. - - - - - Removes an item from the lifetime container. The item is - not disposed. - - The item to be removed. - - - - Gets the number of references in the lifetime container - - - The number of references in the lifetime container - - - - - Represents a locator that can be read from. - - - A locator is a dictionary of keys to values, but it keeps the values with - weak references, so that locating an object does not keep it alive. If you - want to keep the object alive too, you should consider using an - . - Locators have a built-in concept of hierarchy, so you can ask questions - of a locator and tell it whether to return results from the current locator - only, or whether to ask the parent locator when local lookups fail. - - - - - Determine if the locator contains an object for the given key. - - The key to check. - - true if the locator contains an object for the key; returns - false otherwise. - - - - - Finds objects in the locator using the predicate, and returns a temporary locator - filled with the found objects. - - The predicate to test whether to include an object. - The new locator - Predicate is null. - - - - Gets an object from the locator, registered with the key of typeof(T). - - The type of the object to find. - The object, if found; null otherwise. - - - - Gets an object from the locator, registered with the given key. - - The type of the object to find. - The key that the object is registered with. - The object, if found; null otherwise. - Key is null. - - - - Gets an object from the locator, registered with the given key. - - The key that the object is registered with. - The object, if found; null otherwise. - Key is null. - - - - Gets the number of items in the locator. - - - The number of items in the locator. - - - - - Gets the parent locator. - - - The parent locator. - - - - - Determines if the locator is read-only. - - - true if the locator is read-only; otherwise, false. - - - - - Represents a locator that can be read from and written to. - - - - A locator is dictionary of keys to values, but it keeps the values with - weak references, so that locating an object does not keep it alive. If you - want to keep the object alive too, you should consider using an - . - - - Locators have a built-in concept of hierarchy, so you can ask questions - of a locator and tell it whether to return results from the current locator - only, or whether to ask the parent locator when local lookups fail. - - - - - Adds an object to the locator, with the given key. - - The key to register the object with. - The object to be registered. - or value are null. - - - - Removes an object from the locator. - - The key under which the object was registered. - - Returns true if the object was found in the locator; returns - false otherwise. - - is null. - - - - An implementation of and . - - - - - Represents an abstract implementation of . - - - - - Represents an abstract implementation of . - - - - - Initialize a new instance of the class. - - - - - Initialize a new instance of the class with a parent . - - A parent . - - - - Determine if the locator contains an object for the given key. - - The key to check. - - true if the locator contains an object for the key; returns - false otherwise. - - - - - Finds objects in the locator using the predicate, and returns a temporary locator - filled with the found objects. - - The predicate to test whether to include an object. - The new locator - Predicate is null. - - - - Gets an object from the locator, registered with the key of typeof(T). - - The type of the object to find. - The object, if found; null otherwise. - - - - Gets an object from the locator, registered with the given key. - - The type of the object to find. - The key that the object is registered with. - The object, if found; null otherwise. - is null. - - - - Gets an object from the locator, registered with the given key. - - The key that the object is registered with. - The object, if found; null otherwise. - Key is null. - - - - Returns an enumerator that iterates through the locator. - - - An object that can be used to iterate through the locator. - - - - - Returns an enumerator that iterates through the locator. - - - An object that can be used to iterate through the locator. - - - - - Gets the number of items in the locator. - - - The number of items in the locator. - - - - - Gets the parent locator. - - - The parent locator. - - - - - Determines if the locator is read-only. - - - true if the locator is read-only; otherwise, false. - - - - - Initialize a new instance of the class. - - - - - Initialize a new instance of the class with a parent . - - A parent . - - - - Adds an object to the locator, with the given key. - - The key to register the object with. - The object to be registered. - or value are null. - - - - Removes an object from the locator. - - The key under which the object was registered. - - Returns true if the object was found in the locator; returns - false otherwise. - - is null. - - - - Determines if the locator is read-only. - - - true if the locator is read-only; otherwise, false. - - - - - Initializes a new instance of the class. - - - - - Initializes a new instance of the class as a child of the . - - The parent locator. - - - - Adds an object to the locator, with the given key. - - The key to register the object with. - The object to be registered. - Key or value are null. - - - - Determine if the locator contains an object for the given key. - - The key to check. - - true if the locator contains an object for the key; returns - false otherwise. - - - - - Gets an object from the locator, registered with the given key. - - The key that the object is registered with. - The object, if found; null otherwise. - Key is null. - - - - Returns an enumerator that iterates through a locator. - - - An object that can be used to iterate through the locator. - - - - - Removes an object from the locator. - - The key under which the object was registered. - - Returns true if the object was found in the locator; returns - false otherwise. - - Key is null. - - - - Gets the number of items in the locator. - - - The number of items in the locator. - - - - - An implementation of that wraps an existing locator - to ensure items are not written into the locator. - - - - - Initialize a new instance of the class with an to wrap. - - The inner locator to be wrapped. - - - - Determine if the locator contains an object for the given key. - - The key to check. - - true if the locator contains an object for the key; returns - false otherwise. - - - - - Gets an object from the locator, registered with the given key. - - The key that the object is registered with. - The object, if found; null otherwise. - Key is null. - - - - Returns an enumerator that iterates through the locator. - - - An object that can be used to iterate through the locator. - - - - - Gets the number of items in the locator. - - - The number of items in the locator. - - - - - Gets the parent locator. - - - The parent locator. - - - - - Determines if the locator is read-only. - - - true if the locator is read-only; otherwise, false. - - - - - A custom collection wrapper over objects. - - - - - Initialize a new instance of a class. - - - - - Initialize a new instance of a class with another policy list. - - An inner policy list to search. - - - - Removes an individual policy type for a build key. - - The type the policy was registered as. - The key the policy applies. - - - - Removes an individual policy type for a build key. - - The type of policy to remove. - The key the policy applies. - - - - Removes all policies from the list. - - - - - Removes a default policy. - - The type the policy was registered as. - - - - Removes a default policy. - - The type the policy was registered as. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - The policy in the list, if present; returns null otherwise. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - The policy in the list, if present; returns null otherwise. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Gets an individual policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Get the non default policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Get the non default policy. - - The interface the policy is registered under. - The key the policy applies. - true if the policy searches local only; otherwise false to seach up the parent chain. - The policy in the list, if present; returns null otherwise. - - - - Sets an individual policy. - - The interface the policy is registered under. - The policy to be registered. - The key the policy applies. - - - - Sets an individual policy. - - The of the policy. - The policy to be registered. - The key the policy applies. - - - - Sets a default policy. When checking for a policy, if no specific individual policy - is available, the default will be used. - - The interface to register the policy under. - The default policy to be registered. - - - - Sets a default policy. When checking for a policy, if no specific individual policy - is available, the default will be used. - - The interface to register the policy under. - The default policy to be registered. - - - - Gets the number of items in the locator. - - - The number of items in the locator. - - - - - A builder policy used to create lifetime policy instances. - Used by the LifetimeStrategy when instantiating open - generic types. - - - - - Create a new instance of . - - The new instance. - - - - A that controls how instances are - persisted and recovered from an external store. Used to implement - things like singletons and per-http-request lifetime. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object to store. - - - - Remove the value this lifetime policy is managing from backing store. - - - - - An implementation that uses - a to figure out if an object - has already been created and to update or remove that - object from some backing store. - - - - - Called during the chain of responsibility for a build operation. The - PreBuildUp method is called when the chain is being executed in the - forward direction. - - Context of the build operation. - - - - Called during the chain of responsibility for a build operation. The - PostBuildUp method is called when the chain has finished the PreBuildUp - phase and executes in reverse order from the PreBuildUp calls. - - Context of the build operation. - - - - A that stores objects in the locator and - lifetime container provided by the context. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - - - - Remove the given object from backing store. - - - - - A method that does whatever is needed to clean up - as part of cleaning up after an exception. - - - Don't do anything that could throw in this method, - it will cause later recover operations to get skipped - and play real havok with the stack trace. - - - - - An implementation of that does nothing, - ensuring that a new object gets created every time. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - - - - Remove the given object from backing store. - - - - - Represents a chain of responsibility for builder strategies partitioned by stages. - - The stage enumeration to partition the strategies. - - - - Initialize a new instance of the class. - - - - - Initialize a new instance of the class with an inner strategy chain to use when building. - - The inner strategy chain to use first when finding strategies in the build operation. - - - - Adds a strategy to the chain at a particular stage. - - The strategy to add to the chain. - The stage to add the strategy. - - - - Add a new strategy for the . - - The of - The stage to add the strategy. - - - - Clear the current strategy chain list. - - - This will not clear the inner strategy chain if this instane was created with one. - - - - - Makes a strategy chain based on this instance. - - A new . - - - - Represents a chain of responsibility for builder strategies. - - - - - Initialzie a new instance of the class. - - - - - Initialzie a new instance of the class with a colleciton of strategies. - - A collection of strategies to initialize the chain. - - - - Adds a strategy to the chain. - - The strategy to add to the chain. - - - - Adds strategies to the chain. - - The strategies to add to the chain. - - - - Reverse the order of the strategy chain. - - The reversed strategy chain. - - - - Execute this strategy chain against the given context to build up. - - Context for the build processes. - The build up object - - - - Execute this strategy chain against the given context, - calling the TearDown methods on the strategies. - - Context for the teardown process. - - - - Returns an enumerator that iterates through the collection. - - - - A that can be used to iterate through the collection. - - 1 - - - - Returns an enumerator that iterates through a collection. - - - - An object that can be used to iterate through the collection. - - 2 - - - - Utility methods for dealing with arbitrary build key objects. - - - - - Gets the of object to build from the build key. - - The build key to get the . - The of object to build from the key. - - - - Tries to get the from . - - The build key to get the . - - true if the was found; otherwise, false. - - - - Given a , return a new build key - which is the same as the original, except that the type has - been replaced with . - - original build key - New type to put in new build key. - The new build key. - - - - Represents a simple class for validating parameters and throwing exceptions. - - - - - Validates is not null and throws if it is null. - - The value to validate. - The name of . - - - - Validates is not null or an empty string and throws if it is null or an empty string . - - The value to validate. - The name of . - - - - Represents a dictionary which stores the values as weak references instead of strong - references. Null values are supported. - - The key type - The value type - - - - Gets the count of the number of items in the dictionary. - - - The count of the number of items in the dictionary. - - - Since the items in the dictionary are held by weak reference, the count value - cannot be relied upon to guarantee the number of objects that would be discovered via - enumeration. Treat the Count as an estimate only. - - - - - Determines if the dictionary contains a value for the key. - - The key to look for. - true if the key is contained in the dictionary; otherwise, false. - - - - Returns an enumerator that iterates through the dictionary. - - - An object that can be used to iterate through the dictionary. - - - - - Removes an item from the dictionary. - - The key of the item to be removed. - Returns true if the key was in the dictionary; return false otherwise. - - - - Attempts to get a value from the dictionary. - - The key - The value - Returns true if the value was present; false otherwise. - - - - Returns a count of the number of items in the dictionary. - - - Since the items in the dictionary are held by weak reference, the count value - cannot be relied upon to guarantee the number of objects that would be discovered via - enumeration. Treat the Count as an estimate only. - - - - - Retrieves a value from the dictionary. - - The key to look for. - The value in the dictionary. - Thrown when the key does exist in the dictionary. - Since the dictionary contains weak references, the key may have been removed by the - garbage collection of the object. - - - - The exception thrown when injection is attempted on a method - that is an open generic or has out or ref params. - - - The exception thrown when injection is attempted on a method - that is an open generic or has out or ref params. - - - - - Construct a new with no - message. - - - - - Construct a with the given message - - Message to return. - - - - Construct a with the given message - and inner exception. - - Message to return. - Inner exception - - - - Used for serialization. - - Serialization info. - Serialization context. - - - - Build key used to combine a type object with a string name. Used by - ObjectBuilder to indicate exactly what is being built. - - - - - Create a new instance with the given - type and name. - - to build. - Key to use to look up type mappings and singletons. - - - - Create a new instance for the default - buildup of the given type. - - to build. - - - - This helper method creates a new instance. It is - initialized for the default key for the given type. - - Type to build. - A new instance. - - - - This helper method creates a new instance for - the given type and key. - - Type to build - Key to use to look up type mappings and singletons. - A new instance initialized with the given type and name. - - - - Construct a new build key object with the current type - replaced with the specified . - - This method creates a new build key object, the original is unchanged. - New type to place in the build key. - The new build key. - - - - Compare two instances. - - Two instances compare equal - if they contain the same name and the same type. Also, comparing - against a different type will also return false. - Object to compare to. - True if the two keys are equal, false if not. - - - - Calculate a hash code for this instance. - - A hash code. - - - - Compare two instances for equality. - - Two instances compare equal - if they contain the same name and the same type. - First of the two keys to compare. - Second of the two keys to compare. - True if the values of the keys are the same, else false. - - - - Compare two instances for inequality. - - Two instances compare equal - if they contain the same name and the same type. If either field differs - the keys are not equal. - First of the two keys to compare. - Second of the two keys to compare. - false if the values of the keys are the same, else true. - - - - Formats the build key as a string (primarily for debugging). - - A readable string representation of the build key. - - - - Return the stored in this build key. - - The type to build. - - - - Returns the name stored in this build key. - - The name to use when building. - - - - A series of helper methods to deal with sequences - - objects that implement . - - LINQ in C# 3.0 does pretty much the same stuff, - but we're keeping C# 2.0 compatibility here. - - - - Given an , return a - new containing the same contents. - - Type of item store in the sequence. - Sequence to create list from. - The new - - - - Given an return a new - that contains - all the objects in that - are castable to . - - Desired type for objects. - Input sequence. - New output sequence. - - - - A function that turns an arbitrary parameter list into an - . - - Type of arguments. - The items to put into the collection. - An array that contains the values of the . - - - - Create an array containing the elements of the given sequence. - - Type of sequence and array. - Input sequence. - The resulting array. - - - - Given a sequence of , returns a sequence - containing those elements that satisfy the given predicate . - - Type of items in the sequence. - Source sequence. - Predicate used to test which items match. - The sequence of items that satify . This - sequence may be empty. - - - - Tests the given , returning true if any - element in satisfies the given predicate. - - Type of elements in sequence. - Sequence to test. - Predicate to use to test for existence. - true if any elements satify pred, false if not. - - - - Tests the given , returning true only if all - elements in satisfies the given predicate. - - Type of elements in sequence. - Sequence to test. - Predicate to use to test. - true if all elements satify pred, false if not. - - - - Given a sequence of , returns a sequence of - created by running the items in - through . - - Type of items in input. - Type of items in output. - Input sequence. - Mapping function. - The converted output sequence. - - - - Run a functional Reduce operation. See other methods for examples. - - Type of inputs. - Type of final output. - Sequence of input items. - Initial value for accumulator. - Reduce function. - - - - - Convert the given sequence to a single string. The items in the string are - separated by the given separator, and each object is converted to a string - using the method given. - - Type of input sequence. - Input sequence. - Separator string. - Function to convert instances to - strings. - The collected string. - - - - Convert the given sequence to a single string. The items in the string are separated - by the given separator, and each object is converted to a string by calling its - method. - - Type of input sequence. - Input sequence. - Separator string. - The collected string. - - - - Return the first item in the given sequence. - - Thrown if the sequence is empty. - Type of items in the sequence. - The sequence. - First item in the sequence. - - - - Execute the given action delegate for each item in the sequence. - - Type of item in the sequence. - The sequence of items. - Action to perform on each item. - - - - Concatenate multiple sequences into a single one. - - Type of sequences in the sequence. - The sequences to combine. - The combined sequence. - - - - A delegate that defines the function passed to the methods. - - Type of item being reduced. - Type of the accumulator object. - Current item to process. - Current value of the accumulator. - - - - - Static class containing constructor methods for - instances of , so that we - get type inference. - - - - - Make a new instance of that wraps - the given items. - - Type of items in the sequence. - Items in the sequence. - The sequence. - - - - Make a new instance of that wraps - the given items. - - Type of items in the sequence. - Items in the sequence. - The sequence. - - - - And another helper class that makes it possible to chain sequence operations together. - - Type of item contained in the sequence. - - - - Create a new instance wrapping the given IEnumerable. - - The sequence to wrap. - - - - Returns an enumerator that iterates through a collection. - - - An object that can be used to iterate through the collection. - - 2 - - - - Returns an enumerator that iterates through the collection. - - - A that can be used to iterate through the collection. - - 1 - - - - Given a sequence object, return a list containing those items. - - The materialized list. - - - - Return an array with the same contents as this sequence. - - The materialized array. - - - - Returns new sequence containing only the items for which the predicate is true. - - Test to indicate sequence inclusion - New sequence. - - - - Tests the sequence, returning true if any - element satisfies the given predicate. - - Predicate to use to test for existence. - true if any elements satify pred, false if not. - - - - Tests the sequence, returning true only if all - elements satisfy the given predicate. - - Predicate to use to test. - true if all elements satify pred, false if not. - - - - Return a new sequence consisting of the result of running each element through - the given . - - Desired output type. - Converter delegate. - New Sequence - - - - Run a functional Reduce operation. See other methods for examples. - - Type of final output. - Initial value for accumulator. - Reduce function. - - - - - Convert the given sequence to a single string. The items in the string are - separated by the given separator, and each object is converted to a string - using the method given. - - Separator string. - Function to convert instances to - strings. - The collected string. - - - - Convert the given sequence to a single string. The items in the string are separated - by the given separator, and each object is converted to a string by calling its - method. - - Separator string. - The collected string. - - - - Return the first item in the given sequence. - - Thrown if the sequence is empty. - First item in the sequence. - - - - Execute the given action delegate for each item in the sequence. - - Action to perform on each item. - - - - Concatenate multiple sequences with this one to return a single - sequence containing all items. - - Sequences to combine. - The combined sequence. - - - + + + + Microsoft.Practices.ObjectBuilder2 + + + + + An implementation of . It contains all the default strategies shipped + with ObjectBuilder. + + + + + Represents the main interface for an object builder. + + + + + Performs a build operation. + + + This operation uses the strategies and permanent policies already configured + into the builder, combined with the optional transient policies, and starts a build + operation. Transient policies override any built-in policies, when present. + + The locator to be used for this build operation. + The to use for this build operation. + + The transient policies to apply to this build. These + policies take precedence over any permanent policies built into the builder. + + + The to use for this build operation. + + The key of the object to build. + + The existing object to run the build chain on, if one exists. + If null is passed, a new object instance will typically be created by some strategy + in the chain. + + The built object. + + + + Performs a build operation. + + + This operation uses the strategies and permanent policies already configured + into the builder, combined with the optional transient policies, and starts a build + operation. Transient policies override any built-in policies, when present. + + The type to build. + The locator to be used for this build operation. + The to use for this build operation. + + The transient policies to apply to this build. These + policies take precedence over any permanent policies built into the builder. + + + The to use for this build operation. + + The key of the object to build. + + The existing object to run the build chain on, if one exists. + If null is passed, a new object instance will typically be created by some strategy + in the chain. + + The built object. + + + + Performs an unbuild operation. + + The type to unbuild. If not provided, it will be inferred from the + type of item. + + The locator to be used for this build operation. + The to use for this build operation. + + The transient policies to apply to this build. These + policies take precedence over any permanent policies built into the builder. + + + The to use for this build operation. + + The item to tear down. + The torn down item. + + + + Performs a build operation. + + + This operation uses the strategies and permanent policies already configured + into the builder, combined with the optional transient policies, and starts a build + operation. Transient policies override any built-in policies, when present. + + The locator to be used for this build operation. + The to use for this build operation. + + The transient policies to apply to this build. These + policies take precedence over any permanent policies built into the builder. + + + The to use for this build operation. + + The key of the object to build. + + The existing object to run the build chain on, if one exists. + If null is passed, a new object instance will typically be created by some strategy + in the chain. + + The built object. + + + + Performs a build operation. + + + This operation uses the strategies and permanent policies already configured + into the builder, combined with the optional transient policies, and starts a build + operation. Transient policies override any built-in policies, when present. + + The type to build. + The locator to be used for this build operation. + The to use for this build operation. + + The transient policies to apply to this build. These + policies take precedence over any permanent policies built into the builder. + + + The to use for this build operation. + + The key of the object to build. + + The existing object to run the build chain on, if one exists. + If null is passed, a new object instance will typically be created by some strategy + in the chain. + + The built object. + + + + Performs an unbuild operation. + + The type to unbuild. If not provided, it will be inferred from the + type of item. + + The locator to be used for this build operation. + The to use for this build operation. + + The transient policies to apply to this build. These + policies take precedence over any permanent policies built into the builder. + + + The to use for this build operation. + + The item to tear down. + The torn down item. + + + + Represents the context in which a build-up or tear-down operation runs. + + + + + Represents the context in which a build-up or tear-down operation runs. + + + + + Create a new IBuilderContext which has the same strategies, locator, policies, and lifetime + but a new build key and existing object. Used to execute recursive calls when + building up dependencies. + + Build key for new buildup. + New exsting object for buildup. + The new context. + + + + Gets the head of the strategy chain. + + + The strategy that's first in the chain; returns null if there are no + strategies in the chain. + + + + + Gets the associated with the build. + + + The associated with the build. + + + + + Gets the locator available to the strategies. + + + The locator available to the strategies. + + + + + Gets the original build key for the build operation. + + + The original build key for the build operation. + + + + + The set of policies that were passed into this context. + + This returns the policies passed into the context. + Policies added here will remain after buildup completes. + The persistent policies for the current context. + + + + Gets the policies for the current context. + + Any policies added to this object are transient + and will be erased at the end of the buildup. + + The policies for the current context. + + + + + Gets the collection of objects + that need to execute in event of an exception. + + + + + Get the current build key for the current build operation. + + + + + The current object being built up or torn down. + + + The current object being manipulated by the build operation. May + be null if the object hasn't been created yet. + + + + Flag indicating if the build operation should continue. + + true means that building should not call any more + strategies, false means continue to the next strategy. + + + + Initialize a new instance of the class. + + + + + Initialize a new instance of the class with a , + , , and the + build key used to start this build operation. + + The to use for this context. + The to use for this context. + The to use for this context. + The to use for this context. + Build key to start building. + The existing object to build up. + + + + Create a new using the explicitly provided + values. + + The to use for this context. + The to use for this context. + The to use for this context. + The set of persistent policies to use for this context. + The set of transient policies to use for this context. It is + the caller's responsibility to ensure that the transient and persistent policies are properly + combined. + Build key for this context. + Existing object to build up. + + + + Create a new IBuilderContext which has the same strategies, locator, policies, and lifetime + but a new build key and existing object. Used to execute recursive calls when + building up dependencies. + + Build key for new buildup. + New exsting object for buildup. + The new context. + + + + A convenience method to do a new buildup operation on an existing context. + + This helper is specific to NamedTypeBuildKey. + Type to return from the buildup. + Existing context. + The built up object. + + + + Gets the head of the strategy chain. + + + The strategy that's first in the chain; returns null if there are no + strategies in the chain. + + + + + Get the current build key for the current build operation. + + + + + The current object being built up or torn down. + + + The current object being manipulated by the build operation. May + be null if the object hasn't been created yet. + + + + Gets the associated with the build. + + + The associated with the build. + + + + + Gets the locator available to the strategies. + + + The locator available to the strategies. + + + + + Gets the original build key for the build operation. + + + The original build key for the build operation. + + + + + The set of policies that were passed into this context. + + This returns the policies passed into the context. + Policies added here will remain after buildup completes. + The persistent policies for the current context. + + + + Gets the policies for the current context. + + + Any modifications will be transient (meaning, they will be forgotten when + the outer BuildUp for this context is finished executing). + + + The policies for the current context. + + + + + Gets the collection of objects + that need to execute in event of an exception. + + + + + Flag indicating if the build operation should continue. + + true means that building should not call any more + strategies, false means continue to the next strategy. + + + + The exception that gets thrown if a build or teardown operation fails. + + + + + Create a new instance containing + the information about the currently executing strategy that caused + the exception. + + The that was + executing at the time the exception was thrown. + The index of the current strategy in its + strategy chain. + The build key being built up. + Underlying exception. + + + + Create a new . Do not use this constructor, it + does not take any of the data that makes this type useful. + + + + + Create a new . Do not use this constructor, it + does not take any of the data that makes this type useful. + + Error message, ignored. + + + + Create a new . Do not use this constructor, it + does not take any of the data that makes this type useful. + + Error message, ignored. + Inner exception. + + + + Create a new from the serialized information. + + Serialization info. + Streaming context. + + + + When overridden in a derived class, sets the with information about the exception. + + + The that contains contextual information about the source or destination. + The that holds the serialized object data about the exception being thrown. + The info parameter is a null reference (Nothing in Visual Basic). 2 + + + + The strategy that was executing when the exception occurred. + + + + + The index of the currently executing strategy in the build chain. + + + + + The build key that was being built at the time of the exception. + + + + + Gets a message that describes the current exception. + + + + The error message that explains the reason for the exception, or an empty string(""). + + 1 + + + + Represents that a dependency could not be resolved. + + + Represents that a dependency could not be resolved. + + + + + Initializes a new instance of the class with no extra information. + + + + + Initializes a new instance of the class with the given message. + + Some random message. + + + + Initialize a new instance of the class with the given + message and inner exception. + + Some random message + Inner exception. + + + + Initializes a new instance of the class with the build key of the object begin built. + + The build key of the object begin built. + + + + Initializes a new instance of the class with serialized data. + + The that holds the serialized object data about the exception being thrown. + The that contains contextual information about the source or destination. + + + + Data structure that stores the set of + objects and executes them when requested. + + + + + Add a new object to this + list. + + Object to add. + + + + Execute the method + of everything in the recovery list. Recoveries will execute + in the opposite order of add - it's a stack. + + + + + Return the number of recovery objects currently in the stack. + + + + + This interface provides a hook for the builder context to + implement error recovery when a builder strategy throws + an exception. Since we can't get try/finally blocks onto + the call stack for later stages in the chain, we instead + add these objects to the context. If there's an exception, + all the current IRequiresRecovery instances will have + their Recover methods called. + + + + + A method that does whatever is needed to clean up + as part of cleaning up after an exception. + + + Don't do anything that could throw in this method, + it will cause later recover operations to get skipped + and play real havok with the stack trace. + + + + + A strongly-typed resource class, for looking up localized strings, etc. + + + + + Returns the cached ResourceManager instance used by this class. + + + + + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + + + + + Looks up a localized string similar to The type {0} has multiple constructors of length {1}. Unable to disambiguate.. + + + + + Looks up a localized string similar to The current build operation (build key {2}) failed: {3} (Strategy type {0}, index {1}). + + + + + Looks up a localized string similar to The current type, {0}, is an interface and cannot be constructed. Are you missing a type mapping?. + + + + + Looks up a localized string similar to Cannot extract type from build key {0}.. + + + + + Looks up a localized string similar to The method {1} on type {0} has an out parameter. Injection cannot be performed.. + + + + + Looks up a localized string similar to The method {1} on type {0} is marked for injection, but it is an open generic method. Injection cannot be performed.. + + + + + Looks up a localized string similar to The parameter {0} could not be resolved when attempting to call constructor {1}.. + + + + + Looks up a localized string similar to An item with the given key is already present in the dictionary.. + + + + + Looks up a localized string similar to The value for parameter "{1}" of method {0} could not be resolved. . + + + + + Looks up a localized string similar to Could not resolve dependency for build key {0}.. + + + + + Looks up a localized string similar to The type {0} has multiple constructors marked with the InjectionConstructor attribute. Unable to disambiguate.. + + + + + Looks up a localized string similar to The supplied type {0} must be an open generic type.. + + + + + Looks up a localized string similar to The supplied type {0} does not have the same number of generic arguments as the target type {1}.. + + + + + Looks up a localized string similar to The type {0} does not have an accessible constructor.. + + + + + Looks up a localized string similar to The value for the property "{0}" could not be resolved.. + + + + + Looks up a localized string similar to The provided string argument must not be empty.. + + + + + An implementation of . + + + + + Add a new object to this + list. + + Object to add. + + + + Execute the method + of everything in the recovery list. Recoveries will execute + in the opposite order of add - it's a stack. + + + + + Return the number of recovery objects currently in the stack. + + + + + Implementation of which will notify an object about + the completion of a operation, or start of a + operation. + + + This strategy checks the object that is passing through the builder chain to see if it + implements IBuilderAware and if it does, it will call + and . This strategy is meant to be used from the + stage. + + + + + Represents a strategy in the 's chain of responsibility. + Strategies are required to support both BuildUp and TearDown. + + + + + Represents a strategy in the 's chain of responsibility. + Strategies are required to support both BuildUp and TearDown. Although you + can implement this interface directly, you may also choose to use + as the base class for your strategies, as + this class provides useful helper methods and makes support BuildUp and TearDown + optional. + + + + + Called during the chain of responsibility for a build operation. The + PreBuildUp method is called when the chain is being executed in the + forward direction. + + Context of the build operation. + + + + Called during the chain of responsibility for a build operation. The + PostBuildUp method is called when the chain has finished the PreBuildUp + phase and executes in reverse order from the PreBuildUp calls. + + Context of the build operation. + + + + Called during the chain of responsibility for a teardown operation. The + PreTearDown method is called when the chain is being executed in the + forward direction. + + Context of the teardown operation. + + + + Called during the chain of responsibility for a teardown operation. The + PostTearDown method is called when the chain has finished the PreTearDown + phase and executes in reverse order from the PreTearDown calls. + + + + + + Called during the chain of responsibility for a build operation. The + PreBuildUp method is called when the chain is being executed in the + forward direction. + + Context of the build operation. + + + + Called during the chain of responsibility for a build operation. The + PostBuildUp method is called when the chain has finished the PreBuildUp + phase and executes in reverse order from the PreBuildUp calls. + + Context of the build operation. + + + + Called during the chain of responsibility for a teardown operation. The + PreTearDown method is called when the chain is being executed in the + forward direction. + + Context of the teardown operation. + + + + Called during the chain of responsibility for a teardown operation. The + PostTearDown method is called when the chain has finished the PreTearDown + phase and executes in reverse order from the PreTearDown calls. + + + + + + Called during the chain of responsibility for a build operation. The + PreBuildUp method is called when the chain is being executed in the + forward direction. + + Context of the build operation. + + + + Called during the chain of responsibility for a teardown operation. The + PreTearDown method is called when the chain is being executed in the + forward direction. + + Context of the teardown operation. + + + + Implemented on a class when it wants to receive notifications + about the build process. + + + + + Called by the when the object is being built up. + + The key of the object that was just built up. + + + + Called by the when the object is being torn down. + + + + + Enumeration to represent the object builder stages. + + + The order of the values in the enumeration is the order in which the stages are run. + + + + + Strategies in this stage run before creation. Typical work done in this stage might + include strategies that use reflection to set policies into the context that other + strategies would later use. + + + + + Strategies in this stage create objects. Typically you will only have a single policy-driven + creation strategy in this stage. + + + + + Strategies in this stage work on created objects. Typical work done in this stage might + include setter injection and method calls. + + + + + Strategies in this stage work on objects that are already initialized. Typical work done in + this stage might include looking to see if the object implements some notification interface + to discover when its initialization stage has been completed. + + + + + Represents a builder policy interface. Since there are no fixed requirements + for policies, it acts as a marker interface from which to derive all other + policy interfaces. + + + + + Represents a builder policy for mapping build keys. + + + + + Represents a builder policy for mapping build keys. + + + + + Maps the build key. + + The build key to map. + The new build key. + + + + Initialize a new instance of the with the new build key. + + + + + + Map the to a new build key. + + The build key to mapl + The new build key. + + + + Represents a strategy for mapping build keys in the build up operation. + + + + + Called during the chain of responsibility for a build operation. Looks for the + and if found maps the build key for the current operation. + + The context for the operation. + + + + An implementation of that can map + generic types. + + + + + Create a new instance + that will map generic types. + + Build key to map to. This must be or contain an open generic type. + + + + Maps the build key. + + The build key to map. + The new build key. + + + + A that will look for a build plan + in the current context. If it exists, it invokes it, otherwise + it creates one and stores it for later, and invokes it. + + + + + Called during the chain of responsibility for a build operation. + + The context for the operation. + + + + An implementation of that chooses + constructors based on these criteria: first, pick a constructor marked with the + attribute. If there + isn't one, then choose the constructor with the longest parameter list. If that is ambiguous, + then throw. + + Thrown when the constructor to choose is ambiguous. + Attribute used to mark the constructor to call. + + + + Base class that provides an implementation of + which lets you override how the parameter resolvers are created. + + + + + A that, when implemented, + will determine which constructor to call from the build plan. + + + + + Choose the constructor to call for the given type. + + Current build context + The chosen constructor. + + + + Choose the constructor to call for the given type. + + Current build context. + The chosen constructor. + Thrown when the constructor to choose is ambiguous. + + + + Create a instance for the given + . + + Parameter to create the resolver for. + The resolver object. + + + + Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. + + + + Value Condition Less than zerox is less than y.Zerox equals y.Greater than zerox is greater than y. + + + The second object to compare. + The first object to compare. + + + + Create a instance for the given + . + + Parameter to create the resolver for. + The resolver object. + + + + Objects of this type are the return value from . + It encapsulates the desired with the string keys + needed to look up the for each + parameter. + + + + + Base class for return values from selector policies that + return a memberinfo of some sort plus a list of parameter + keys to look up the parameter resolvers. + + + + + Base class for return of selector policies that need + to keep track of a set of parameter keys. + + + + + Add a new parameter key to this object. Keys are assumed + to be in the order of the parameters to the constructor. + + Key for the next parameter to look up. + + + + The set of keys for the constructor parameters. + + + + + Construct a new , storing + the given member info. + + Member info to store. + + + + The member info stored. + + + + + Create a new instance which + contains the given constructor. + + + + + + The constructor this object wraps. + + + + + A that emits IL to call constructors + as part of creating a build plan. + + + + + Called during the chain of responsibility for a build operation. + + Existing object is an instance of . + The context for the operation. + + + + A helper method used by the generated IL to throw an exception if + a dependency cannot be resolved. + + The currently being + used for the build of this object. + + + + A helper method used by the generated IL to throw an exception if a parameter + fails to resolve. + + Inner exception to throw. + Name of the parameter that was attempted to be resolved. + String describing which constructor we were calling. + Current build context. + + + + A helper method used by the generated IL to throw an exception if + no existing object is present, but the user is attempting to build + an interface (usually due to the lack of a type mapping). + + + + + + An implementation of that will + check for full trust and if we're building a class or an interface. If in full + trust, attach to the class or module of the interface respectively. If in partial + trust, attach to the OB2 module instead. + + + + + This interface defines a policy that manages creation of the dynamic methods + used by the ObjectBuilder code generation. This way, we can replace the details + of how the dynamic method is created to handle differences in CLR (like Silverlight + vs desktop) or security policies. + + + + + Create a builder method for the given type, using the given name. + + Type that will be built by the generated method. + Name to give to the method. + A object with the proper signature to use + as part of a build plan. + + + + Create a builder method for the given type, using the given name. + + Type that will be built by the generated method. + Name to give to the method. + A object with the proper signature to use + as part of a build plan. + + + + This object tracks the current state of the build plan generation, + accumulates the IL, provides the preamble & postamble for the dynamic + method, and tracks things like local variables in the generated IL + so that they can be reused across IL generation strategies. + + + + + Create a that is initialized + to handle creation of a dynamic method to build the given type. + + Type that we're trying to create a build plan for. + An object that actually + creates our object. + + + + Completes generation of the dynamic method and returns the + generated dynamic method delegate. + + The created + + + + Emit the IL to put the build context on top of the IL stack. + + + + + Emit the IL to put the current build key on top of the IL stack. + + + + + Emit the IL to put the current "existing" object on the top of the IL stack. + + + + + Emit the IL to make the top of the IL stack our current "existing" object. + + + + + Emit the IL to load the given object onto the top of the IL stack. + + Type to load on the stack. + + + + Emit the IL needed to look up an and + call it to get a value. + + Type of the dependency to resolve. + Key to look up the policy by. + + + + A reflection helper method to make it easier to grab a property getter + for the given property. + + Type that implements the property we want. + Type of the property. + Name of the property. + The property getter's . + + + + A reflection helper method that makes it easier to grab a + for a method. + + Type that implements the method we want. + Name of the method. + Types of arguments to the method. + The method's . + + + + The underlying that can be used to + emit IL into the generated dynamic method. + + + + + The type we're currently creating the method to build. + + + + + A delegate type that defines the signature of the + dynamic method created by the build plans. + + used to build up the object. + + + + An implementation of that runs the + given delegate to execute the plan. + + + + + A build plan is an object that, when invoked, will create a new object + or fill in a given existing one. It encapsulates all the information + gathered by the strategies to construct a particular object. + + + + + Creates an instance of this build plan's type, or fills + in the existing type if passed in. + + Context used to build up the object. + + + + An implementation + that constructs a build plan via dynamic IL emission. + + + + + A that can create and return an + for the given build key. + + + + + Create a build plan using the given context and build key. + + Current build context. + Current build key. + The build plan. + + + + Construct a that + uses the given strategy chain to construct the build plan. + + + + + + Construct a build plan. + + The current build context. + The current build key. + The created build plan. + + + + A that generates IL to call + chosen methods (as specified by the current ) + as part of object build up. + + + + + Called during the chain of responsibility for a build operation. The + PreBuildUp method is called when the chain is being executed in the + forward direction. + + Context of the build operation. + + + + A helper method used by the generated IL to throw an exception + when an injection method parameter could not be resolved. + + Exception that provides the failure info. + Name of the method that was going to be called. + Parameter that failed to resolve. + + + + A that generates IL to resolve properties + on an object being built. + + + + + Called during the chain of responsibility for a build operation. + + The context for the operation. + + + + A helper method called by the generated IL to throw an exception if a property's + value cannot be resolved. + + The actual exception that caused the resolution to fail. + Name of the property that didn't resolve. + + + + An that will examine the given + types and return a sequence of objects + that should be called as part of building the object. + + + + + Return the sequence of methods to call while building the target object. + + Current build context. + Sequence of methods to call. + + + + An implementation of that selects + methods by looking for the given + attribute on those methods. + + Type of attribute used to mark methods + to inject. + + + + Base class that provides an implementation of + which lets you override how the parameter resolvers are created. + + Attribute that marks methods that should + be called. + + + + Return the sequence of methods to call while building the target object. + + Current build context. + Sequence of methods to call. + + + + Create a instance for the given + . + + Parameter to create the resolver for. + The resolver object. + + + + Create a instance for the given + . + + Parameter to create the resolver for. + The resolver object. + + + + Objects of this type are the return value from . + It encapsulates the desired with the string keys + needed to look up the for each + parameter. + + + + + Create a new instance which + contains the given method. + + The method + + + + The constructor this object wraps. + + + + + An that returns a sequence + of properties that should be injected for the given type. + + + + + Returns sequence of properties on the given type that + should be set as part of building that object. + + Current build context. + Sequence of objects + that contain the properties to set. + + + + Base class that provides an implementation of + which lets you override how the parameter resolvers are created. + + + + + Returns sequence of properties on the given type that + should be set as part of building that object. + + current build context. + Sequence of objects + that contain the properties to set. + + + + Create a for the given + property. + + Property to create resolver for. + The resolver object. + + + + An implementation of that looks + for properties marked with the + attribute that are also settable and not indexers. + + + + + + Create a for the given + property. + + Property to create resolver for. + The resolver object. + + + + Objects of this type are returned from + . + This class combines the about + the property with the string key used to look up the resolver + for this property's value. + + + + + Create an instance of + with the given and key. + + The property. + Key to use to look up the resolver. + + + + PropertyInfo for this property. + + + + + Key to look up this property's resolver. + + + + + Implementation of . + + + + + A builder policy that lets you keep track of the current + resolvers and will remove them from the given policy set. + + + + + Add a new resolver to track by key. + + Key that was used to add the resolver to the policy set. + + + + Remove the currently tracked resolvers from the given policy list. + + Policy list to remove the resolvers from. + + + + Add a new resolver to track by key. + + Key that was used to add the resolver to the policy set. + + + + Remove the currently tracked resolvers from the given policy list. + + Policy list to remove the resolvers from. + + + + Get an instance that implements , + either the current one in the policy set or creating a new one if it doesn't + exist. + + Policy list to look up from. + Build key to track. + The resolver tracker. + + + + Add a key to be tracked to the current tracker. + + Policy list containing the resolvers and trackers. + Build key for the resolvers being tracked. + Key for the resolver. + + + + Remove the resolvers for the given build key. + + Policy list containing the build key. + Build key. + + + + An implementation of that + calls back into the build chain to build up the dependency, passing + a type given at compile time as its build key. + + + + + A that is used at build plan execution time + to resolve a dependent value. + + + + + Get the value for a dependency. + + Current build context. + The value for the dependency. + + + + Create a new instance storing the given type. + + Type to resolve. + + + + Get the value for a dependency. + + Current build context. + The value for the dependency. + + + + A custom collection over objects. + + + + + Removes an individual policy type for a build key. + + The type the policy was registered as. + The key the policy applies. + + + + Removes an individual policy type for a build key. + + The type of policy to remove. + The key the policy applies. + + + + Removes all policies from the list. + + + + + Removes a default policy. + + The type the policy was registered as. + + + + Removes a default policy. + + The type the policy was registered as. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + The policy in the list, if present; returns null otherwise. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + The policy in the list, if present; returns null otherwise. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Get the non default policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Get the non default policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Sets an individual policy. + + The interface the policy is registered under. + The policy to be registered. + The key the policy applies. + + + + Sets an individual policy. + + The of the policy. + The policy to be registered. + The key the policy applies. + + + + Sets a default policy. When checking for a policy, if no specific individual policy + is available, the default will be used. + + The interface to register the policy under. + The default policy to be registered. + + + + Sets a default policy. When checking for a policy, if no specific individual policy + is available, the default will be used. + + The interface to register the policy under. + The default policy to be registered. + + + + This interface defines a standard method to convert any + regardless + of the stage enum into a regular, flat strategy chain. + + + + + Convert this into + a flat . + + The flattened . + + + + Represents a chain of responsibility for builder strategies. + + + + + Reverse the order of the strategy chain. + + The reversed strategy chain. + + + + Execute this strategy chain against the given context, + calling the Buildup methods on the strategies. + + Context for the build process. + The build up object + + + + Execute this strategy chain against the given context, + calling the TearDown methods on the strategies. + + Context for the teardown process. + + + + Represents a build key based on type. + + + + + Construct a new build key object with the current type + replaced with the specified . + + This method creates a new build key object, the original is unchanged. + New type to place in the build key. + The new build key. + + + + Gets the that represents the key. + + + The that represents the key. + + + + + Represents a lifetime container. + + + A lifetime container tracks the lifetime of an object, and implements + IDisposable. When the container is disposed, any objects in the + container which implement IDisposable are also disposed. + + + + + Adds an object to the lifetime container. + + The item to be added to the lifetime container. + + + + Determine if a given object is in the lifetime container. + + + The item to locate in the lifetime container. + + + Returns true if the object is contained in the lifetime + container; returns false otherwise. + + + + + Removes an item from the lifetime container. The item is + not disposed. + + The item to be removed. + + + + Gets the number of references in the lifetime container + + + The number of references in the lifetime container + + + + + Represents a lifetime container. + + + A lifetime container tracks the lifetime of an object, and implements + IDisposable. When the container is disposed, any objects in the + container which implement IDisposable are also disposed. + + + + + Adds an object to the lifetime container. + + The item to be added to the lifetime container. + + + + Determine if a given object is in the lifetime container. + + + The item to locate in the lifetime container. + + + Returns true if the object is contained in the lifetime + container; returns false otherwise. + + + + + Releases the resources used by the . + + + + + Releases the managed resources used by the DbDataReader and optionally releases the unmanaged resources. + + + true to release managed and unmanaged resources; false to release only unmanaged resources. + + + + + Returns an enumerator that iterates through the lifetime container. + + + An object that can be used to iterate through the life time container. + + + + + Returns an enumerator that iterates through the lifetime container. + + + An object that can be used to iterate through the life time container. + + + + + Removes an item from the lifetime container. The item is + not disposed. + + The item to be removed. + + + + Gets the number of references in the lifetime container + + + The number of references in the lifetime container + + + + + Represents a locator that can be read from. + + + A locator is a dictionary of keys to values, but it keeps the values with + weak references, so that locating an object does not keep it alive. If you + want to keep the object alive too, you should consider using an + . + Locators have a built-in concept of hierarchy, so you can ask questions + of a locator and tell it whether to return results from the current locator + only, or whether to ask the parent locator when local lookups fail. + + + + + Determine if the locator contains an object for the given key. + + The key to check. + + true if the locator contains an object for the key; returns + false otherwise. + + + + + Finds objects in the locator using the predicate, and returns a temporary locator + filled with the found objects. + + The predicate to test whether to include an object. + The new locator + Predicate is null. + + + + Gets an object from the locator, registered with the key of typeof(T). + + The type of the object to find. + The object, if found; null otherwise. + + + + Gets an object from the locator, registered with the given key. + + The type of the object to find. + The key that the object is registered with. + The object, if found; null otherwise. + Key is null. + + + + Gets an object from the locator, registered with the given key. + + The key that the object is registered with. + The object, if found; null otherwise. + Key is null. + + + + Gets the number of items in the locator. + + + The number of items in the locator. + + + + + Gets the parent locator. + + + The parent locator. + + + + + Determines if the locator is read-only. + + + true if the locator is read-only; otherwise, false. + + + + + Represents a locator that can be read from and written to. + + + + A locator is dictionary of keys to values, but it keeps the values with + weak references, so that locating an object does not keep it alive. If you + want to keep the object alive too, you should consider using an + . + + + Locators have a built-in concept of hierarchy, so you can ask questions + of a locator and tell it whether to return results from the current locator + only, or whether to ask the parent locator when local lookups fail. + + + + + Adds an object to the locator, with the given key. + + The key to register the object with. + The object to be registered. + or value are null. + + + + Removes an object from the locator. + + The key under which the object was registered. + + Returns true if the object was found in the locator; returns + false otherwise. + + is null. + + + + An implementation of and . + + + + + Represents an abstract implementation of . + + + + + Represents an abstract implementation of . + + + + + Initialize a new instance of the class. + + + + + Initialize a new instance of the class with a parent . + + A parent . + + + + Determine if the locator contains an object for the given key. + + The key to check. + + true if the locator contains an object for the key; returns + false otherwise. + + + + + Finds objects in the locator using the predicate, and returns a temporary locator + filled with the found objects. + + The predicate to test whether to include an object. + The new locator + Predicate is null. + + + + Gets an object from the locator, registered with the key of typeof(T). + + The type of the object to find. + The object, if found; null otherwise. + + + + Gets an object from the locator, registered with the given key. + + The type of the object to find. + The key that the object is registered with. + The object, if found; null otherwise. + is null. + + + + Gets an object from the locator, registered with the given key. + + The key that the object is registered with. + The object, if found; null otherwise. + Key is null. + + + + Returns an enumerator that iterates through the locator. + + + An object that can be used to iterate through the locator. + + + + + Returns an enumerator that iterates through the locator. + + + An object that can be used to iterate through the locator. + + + + + Gets the number of items in the locator. + + + The number of items in the locator. + + + + + Gets the parent locator. + + + The parent locator. + + + + + Determines if the locator is read-only. + + + true if the locator is read-only; otherwise, false. + + + + + Initialize a new instance of the class. + + + + + Initialize a new instance of the class with a parent . + + A parent . + + + + Adds an object to the locator, with the given key. + + The key to register the object with. + The object to be registered. + or value are null. + + + + Removes an object from the locator. + + The key under which the object was registered. + + Returns true if the object was found in the locator; returns + false otherwise. + + is null. + + + + Determines if the locator is read-only. + + + true if the locator is read-only; otherwise, false. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class as a child of the . + + The parent locator. + + + + Adds an object to the locator, with the given key. + + The key to register the object with. + The object to be registered. + Key or value are null. + + + + Determine if the locator contains an object for the given key. + + The key to check. + + true if the locator contains an object for the key; returns + false otherwise. + + + + + Gets an object from the locator, registered with the given key. + + The key that the object is registered with. + The object, if found; null otherwise. + Key is null. + + + + Returns an enumerator that iterates through a locator. + + + An object that can be used to iterate through the locator. + + + + + Removes an object from the locator. + + The key under which the object was registered. + + Returns true if the object was found in the locator; returns + false otherwise. + + Key is null. + + + + Gets the number of items in the locator. + + + The number of items in the locator. + + + + + An implementation of that wraps an existing locator + to ensure items are not written into the locator. + + + + + Initialize a new instance of the class with an to wrap. + + The inner locator to be wrapped. + + + + Determine if the locator contains an object for the given key. + + The key to check. + + true if the locator contains an object for the key; returns + false otherwise. + + + + + Gets an object from the locator, registered with the given key. + + The key that the object is registered with. + The object, if found; null otherwise. + Key is null. + + + + Returns an enumerator that iterates through the locator. + + + An object that can be used to iterate through the locator. + + + + + Gets the number of items in the locator. + + + The number of items in the locator. + + + + + Gets the parent locator. + + + The parent locator. + + + + + Determines if the locator is read-only. + + + true if the locator is read-only; otherwise, false. + + + + + A custom collection wrapper over objects. + + + + + Initialize a new instance of a class. + + + + + Initialize a new instance of a class with another policy list. + + An inner policy list to search. + + + + Removes an individual policy type for a build key. + + The type the policy was registered as. + The key the policy applies. + + + + Removes an individual policy type for a build key. + + The type of policy to remove. + The key the policy applies. + + + + Removes all policies from the list. + + + + + Removes a default policy. + + The type the policy was registered as. + + + + Removes a default policy. + + The type the policy was registered as. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + The policy in the list, if present; returns null otherwise. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + The policy in the list, if present; returns null otherwise. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Gets an individual policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Get the non default policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Get the non default policy. + + The interface the policy is registered under. + The key the policy applies. + true if the policy searches local only; otherwise false to seach up the parent chain. + The policy in the list, if present; returns null otherwise. + + + + Sets an individual policy. + + The interface the policy is registered under. + The policy to be registered. + The key the policy applies. + + + + Sets an individual policy. + + The of the policy. + The policy to be registered. + The key the policy applies. + + + + Sets a default policy. When checking for a policy, if no specific individual policy + is available, the default will be used. + + The interface to register the policy under. + The default policy to be registered. + + + + Sets a default policy. When checking for a policy, if no specific individual policy + is available, the default will be used. + + The interface to register the policy under. + The default policy to be registered. + + + + Gets the number of items in the locator. + + + The number of items in the locator. + + + + + A builder policy used to create lifetime policy instances. + Used by the LifetimeStrategy when instantiating open + generic types. + + + + + Create a new instance of . + + The new instance. + + + + A that controls how instances are + persisted and recovered from an external store. Used to implement + things like singletons and per-http-request lifetime. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object to store. + + + + Remove the value this lifetime policy is managing from backing store. + + + + + An implementation that uses + a to figure out if an object + has already been created and to update or remove that + object from some backing store. + + + + + Called during the chain of responsibility for a build operation. The + PreBuildUp method is called when the chain is being executed in the + forward direction. + + Context of the build operation. + + + + Called during the chain of responsibility for a build operation. The + PostBuildUp method is called when the chain has finished the PreBuildUp + phase and executes in reverse order from the PreBuildUp calls. + + Context of the build operation. + + + + A that stores objects in the locator and + lifetime container provided by the context. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + + + + Remove the given object from backing store. + + + + + A method that does whatever is needed to clean up + as part of cleaning up after an exception. + + + Don't do anything that could throw in this method, + it will cause later recover operations to get skipped + and play real havok with the stack trace. + + + + + An implementation of that does nothing, + ensuring that a new object gets created every time. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + + + + Remove the given object from backing store. + + + + + Represents a chain of responsibility for builder strategies partitioned by stages. + + The stage enumeration to partition the strategies. + + + + Initialize a new instance of the class. + + + + + Initialize a new instance of the class with an inner strategy chain to use when building. + + The inner strategy chain to use first when finding strategies in the build operation. + + + + Adds a strategy to the chain at a particular stage. + + The strategy to add to the chain. + The stage to add the strategy. + + + + Add a new strategy for the . + + The of + The stage to add the strategy. + + + + Clear the current strategy chain list. + + + This will not clear the inner strategy chain if this instane was created with one. + + + + + Makes a strategy chain based on this instance. + + A new . + + + + Represents a chain of responsibility for builder strategies. + + + + + Initialzie a new instance of the class. + + + + + Initialzie a new instance of the class with a colleciton of strategies. + + A collection of strategies to initialize the chain. + + + + Adds a strategy to the chain. + + The strategy to add to the chain. + + + + Adds strategies to the chain. + + The strategies to add to the chain. + + + + Reverse the order of the strategy chain. + + The reversed strategy chain. + + + + Execute this strategy chain against the given context to build up. + + Context for the build processes. + The build up object + + + + Execute this strategy chain against the given context, + calling the TearDown methods on the strategies. + + Context for the teardown process. + + + + Returns an enumerator that iterates through the collection. + + + + A that can be used to iterate through the collection. + + 1 + + + + Returns an enumerator that iterates through a collection. + + + + An object that can be used to iterate through the collection. + + 2 + + + + Utility methods for dealing with arbitrary build key objects. + + + + + Gets the of object to build from the build key. + + The build key to get the . + The of object to build from the key. + + + + Tries to get the from . + + The build key to get the . + + true if the was found; otherwise, false. + + + + Given a , return a new build key + which is the same as the original, except that the type has + been replaced with . + + original build key + New type to put in new build key. + The new build key. + + + + Represents a simple class for validating parameters and throwing exceptions. + + + + + Validates is not null and throws if it is null. + + The value to validate. + The name of . + + + + Validates is not null or an empty string and throws if it is null or an empty string . + + The value to validate. + The name of . + + + + Represents a dictionary which stores the values as weak references instead of strong + references. Null values are supported. + + The key type + The value type + + + + Gets the count of the number of items in the dictionary. + + + The count of the number of items in the dictionary. + + + Since the items in the dictionary are held by weak reference, the count value + cannot be relied upon to guarantee the number of objects that would be discovered via + enumeration. Treat the Count as an estimate only. + + + + + Determines if the dictionary contains a value for the key. + + The key to look for. + true if the key is contained in the dictionary; otherwise, false. + + + + Returns an enumerator that iterates through the dictionary. + + + An object that can be used to iterate through the dictionary. + + + + + Removes an item from the dictionary. + + The key of the item to be removed. + Returns true if the key was in the dictionary; return false otherwise. + + + + Attempts to get a value from the dictionary. + + The key + The value + Returns true if the value was present; false otherwise. + + + + Returns a count of the number of items in the dictionary. + + + Since the items in the dictionary are held by weak reference, the count value + cannot be relied upon to guarantee the number of objects that would be discovered via + enumeration. Treat the Count as an estimate only. + + + + + Retrieves a value from the dictionary. + + The key to look for. + The value in the dictionary. + Thrown when the key does exist in the dictionary. + Since the dictionary contains weak references, the key may have been removed by the + garbage collection of the object. + + + + The exception thrown when injection is attempted on a method + that is an open generic or has out or ref params. + + + The exception thrown when injection is attempted on a method + that is an open generic or has out or ref params. + + + + + Construct a new with no + message. + + + + + Construct a with the given message + + Message to return. + + + + Construct a with the given message + and inner exception. + + Message to return. + Inner exception + + + + Used for serialization. + + Serialization info. + Serialization context. + + + + Build key used to combine a type object with a string name. Used by + ObjectBuilder to indicate exactly what is being built. + + + + + Create a new instance with the given + type and name. + + to build. + Key to use to look up type mappings and singletons. + + + + Create a new instance for the default + buildup of the given type. + + to build. + + + + This helper method creates a new instance. It is + initialized for the default key for the given type. + + Type to build. + A new instance. + + + + This helper method creates a new instance for + the given type and key. + + Type to build + Key to use to look up type mappings and singletons. + A new instance initialized with the given type and name. + + + + Construct a new build key object with the current type + replaced with the specified . + + This method creates a new build key object, the original is unchanged. + New type to place in the build key. + The new build key. + + + + Compare two instances. + + Two instances compare equal + if they contain the same name and the same type. Also, comparing + against a different type will also return false. + Object to compare to. + True if the two keys are equal, false if not. + + + + Calculate a hash code for this instance. + + A hash code. + + + + Compare two instances for equality. + + Two instances compare equal + if they contain the same name and the same type. + First of the two keys to compare. + Second of the two keys to compare. + True if the values of the keys are the same, else false. + + + + Compare two instances for inequality. + + Two instances compare equal + if they contain the same name and the same type. If either field differs + the keys are not equal. + First of the two keys to compare. + Second of the two keys to compare. + false if the values of the keys are the same, else true. + + + + Formats the build key as a string (primarily for debugging). + + A readable string representation of the build key. + + + + Return the stored in this build key. + + The type to build. + + + + Returns the name stored in this build key. + + The name to use when building. + + + + A series of helper methods to deal with sequences - + objects that implement . + + LINQ in C# 3.0 does pretty much the same stuff, + but we're keeping C# 2.0 compatibility here. + + + + Given an , return a + new containing the same contents. + + Type of item store in the sequence. + Sequence to create list from. + The new + + + + Given an return a new + that contains + all the objects in that + are castable to . + + Desired type for objects. + Input sequence. + New output sequence. + + + + A function that turns an arbitrary parameter list into an + . + + Type of arguments. + The items to put into the collection. + An array that contains the values of the . + + + + Create an array containing the elements of the given sequence. + + Type of sequence and array. + Input sequence. + The resulting array. + + + + Given a sequence of , returns a sequence + containing those elements that satisfy the given predicate . + + Type of items in the sequence. + Source sequence. + Predicate used to test which items match. + The sequence of items that satify . This + sequence may be empty. + + + + Tests the given , returning true if any + element in satisfies the given predicate. + + Type of elements in sequence. + Sequence to test. + Predicate to use to test for existence. + true if any elements satify pred, false if not. + + + + Tests the given , returning true only if all + elements in satisfies the given predicate. + + Type of elements in sequence. + Sequence to test. + Predicate to use to test. + true if all elements satify pred, false if not. + + + + Given a sequence of , returns a sequence of + created by running the items in + through . + + Type of items in input. + Type of items in output. + Input sequence. + Mapping function. + The converted output sequence. + + + + Run a functional Reduce operation. See other methods for examples. + + Type of inputs. + Type of final output. + Sequence of input items. + Initial value for accumulator. + Reduce function. + + + + + Convert the given sequence to a single string. The items in the string are + separated by the given separator, and each object is converted to a string + using the method given. + + Type of input sequence. + Input sequence. + Separator string. + Function to convert instances to + strings. + The collected string. + + + + Convert the given sequence to a single string. The items in the string are separated + by the given separator, and each object is converted to a string by calling its + method. + + Type of input sequence. + Input sequence. + Separator string. + The collected string. + + + + Return the first item in the given sequence. + + Thrown if the sequence is empty. + Type of items in the sequence. + The sequence. + First item in the sequence. + + + + Execute the given action delegate for each item in the sequence. + + Type of item in the sequence. + The sequence of items. + Action to perform on each item. + + + + Concatenate multiple sequences into a single one. + + Type of sequences in the sequence. + The sequences to combine. + The combined sequence. + + + + A delegate that defines the function passed to the methods. + + Type of item being reduced. + Type of the accumulator object. + Current item to process. + Current value of the accumulator. + + + + + Static class containing constructor methods for + instances of , so that we + get type inference. + + + + + Make a new instance of that wraps + the given items. + + Type of items in the sequence. + Items in the sequence. + The sequence. + + + + Make a new instance of that wraps + the given items. + + Type of items in the sequence. + Items in the sequence. + The sequence. + + + + And another helper class that makes it possible to chain sequence operations together. + + Type of item contained in the sequence. + + + + Create a new instance wrapping the given IEnumerable. + + The sequence to wrap. + + + + Returns an enumerator that iterates through a collection. + + + An object that can be used to iterate through the collection. + + 2 + + + + Returns an enumerator that iterates through the collection. + + + A that can be used to iterate through the collection. + + 1 + + + + Given a sequence object, return a list containing those items. + + The materialized list. + + + + Return an array with the same contents as this sequence. + + The materialized array. + + + + Returns new sequence containing only the items for which the predicate is true. + + Test to indicate sequence inclusion + New sequence. + + + + Tests the sequence, returning true if any + element satisfies the given predicate. + + Predicate to use to test for existence. + true if any elements satify pred, false if not. + + + + Tests the sequence, returning true only if all + elements satisfy the given predicate. + + Predicate to use to test. + true if all elements satify pred, false if not. + + + + Return a new sequence consisting of the result of running each element through + the given . + + Desired output type. + Converter delegate. + New Sequence + + + + Run a functional Reduce operation. See other methods for examples. + + Type of final output. + Initial value for accumulator. + Reduce function. + + + + + Convert the given sequence to a single string. The items in the string are + separated by the given separator, and each object is converted to a string + using the method given. + + Separator string. + Function to convert instances to + strings. + The collected string. + + + + Convert the given sequence to a single string. The items in the string are separated + by the given separator, and each object is converted to a string by calling its + method. + + Separator string. + The collected string. + + + + Return the first item in the given sequence. + + Thrown if the sequence is empty. + First item in the sequence. + + + + Execute the given action delegate for each item in the sequence. + + Action to perform on each item. + + + + Concatenate multiple sequences with this one to return a single + sequence containing all items. + + Sequences to combine. + The combined sequence. + + + diff --git a/SharedLibs/Microsoft.Practices.Unity.xml b/SharedLibs/Microsoft.Practices.Unity.xml index 80143dde..baef93e2 100644 --- a/SharedLibs/Microsoft.Practices.Unity.xml +++ b/SharedLibs/Microsoft.Practices.Unity.xml @@ -1,2977 +1,2977 @@ - - - - Microsoft.Practices.Unity - - - - - Base class for attributes that can be placed on parameters - or properties to specify how to resolve the value for - that parameter or property. - - - - - Create an instance of that - will be used to get the value for the member this attribute is - applied to. - - Type of parameter or property that - this attribute is decoration. - The resolver object. - - - - This attribute is used to indicate which constructor to choose when - the container attempts to build a type. - - - - - This attribute is used to mark methods that should be called when - the container is building an object. - - - - - This attribute is used to mark properties and parameters as targets for injection. - - - For properties, this attribute is necessary for injection to happen. For parameters, - it's not needed unless you want to specify additional information to control how - the parameter is resolved. - - - - - Create an instance of with no name. - - - - - Create an instance of with the given name. - - Name to use when resolving this dependency. - - - - Create an instance of that - will be used to get the value for the member this attribute is - applied to. - - Type of parameter or property that - this attribute is decoration. - The resolver object. - - - - The name specified in the constructor. - - - - - This extension installs the default strategies and policies into the container - to implement the standard behavior of the Unity container. - - - This extension installs the default strategies and policies into the container - to implement the standard behavior of the Unity container. - - - - - Base class for all extension objects. - - - - - Base interface for all extension configuration interfaces. - - - - - Retrieve the container instance that we are currently configuring. - - - - - The container calls this method when the extension is added. - - A instance that gives the - extension access to the internals of the container. - - - - Initial the container with this extension's functionality. - - - When overridden in a derived class, this method will modify the given - by adding strategies, policies, etc. to - install it's functions into the container. - - - - Removes the extension's functions from the container. - - - - This method is called when extensions are being removed from the container. It can be - used to do things like disconnect event handlers or clean up member state. You do not - need to remove strategies or policies here; the container will do that automatically. - - - The default implementation of this method does nothing. - - - - - The container this extension has been added to. - - The that this extension has been added to. - - - - The object used to manipulate - the inner state of the container. - - - - - Add the correct to the policy - set. This version adds the appropriate policy for running on the desktop CLR. - - - - - Add the default ObjectBuilder strategies & policies to the container. - - - - - The class provides the means for extension objects - to manipulate the internal state of the . - - - - - Store a type/name pair for later resolution. - - - - When users register type mappings (or other things) with a named key, this method - allows you to register that name with the container so that when the - method is called, that name is included in the list that is returned. - - to register. - Name assocated with that type. - - - - The container that this context is associated with. - - The object. - - - - The strategies this container uses. - - The that the container uses to build objects. - - - - The strategies this container uses to construct build plans. - - The that this container uses when creating - build plans. - - - - The policies this container uses. - - The the that container uses to build objects. - - - - The that this container uses. - - The Locator is an object that is used to store information to be found later during the build process. - - - - The that this container uses. - - The is used to manage objects that the container is managing. - - - - This event is raised when the method, - or one of its overloads, is called. - - - - - This event is raised when the method, - or one of its overloads, is called. - - - - - An EventArgs class that holds a string Name. - - - - - Create a new with a null name. - - - - - Create a new with the given name. - - Name to store. - - - - The name. - - Name used for this event arg object. - - - - Event argument class for the event. - - - - - Create a new instance of . - - Type to map from. - Type to map to. - Name for the registration. - to manage instances. - - - - Type to map from. - - - - - Type to map to. - - - - - to manage instances. - - - - - Event argument class for the event. - - - - - Create a default instance. - - - - - Create a instance initialized with the given arguments. - - Type of instance being registered. - The instance object itself. - Name to register under, null if default registration. - object that handles how - the instance will be owned. - - - - Type of instance being registered. - - - Type of instance being registered. - - - - - Instance object being registered. - - Instance object being registered - - - - that controls ownership of - this instance. - - - - - A that lets you specify that - an instance of a generic type parameter should be resolved. - - - - - Base type for objects that are used to configure parameters for - constructor or method injection, or for getting the value to - be injected into a property. - - - - - Test to see if this parameter value has a matching type for the given type. - - Type to check. - True if this parameter value is compatible with type , - false if not. - - - - Return a instance that will - return this types value for the parameter. - - Type that contains the member that needs this parameter. Used - to resolve open generic parameters. - The . - - - - Convert the given set of arbitrary values to a sequence of InjectionParameterValue - objects. The rules are: If it's already an InjectionParameterValue, return it. If - it's a Type, return a ResolvedParameter object for that type. Otherwise return - an InjectionParameter object for that value. - - The values to build the sequence from. - The resulting converted sequence. - - - - Convert an arbitrary value to an InjectionParameterValue object. The rules are: - If it's already an InjectionParameterValue, return it. If it's a Type, return a - ResolvedParameter object for that type. Otherwise return an InjectionParameter - object for that value. - - The value to convert. - The resulting . - - - - Name for the type represented by this . - This may be an actual type name or a generic argument name. - - - - - Create a new instance that specifies - that the given named generic parameter should be resolved. - - The generic parameter name to resolve. - - - - Create a new instance that specifies - that the given named generic parameter should be resolved. - - The generic parameter name to resolve. - name to use when looking up in the container. - - - - Test to see if this parameter value has a matching type for the given type. - - Type to check. - True if this parameter value is compatible with type , - false if not. - - - - Return a instance that will - return this types value for the parameter. - - Type that contains the member that needs this parameter. Used - to resolve open generic parameters. - The . - - - - Name for the type represented by this . - This may be an actual type name or a generic argument name. - - - - - A that lets you specify that - an array containing the registered instances of a generic type parameter - should be resolved. - - - - - Create a new instance that specifies - that the given named generic parameter should be resolved. - - The generic parameter name to resolve. - The values for the elements, that will - be converted to objects. - - - - Test to see if this parameter value has a matching type for the given type. - - Type to check. - True if this parameter value is compatible with type , - false if not. - A type is considered compatible if it is an array type of rank one - and its element type is a generic type parameter with a name matching this generic - parameter name configured for the receiver. - - - - Return a instance that will - return this types value for the parameter. - - Type that contains the member that needs this parameter. Used - to resolve open generic parameters. - The . - - - - Name for the type represented by this . - This may be an actual type name or a generic argument name. - - - - - A Unity container extension that allows you to configure - which constructors, properties, and methods get injected - via an API rather than through attributes. - - - - - Initial the container with this extension's functionality. - - - When overridden in a derived class, this method will modify the given - by adding strategies, policies, etc. to - install it's functions into the container. - - - - API to configure the injection settings for a particular type. - - Type the injection is being configured for. - Objects containing the details on which members to inject and how. - This extension object. - - - - API to configure the injection settings for a particular type/name pair. - - Type the injection is being configured for. - Name of registration - Objects containing the details on which members to inject and how. - This extension object. - - - - API to configure the injection settings for a particular type. - - Type to configure. - Objects containing the details on which members to inject and how. - This extension object. - - - - API to configure the injection settings for a particular type/name pair. - - Type to configure. - Name of registration. - Objects containing the details on which members to inject and how. - This extension object. - - - - Remove policies associated with building this type. This removes the - compiled build plan so that it can be rebuilt with the new settings - the next time this type is resolved. - - Type of object to clear the plan for. - Name the object is being registered with. - - - - A class that holds the collection of information - for a constructor, so that the container can - be configured to call this constructor. - - - - - Base class for objects that can be used to configure what - class members get injected by the container. - - - - - Add policies to the to configure the - container to call this constructor with the appropriate parameter values. - - Type to register. - Policy list to add policies to. - - - - Add policies to the to configure the - container to call this constructor with the appropriate parameter values. - - Type to register. - Name used to resolve the type object. - Policy list to add policies to. - - - - Create a new instance of that looks - for a constructor with the given set of parameters. - - The values for the parameters, that will - be converted to objects. - - - - Add policies to the to configure the - container to call this constructor with the appropriate parameter values. - - Type to register. - Name used to resolve the type object. - Policy list to add policies to. - - - - An that configures the - container to call a method as part of buildup. - - - - - Create a new instance which will configure - the container to call the given methods with the given parameters. - - Name of the method to call. - Parameter values for the method. - - - - Add policies to the to configure the - container to call this constructor with the appropriate parameter values. - - Type to register. - Name used to resolve the type object. - Policy list to add policies to. - - - - A small function to handle name matching. You can override this - to do things like case insensitive comparisons. - - MethodInfo for the method you're checking. - Name of the method you're looking for. - True if a match, false if not. - - - - A class that holds on to the given value and provides - the required - when the container is configured. - - - - - A base class for implementing classes - that deal in explicit types. - - - - - Create a new that exposes - information about the given . - - Type of the parameter. - - - - Test to see if this parameter value has a matching type for the given type. - - Type to check. - True if this parameter value is compatible with type , - false if not. - - - - The type of parameter this object represents. - - - - - Name for the type represented by this . - This may be an actual type name or a generic argument name. - - - - - Create an instance of that stores - the given value, using the runtime type of that value as the - type of the parameter. - - Value to be injected for this parameter. - - - - Create an instance of that stores - the given value, associated with the given type. - - Type of the parameter. - Value of the parameter - - - - Return a instance that will - return this types value for the parameter. - - Type that contains the member that needs this parameter. Used - to resolve open generic parameters. - The . - - - - A generic version of that makes it a - little easier to specify the type of the parameter. - - Type of parameter. - - - - Create a new . - - Value for the parameter. - - - - This class stores information about which properties to inject, - and will configure the container accordingly. - - - - - Configure the container to inject the given property name, - resolving the value via the container. - - Name of the property to inject. - - - - Configure the container to inject the given property name, - using the value supplied. This value is converted to an - object using the - rules defined by the - method. - - Name of property to inject. - Value for property. - - - - Add policies to the to configure the - container to call this constructor with the appropriate parameter values. - - Type to register. - Name used to resolve the type object. - Policy list to add policies to. - - - - A class that stores a type, and generates a - resolver object that resolves all the named instances or the - type registered in a container. - - - - - Construct a new that - resolves to the given element type and collection of element values. - - The type of elements to resolve. - The values for the elements, that will - be converted to objects. - - - - Construct a new that - resolves to the given array and element types and collection of element values. - - The type for the array of elements to resolve. - The type of elements to resolve. - The values for the elements, that will - be converted to objects. - - - - Return a instance that will - return this types value for the parameter. - - Type that contains the member that needs this parameter. Used - to resolve open generic parameters. - The . - - - - A generic version of for convenience - when creating them by hand. - - Type of the elements for the array of the parameter. - - - - Construct a new that - resolves to the given element generic type with the given element values. - - The values for the elements, that will - be converted to objects. - - - - Interface defining the behavior of the Unity dependency injection container. - - - - - Register a type with specific members to be injected. - - Type this registration is for. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container. - - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - - This overload registers a default mapping and transient lifetime. - - - that will be requested. - that will actually be returned. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container. - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - that will be requested. - that will actually be returned. - Name of this mapping. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type with the container. - No type mapping is performed for this type. - - The type to apply the to. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type with the container. - No type mapping is performed for this type. - - The type to configure injection on. - Name that will be used to request the type. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type and name with the container. - No type mapping is performed for this type. - - The type to apply the to. - Name that will be used to request the type. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type with specific members to be injected. - - Type this registration is for. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container. - - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - - This overload registers a default mapping. - - - that will be requested. - that will actually be returned. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container. - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type and name with the container. - No type mapping is performed for this type. - - The to apply the to. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type and name with the container. - No type mapping is performed for this type. - - The to configure in the container. - Name to use for registration, null if a default registration. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type and name with the container. - No type mapping is performed for this type. - - The to apply the to. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration and has the container take over the lifetime of the instance. - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration (name = null). - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload automatically has the container take ownership of the . - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration and has the container take over the lifetime of the instance. - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration (name = null). - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload automatically has the container take ownership of the . - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Resolve an instance of the default requested type from the container. - - of object to get from the container. - The retrieved object. - - - - Resolve an instance of the requested type with the given name from the container. - - of object to get from the container. - Name of the object to retrieve. - The retrieved object. - - - - Resolve an instance of the default requested type from the container. - - of object to get from the container. - The retrieved object. - - - - Resolve an instance of the requested type with the given name from the container. - - of object to get from the container. - Name of the object to retrieve. - The retrieved object. - - - - Return instances of all registered types requested. - - - - This method is useful if you've registered multiple types with the same - but different names. - - - Be aware that this method does NOT return an instance for the default (unnamed) registration. - - - The type requested. - Set of objects of type . - - - - Return instances of all registered types requested. - - - - This method is useful if you've registered multiple types with the same - but different names. - - - Be aware that this method does NOT return an instance for the default (unnamed) registration. - - - The type requested. - Set of objects of type . - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - - This overload uses the default registrations. - - - of object to perform injection on. - Instance to build up. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - of object to perform injection on. - Instance to build up. - name to use when looking up the typemappings and other configurations. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - - This overload uses the default registrations. - - - of object to perform injection on. - Instance to build up. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - of object to perform injection on. - Instance to build up. - name to use when looking up the typemappings and other configurations. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container, and clean it up. - - The object to tear down. - - - - Add an extension object to the container. - - to add. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Creates a new extension object and adds it to the container. - - Type of to add. The extension type - must have a zero-argument public constructor. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Resolve access to a configuration interface exposed by an extension. - - Extensions can expose configuration interfaces as well as adding - strategies and policies to the container. This method walks the list of - added extensions and returns the first one that implements the requested type. - - The configuration interface required. - The requested extension's configuration interface, or null if not found. - - - - Resolve access to a configuration interface exposed by an extension. - - Extensions can expose configuration interfaces as well as adding - strategies and policies to the container. This method walks the list of - added extensions and returns the first one that implements the requested type. - - of configuration interface required. - The requested extension's configuration interface, or null if not found. - - - - Remove all installed extensions from this container. - - - - This method removes all extensions from the container, including the default ones - that implement the out-of-the-box behavior. After this method, if you want to use - the container again you will need to either readd the default extensions or replace - them with your own. - - - The registered instances and singletons that have already been set up in this container - do not get removed. - - - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Create a child container. - - - A child container shares the parent's configuration, but can be configured with different - settings or lifetime. - The new child container. - - - - The parent of this container. - - The parent container, or null if this container doesn't have one. - - - - A that holds onto the instance given to it. - When the is disposed, - the instance is disposed with it. - - - - - Base class for Lifetime managers which need to synchronize calls to - . - - - - The purpose of this class is to provide a basic implementation of the lifetime manager synchronization pattern. - - - Calls to the method of a - instance acquire a lock, and if the instance has not been initialized with a value yet the lock will only be released - when such an initialization takes place by calling the method or if - the build request which resulted in the call to the GetValue method fails. - - - - - - - Base class for Lifetime managers - classes that control how - and when instances are created by the Unity container. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - - - - Remove the given object from backing store. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - Calls to this method acquire a lock which is released only if a non-null value - has been set for the lifetime manager. - - - - Performs the actual retrieval of a value from the backing store associated - with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - This method is invoked by - after it has acquired its lock. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - Setting a value will attempt to release the lock acquired by - . - - - - Performs the actual storage of the given value into backing store for retrieval later. - - The object being stored. - This method is invoked by - before releasing its lock. - - - - Remove the given object from backing store. - - - - - A method that does whatever is needed to clean up - as part of cleaning up after an exception. - - - Don't do anything that could throw in this method, - it will cause later recover operations to get skipped - and play real havok with the stack trace. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - - - - Remove the given object from backing store. - - - - - Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - - 2 - - - - Standard Dispose pattern implementation. Not needed, but it keeps FxCop happy. - - Always true, since we don't have a finalizer. - - - - A that holds a weak reference to - it's managed instance. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - - - - Remove the given object from backing store. - - - - - An implementation of that - creates instances of the type of the given Lifetime Manager - by resolving them through the container. - - - - - Create a new that will - return instances of the given type, creating them by - resolving through the container. - - Container to resolve with. - Type of LifetimeManager to create. - - - - Create a new instance of . - - The new instance. - - - - A that holds the instances given to it, - keeping one instance per thread. - - - - This LifetimeManager does not dispose the instances it holds. - - - - - - Initializes a new instance of the class. - - - - - Retrieve a value from the backing store associated with this Lifetime policy for the - current thread. - - the object desired, or if no such object is currently - stored for the current thread. - - - - Stores the given value into backing store for retrieval later when requested - in the current thread. - - The object being stored. - - - - Remove the given object from backing store. - - Not implemented for this lifetime manager. - - - - An implementation that does nothing, - thus ensuring that instances are created new every time. - - - - - Retrieve a value from the backing store associated with this Lifetime policy. - - the object desired, or null if no such object is currently stored. - - - - Stores the given value into backing store for retrieval later. - - The object being stored. - - - - Remove the given object from backing store. - - - - - This strategy implements the logic that will call container.ResolveAll - when an array parameter is detected. - - - - - Do the PreBuildUp stage of construction. This is where the actual work is performed. - - Current build context. - - - - An implementation of that is - aware of the build keys used by the Unity container. - - - - - Create a instance for the given - . - - - This implementation looks for the Unity on the - parameter and uses it to create an instance of - for this parameter. - Parameter to create the resolver for. - The resolver object. - - - - An implementation of that is aware - of the build keys used by the Unity container. - - - - - Create a instance for the given - . - - Parameter to create the resolver for. - The resolver object. - - - - An implementation of that is aware of - the build keys used by the unity container. - - - - - Create a for the given - property. - - Property to create resolver for. - The resolver object. - - - - A implementation that returns - the value set in the constructor. - - - - - Create a new instance of - which will return the given value when resolved. - - The value to return. - - - - Get the value for a dependency. - - Current build context. - The value for the dependency. - - - - An implementation of that stores a - type and name, and at resolution time puts them together into a - . - - - - - Create an instance of - with the given type and name. - - The type. - The name (may be null). - - - - Resolve the value for a dependency. - - Current build context. - The value for the dependency. - - - - The type that this resolver resolves. - - - - - The name that this resolver resolves. - - - - - An implementation of that resolves to - to an array populated with the values that result from resolving other instances - of . - - - - - Create an instance of - with the given type and a collection of - instances to use when populating the result. - - The type. - The resolver policies to use when populating an array. - - - - Resolve the value for a dependency. - - Current build context. - An array pupulated with the results of resolving the resolver policies. - - - - An implementation of that selects - the given constructor and creates the appropriate resolvers to call it with - the specified parameters. - - - - - Create an instance of that - will return the given constructor, being passed the given injection values - as parameters. - - The constructor to call. - Set of objects - that describes how to obtain the values for the constructor parameters. - - - - Choose the constructor to call for the given type. - - Current build context - The chosen constructor. - - - - Helper class for implementing selector policies that need to - set up dependency resolver policies. - - - - - Add dependency resolvers to the parameter set. - - Type that's currently being built (used to resolve open generics). - PolicyList to add the resolvers to. - Objects supplying the dependency resolvers. - Result object to store the keys in. - - - - A implementation that calls the specific - methods with the given parameters. - - - - - Add the given method and parameter collection to the list of methods - that will be returned when the selector's - method is called. - - Method to call. - sequence of objects - that describe how to create the method parameter values. - - - - Return the sequence of methods to call while building the target object. - - Current build context. - Sequence of methods to call. - - - - An implemnetation of which returns - the set of specific properties that the selector was configured with. - - - - - Add a property that will be par of the set returned when the - is called. - - The property to set. - object describing - how to create the value to inject. - - - - Returns sequence of properties on the given type that - should be set as part of building that object. - - Current build context. - Sequence of objects - that contain the properties to set. - - - - The exception thrown by the Unity container when - an attempt to resolve a dependency fails. - - - - - Create a new that records - the exception for the given type and name. - - Type requested from the container. - Name requested from the container. - The actual exception that caused the failure of the build. - - - - Constructor to create a from serialized state. - - Serialization info - Serialization context - - - - Serialize this object into the given context. - - Serialization info - Streaming context - - - - The type that was being requested from the container at the time of failure. - - - - - The name that was being requested from the container at the time of failure. - - - - - A class that stores a name and type, and generates a - resolver object that resolves the parameter via the - container. - - - - - Construct a new that - resolves to the given type. - - Type of this parameter. - - - - Construct a new that - resolves the given type and name. - - Type of this parameter. - Name to use when resolving parameter. - - - - Return a instance that will - return this types value for the parameter. - - Type that contains the member that needs this parameter. Used - to resolve open generic parameters. - The . - - - - A generic version of for convenience - when creating them by hand. - - Type of the parameter - - - - Create a new for the given - generic type and the default name. - - - - - Create a new for the given - generic type and name. - - Name to use to resolve this parameter. - - - - A base class for implmenting that provides - reasonable implementations for most of the overloads defined by the interface. - The overloads all call down to the non-generic versions of the methods with - the most parameters. - - - - - Register a type with specific members to be injected. - - Type this registration is for. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container. - - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - - This overload registers a default mapping. - - - that will be requested. - that will actually be returned. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container. - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - that will be requested. - that will actually be returned. - - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a for the given type with the container. - No type mapping is performed for this type. - - The type to apply the to. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type with the container. - No type mapping is performed for this type. - - The type to configure injection on. - Name that will be used to request the type. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a for the given type and name with the container. - No type mapping is performed for this type. - - The type to apply the to. - Name that will be used to request the type. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a type with specific members to be injected. - - Type this registration is for. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container. - - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - - This overload registers a default mapping. - - - that will be requested. - that will actually be returned. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a for the given type and name with the container. - No type mapping is performed for this type. - - The to apply the to. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Register a for the given type and name with the container. - No type mapping is performed for this type. - - The to configure in the container. - Name to use for registration, null if a default registration. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a for the given type and name with the container. - No type mapping is performed for this type. - - The to apply the to. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container. - - - This method is used to tell the container that when asked for type , - actually return an instance of type . This is very useful for - getting instances of interfaces. - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration and has the container take over the lifetime of the instance. - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration (name = null). - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload automatically has the container take ownership of the . - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration and has the container take over the lifetime of the instance. - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload does a default registration (name = null). - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - - object that controls how this instance will be managed by the container. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - This overload automatically has the container take ownership of the . - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - - If true, the container will take over the lifetime of the instance, - calling Dispose on it (if it's ) when the container is Disposed. - - If false, container will not maintain a strong reference to . User is reponsible - for disposing instance, and for keeping the instance from being garbage collected. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Get an instance of the default requested type from the container. - - of object to get from the container. - The retrieved object. - - - - Get an instance of the requested type with the given name from the container. - - of object to get from the container. - Name of the object to retrieve. - The retrieved object. - - - - Get an instance of the default requested type from the container. - - of object to get from the container. - The retrieved object. - - - - Get an instance of the requested type with the given name from the container. - - of object to get from the container. - Name of the object to retrieve. - The retrieved object. - - - - Return instances of all registered types requested. - - - - This method is useful if you've registered multiple types with the same - but different names. - - - Be aware that this method does NOT return an instance for the default (unnamed) registration. - - - The type requested. - Set of objects of type . - - - - Return instances of all registered types requested. - - - - This method is useful if you've registered multiple types with the same - but different names. - - - Be aware that this method does NOT return an instance for the default (unnamed) registration. - - - The type requested. - Set of objects of type . - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - - This overload uses the default registrations. - - - of object to perform injection on. - Instance to build up. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - of object to perform injection on. - Instance to build up. - name to use when looking up the typemappings and other configurations. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - - This overload uses the default registrations. - - - of object to perform injection on. - Instance to build up. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - of object to perform injection on. - Instance to build up. - name to use when looking up the typemappings and other configurations. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container, and clean it up. - - The object to tear down. - - - - Add an extension object to the container. - - to add. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Creates a new extension object and adds it to the container. - - Type of to add. The extension type - must have a zero-argument public constructor. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Get access to a configuration interface exposed by an extension. - - Extensions can expose configuration interfaces as well as adding - strategies and policies to the container. This method walks the list of - added extensions and returns the first one that implements the requested type. - - The configuration interface required. - The requested extension's configuration interface, or null if not found. - - - - Get access to a configuration interface exposed by an extension. - - Extensions can expose configuration interfaces as well as adding - strategies and policies to the container. This method walks the list of - added extensions and returns the first one that implements the requested type. - - of configuration interface required. - The requested extension's configuration interface, or null if not found. - - - - Remove all installed extensions from this container. - - - - This method removes all extensions from the container, including the default ones - that implement the out-of-the-box behavior. After this method, if you want to use - the container again you will need to either readd the default extensions or replace - them with your own. - - - The registered instances and singletons that have already been set up in this container - do not get removed. - - - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Create a child container. - - - A child container shares the parent's configuration, but can be configured with different - settings or lifetime. - The new child container. - - - - Dispose this container instance. - - - Disposing the container also disposes any child containers, - and disposes any instances whose lifetimes are managed - by the container. - - - - - The parent of this container. - - The parent container, or null if this container doesn't have one. - - - - A static helper class that includes various parameter checking routines. - - - - - Throws if the given argument is null. - - if tested value if null. - Argument value to test. - Name of the argument being tested. - - - - Throws an exception if the tested string argument is null or the empty string. - - Thrown if string value is null. - Thrown if the string is empty - Argument value to check. - Name of argument being checked. - - - - Verifies that an argument type is assignable from the provided type (meaning - interfaces are implemented, or classes exist in the base class hierarchy). - - The argument type that will be assigned to. - The type of the value being assigned. - Argument name. - - - - The build stages we use in the Unity container - strategy pipeline. - - - - - First stage. By default, nothing happens here. - - - - - Second stage. Type mapping occurs here. - - - - - Third stage. lifetime managers are checked here, - and if they're available the rest of the pipeline is skipped. - - - - - Fourth stage. Reflection over constructors, properties, etc. is - performed here. - - - - - Fifth stage. Instance creation happens here. - - - - - Sixth stage. Property sets and method injection happens here. - - - - - Seventh and final stage. By default, nothing happens here. - - - - - A strongly-typed resource class, for looking up localized strings, etc. - - - - - Returns the cached ResourceManager instance used by this class. - - - - - Overrides the current thread's CurrentUICulture property for all - resource lookups using this strongly typed resource class. - - - - - Looks up a localized string similar to The provided string argument must not be empty.. - - - - - Looks up a localized string similar to The method {0}.{1}({2}) is an open generic method. Open generic methods cannot be injected.. - - - - - Looks up a localized string similar to The property {0} on type {1} is an indexer. Indexed properties cannot be injected.. - - - - - Looks up a localized string similar to The method {0}.{1}({2}) has at least one out parameter. Methods with out parameters cannot be injected.. - - - - - Looks up a localized string similar to The method {0}.{1}({2}) has at least one ref parameter.Methods with ref parameters cannot be injected.. - - - - - Looks up a localized string similar to The method {0}.{1}({2}) is static. Static methods cannot be injected.. - - - - - Looks up a localized string similar to The lifetime manager is already registered. Lifetime managers cannot be reused, please create a new one.. - - - - - Looks up a localized string similar to The type {0} does not have a generic argument named "{1}". - - - - - Looks up a localized string similar to The type {0} does not have a constructor that takes the parameters ({1}).. - - - - - Looks up a localized string similar to The type {0} does not have a public method named {1} that takes the parameters ({2}).. - - - - - Looks up a localized string similar to The type {0} does not contain a property named {1}.. - - - - - Looks up a localized string similar to The type {0} is not a generic type, and you are attempting to inject a generic parameter named "{1}".. - - - - - Looks up a localized string similar to The type {0} is not an array type with rank 1, and you are attempting to use a [DependencyArray] attribute on a parameter or property with this type.. - - - - - Looks up a localized string similar to The property {0} on type {1} is not settable.. - - - - - Looks up a localized string similar to The property {0} on type {1} is of type {2}, and cannot be injected with a value of type {3}.. - - - - - Looks up a localized string similar to Resolution of the dependency failed, type = "{0}", name = "{1}". Exception message is: {2}. - - - - - Looks up a localized string similar to The type {1} cannot be assigned to variables of type {0}.. - - - - - A simple, extensible dependency injection container. - - - - - Create a default . - - - - - Create a with the given parent container. - - The parent . The current object - will apply its own settings first, and then check the parent for additional ones. - - - - RegisterType a type mapping with the container, where the created instances will use - the given . - - that will be requested. - that will actually be returned. - Name to use for registration, null if a default registration. - The that controls the lifetime - of the returned instance. - Injection configuration objects. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - RegisterType an instance with the container. - - - - Instance registration is much like setting a type as a singleton, except that instead - of the container creating the instance the first time it is requested, the user - creates the instance ahead of type and adds that instance to the container. - - - Type of instance to register (may be an implemented interface instead of the full type). - Object to returned. - Name for registration. - - If true, the container will take over the lifetime of the instance, - calling Dispose on it (if it's ) when the container is Disposed. - - If false, container will not maintain a strong reference to . User is reponsible - for disposing instance, and for keeping the instance from being garbage collected. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Get an instance of the requested type with the given name from the container. - - of object to get from the container. - Name of the object to retrieve. - The retrieved object. - - - - Return instances of all registered types requested. - - - - This method is useful if you've registered multiple types with the same - but different names. - - - Be aware that this method does NOT return an instance for the default (unnamed) registration. - - - The type requested. - Set of objects of type . - - - - Run an existing object through the container and perform injection on it. - - - - This method is useful when you don't control the construction of an - instance (ASP.NET pages or objects created via XAML, for instance) - but you still want properties and other injection performed. - - of object to perform injection on. - Instance to build up. - name to use when looking up the typemappings and other configurations. - The resulting object. By default, this will be , but - container extensions may add things like automatic proxy creation which would - cause this to return a different object (but still type compatible with ). - - - - Run an existing object through the container, and clean it up. - - The object to tear down. - - - - Add an extension object to the container. - - to add. - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Get access to a configuration interface exposed by an extension. - - Extensions can expose configuration interfaces as well as adding - strategies and policies to the container. This method walks the list of - added extensions and returns the first one that implements the requested type. - - of configuration interface required. - The requested extension's configuration interface, or null if not found. - - - - Remove all installed extensions from this container. - - - - This method removes all extensions from the container, including the default ones - that implement the out-of-the-box behavior. After this method, if you want to use - the container again you will need to either readd the default extensions or replace - them with your own. - - - The registered instances and singletons that have already been set up in this container - do not get removed. - - - The object that this method was called on (this in C#, Me in Visual Basic). - - - - Create a child container. - - - A child container shares the parent's configuration, but can be configured with different - settings or lifetime. - The new child container. - - - - Dispose this container instance. - - - Disposing the container also disposes any child containers, - and disposes any instances whose lifetimes are managed - by the container. - - - - - Dispose this container instance. - - - This class doesn't have a finalizer, so will always be true. - True if being called from the IDisposable.Dispose - method, false if being called from a finalizer. - - - - The parent of this container. - - The parent container, or null if this container doesn't have one. - - - - Implementation of the ExtensionContext that is actually used - by the UnityContainer implementation. - - - This is a nested class so that it can access state in the - container that would otherwise be inaccessible. - - - - - This event is raised when the method, - or one of its overloads, is called. - - - - - This extension supplies the default behavior of the UnityContainer API - by handling the context events and setting policies. - - - - - Install the default container behavior into the container. - - - - - Remove the default behavior from the container. - - - - - Helper class to wrap common reflection stuff dealing with - methods. - - - - - Create a new instance that - lets us do more reflection stuff on that method. - - - - - - Given our set of generic type arguments, - - - - - - - Returns true if any of the parameters of this method - are open generics. - - - - - Return the of each parameter for this - method. - - Sequence of objects, one for - each parameter in order. - - - - A helper class that encapsulates two different - data items together into a a single item. - - - - - Create a new containing - the two values give. - - First value - Second value - - - - The first value of the pair. - - - - - The second value of the pair. - - - - - Container for a Pair helper method. - - - - - A helper factory method that lets users take advantage of type inference. - - Type of first value. - Type of second value. - First value. - Second value. - A new instance. - - - - A utility class that handles the logic of matching parameter - lists, so we can find the right constructor and method overloads. - - - - - Create a new that will attempt to - match the given parameter types. - - Target parameters to match against. - - - - Tests to see if the given set of types matches the ones - we're looking for. - - parameter list to look for. - true if they match, false if they don't. - - - - Tests to see if the given set of types matches the ones we're looking for. - - Candidate method signature to look for. - True if they match, false if they don't. - - - - Another reflection helper class that has extra methods - for dealing with ParameterInfos. - - - - - A small helper class to encapsulate details of the - reflection API, particularly around generics. - - - - - Create a new instance that - lets you look at information about the given type. - - Type to do reflection on. - - - - Test the given object, looking at - the parameters. Determine if any of the parameters are - open generic types that need type attributes filled in. - - The method to check. - True if any of the parameters are open generics. False if not. - - - - If this type is an open generic, use the - given array to - determine what the required closed type is and return that. - - If the parameter is not an open type, just - return this parameter's type. - Type arguments to substitute in for - the open type parameters. - Corresponding closed type of this parameter. - - - - Given a generic argument name, return the corresponding type for this - closed type. For example, if the current type is Foo<User>, and the - corresponding definition was Foo<TSomething>, calling this method - and passing "TSomething" will return typeof(User). - - Name of the generic parameter. - Type of the corresponding generic parameter, or null if there - is no matching name. - - - - The object we're reflecting over. - - - - - Is this type generic? - - - - - Is this type an open generic (no type parameter specified) - - - - - Create a new instance of that - lets you query information about the given ParameterInfo object. - - Parameter to query. - - - + + + + Microsoft.Practices.Unity + + + + + Base class for attributes that can be placed on parameters + or properties to specify how to resolve the value for + that parameter or property. + + + + + Create an instance of that + will be used to get the value for the member this attribute is + applied to. + + Type of parameter or property that + this attribute is decoration. + The resolver object. + + + + This attribute is used to indicate which constructor to choose when + the container attempts to build a type. + + + + + This attribute is used to mark methods that should be called when + the container is building an object. + + + + + This attribute is used to mark properties and parameters as targets for injection. + + + For properties, this attribute is necessary for injection to happen. For parameters, + it's not needed unless you want to specify additional information to control how + the parameter is resolved. + + + + + Create an instance of with no name. + + + + + Create an instance of with the given name. + + Name to use when resolving this dependency. + + + + Create an instance of that + will be used to get the value for the member this attribute is + applied to. + + Type of parameter or property that + this attribute is decoration. + The resolver object. + + + + The name specified in the constructor. + + + + + This extension installs the default strategies and policies into the container + to implement the standard behavior of the Unity container. + + + This extension installs the default strategies and policies into the container + to implement the standard behavior of the Unity container. + + + + + Base class for all extension objects. + + + + + Base interface for all extension configuration interfaces. + + + + + Retrieve the container instance that we are currently configuring. + + + + + The container calls this method when the extension is added. + + A instance that gives the + extension access to the internals of the container. + + + + Initial the container with this extension's functionality. + + + When overridden in a derived class, this method will modify the given + by adding strategies, policies, etc. to + install it's functions into the container. + + + + Removes the extension's functions from the container. + + + + This method is called when extensions are being removed from the container. It can be + used to do things like disconnect event handlers or clean up member state. You do not + need to remove strategies or policies here; the container will do that automatically. + + + The default implementation of this method does nothing. + + + + + The container this extension has been added to. + + The that this extension has been added to. + + + + The object used to manipulate + the inner state of the container. + + + + + Add the correct to the policy + set. This version adds the appropriate policy for running on the desktop CLR. + + + + + Add the default ObjectBuilder strategies & policies to the container. + + + + + The class provides the means for extension objects + to manipulate the internal state of the . + + + + + Store a type/name pair for later resolution. + + + + When users register type mappings (or other things) with a named key, this method + allows you to register that name with the container so that when the + method is called, that name is included in the list that is returned. + + to register. + Name assocated with that type. + + + + The container that this context is associated with. + + The object. + + + + The strategies this container uses. + + The that the container uses to build objects. + + + + The strategies this container uses to construct build plans. + + The that this container uses when creating + build plans. + + + + The policies this container uses. + + The the that container uses to build objects. + + + + The that this container uses. + + The Locator is an object that is used to store information to be found later during the build process. + + + + The that this container uses. + + The is used to manage objects that the container is managing. + + + + This event is raised when the method, + or one of its overloads, is called. + + + + + This event is raised when the method, + or one of its overloads, is called. + + + + + An EventArgs class that holds a string Name. + + + + + Create a new with a null name. + + + + + Create a new with the given name. + + Name to store. + + + + The name. + + Name used for this event arg object. + + + + Event argument class for the event. + + + + + Create a new instance of . + + Type to map from. + Type to map to. + Name for the registration. + to manage instances. + + + + Type to map from. + + + + + Type to map to. + + + + + to manage instances. + + + + + Event argument class for the event. + + + + + Create a default instance. + + + + + Create a instance initialized with the given arguments. + + Type of instance being registered. + The instance object itself. + Name to register under, null if default registration. + object that handles how + the instance will be owned. + + + + Type of instance being registered. + + + Type of instance being registered. + + + + + Instance object being registered. + + Instance object being registered + + + + that controls ownership of + this instance. + + + + + A that lets you specify that + an instance of a generic type parameter should be resolved. + + + + + Base type for objects that are used to configure parameters for + constructor or method injection, or for getting the value to + be injected into a property. + + + + + Test to see if this parameter value has a matching type for the given type. + + Type to check. + True if this parameter value is compatible with type , + false if not. + + + + Return a instance that will + return this types value for the parameter. + + Type that contains the member that needs this parameter. Used + to resolve open generic parameters. + The . + + + + Convert the given set of arbitrary values to a sequence of InjectionParameterValue + objects. The rules are: If it's already an InjectionParameterValue, return it. If + it's a Type, return a ResolvedParameter object for that type. Otherwise return + an InjectionParameter object for that value. + + The values to build the sequence from. + The resulting converted sequence. + + + + Convert an arbitrary value to an InjectionParameterValue object. The rules are: + If it's already an InjectionParameterValue, return it. If it's a Type, return a + ResolvedParameter object for that type. Otherwise return an InjectionParameter + object for that value. + + The value to convert. + The resulting . + + + + Name for the type represented by this . + This may be an actual type name or a generic argument name. + + + + + Create a new instance that specifies + that the given named generic parameter should be resolved. + + The generic parameter name to resolve. + + + + Create a new instance that specifies + that the given named generic parameter should be resolved. + + The generic parameter name to resolve. + name to use when looking up in the container. + + + + Test to see if this parameter value has a matching type for the given type. + + Type to check. + True if this parameter value is compatible with type , + false if not. + + + + Return a instance that will + return this types value for the parameter. + + Type that contains the member that needs this parameter. Used + to resolve open generic parameters. + The . + + + + Name for the type represented by this . + This may be an actual type name or a generic argument name. + + + + + A that lets you specify that + an array containing the registered instances of a generic type parameter + should be resolved. + + + + + Create a new instance that specifies + that the given named generic parameter should be resolved. + + The generic parameter name to resolve. + The values for the elements, that will + be converted to objects. + + + + Test to see if this parameter value has a matching type for the given type. + + Type to check. + True if this parameter value is compatible with type , + false if not. + A type is considered compatible if it is an array type of rank one + and its element type is a generic type parameter with a name matching this generic + parameter name configured for the receiver. + + + + Return a instance that will + return this types value for the parameter. + + Type that contains the member that needs this parameter. Used + to resolve open generic parameters. + The . + + + + Name for the type represented by this . + This may be an actual type name or a generic argument name. + + + + + A Unity container extension that allows you to configure + which constructors, properties, and methods get injected + via an API rather than through attributes. + + + + + Initial the container with this extension's functionality. + + + When overridden in a derived class, this method will modify the given + by adding strategies, policies, etc. to + install it's functions into the container. + + + + API to configure the injection settings for a particular type. + + Type the injection is being configured for. + Objects containing the details on which members to inject and how. + This extension object. + + + + API to configure the injection settings for a particular type/name pair. + + Type the injection is being configured for. + Name of registration + Objects containing the details on which members to inject and how. + This extension object. + + + + API to configure the injection settings for a particular type. + + Type to configure. + Objects containing the details on which members to inject and how. + This extension object. + + + + API to configure the injection settings for a particular type/name pair. + + Type to configure. + Name of registration. + Objects containing the details on which members to inject and how. + This extension object. + + + + Remove policies associated with building this type. This removes the + compiled build plan so that it can be rebuilt with the new settings + the next time this type is resolved. + + Type of object to clear the plan for. + Name the object is being registered with. + + + + A class that holds the collection of information + for a constructor, so that the container can + be configured to call this constructor. + + + + + Base class for objects that can be used to configure what + class members get injected by the container. + + + + + Add policies to the to configure the + container to call this constructor with the appropriate parameter values. + + Type to register. + Policy list to add policies to. + + + + Add policies to the to configure the + container to call this constructor with the appropriate parameter values. + + Type to register. + Name used to resolve the type object. + Policy list to add policies to. + + + + Create a new instance of that looks + for a constructor with the given set of parameters. + + The values for the parameters, that will + be converted to objects. + + + + Add policies to the to configure the + container to call this constructor with the appropriate parameter values. + + Type to register. + Name used to resolve the type object. + Policy list to add policies to. + + + + An that configures the + container to call a method as part of buildup. + + + + + Create a new instance which will configure + the container to call the given methods with the given parameters. + + Name of the method to call. + Parameter values for the method. + + + + Add policies to the to configure the + container to call this constructor with the appropriate parameter values. + + Type to register. + Name used to resolve the type object. + Policy list to add policies to. + + + + A small function to handle name matching. You can override this + to do things like case insensitive comparisons. + + MethodInfo for the method you're checking. + Name of the method you're looking for. + True if a match, false if not. + + + + A class that holds on to the given value and provides + the required + when the container is configured. + + + + + A base class for implementing classes + that deal in explicit types. + + + + + Create a new that exposes + information about the given . + + Type of the parameter. + + + + Test to see if this parameter value has a matching type for the given type. + + Type to check. + True if this parameter value is compatible with type , + false if not. + + + + The type of parameter this object represents. + + + + + Name for the type represented by this . + This may be an actual type name or a generic argument name. + + + + + Create an instance of that stores + the given value, using the runtime type of that value as the + type of the parameter. + + Value to be injected for this parameter. + + + + Create an instance of that stores + the given value, associated with the given type. + + Type of the parameter. + Value of the parameter + + + + Return a instance that will + return this types value for the parameter. + + Type that contains the member that needs this parameter. Used + to resolve open generic parameters. + The . + + + + A generic version of that makes it a + little easier to specify the type of the parameter. + + Type of parameter. + + + + Create a new . + + Value for the parameter. + + + + This class stores information about which properties to inject, + and will configure the container accordingly. + + + + + Configure the container to inject the given property name, + resolving the value via the container. + + Name of the property to inject. + + + + Configure the container to inject the given property name, + using the value supplied. This value is converted to an + object using the + rules defined by the + method. + + Name of property to inject. + Value for property. + + + + Add policies to the to configure the + container to call this constructor with the appropriate parameter values. + + Type to register. + Name used to resolve the type object. + Policy list to add policies to. + + + + A class that stores a type, and generates a + resolver object that resolves all the named instances or the + type registered in a container. + + + + + Construct a new that + resolves to the given element type and collection of element values. + + The type of elements to resolve. + The values for the elements, that will + be converted to objects. + + + + Construct a new that + resolves to the given array and element types and collection of element values. + + The type for the array of elements to resolve. + The type of elements to resolve. + The values for the elements, that will + be converted to objects. + + + + Return a instance that will + return this types value for the parameter. + + Type that contains the member that needs this parameter. Used + to resolve open generic parameters. + The . + + + + A generic version of for convenience + when creating them by hand. + + Type of the elements for the array of the parameter. + + + + Construct a new that + resolves to the given element generic type with the given element values. + + The values for the elements, that will + be converted to objects. + + + + Interface defining the behavior of the Unity dependency injection container. + + + + + Register a type with specific members to be injected. + + Type this registration is for. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container. + + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + + This overload registers a default mapping and transient lifetime. + + + that will be requested. + that will actually be returned. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container. + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + that will be requested. + that will actually be returned. + Name of this mapping. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type with the container. + No type mapping is performed for this type. + + The type to apply the to. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type with the container. + No type mapping is performed for this type. + + The type to configure injection on. + Name that will be used to request the type. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type and name with the container. + No type mapping is performed for this type. + + The type to apply the to. + Name that will be used to request the type. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type with specific members to be injected. + + Type this registration is for. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container. + + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + + This overload registers a default mapping. + + + that will be requested. + that will actually be returned. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container. + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type and name with the container. + No type mapping is performed for this type. + + The to apply the to. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type and name with the container. + No type mapping is performed for this type. + + The to configure in the container. + Name to use for registration, null if a default registration. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type and name with the container. + No type mapping is performed for this type. + + The to apply the to. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration and has the container take over the lifetime of the instance. + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration (name = null). + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload automatically has the container take ownership of the . + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration and has the container take over the lifetime of the instance. + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration (name = null). + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload automatically has the container take ownership of the . + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Resolve an instance of the default requested type from the container. + + of object to get from the container. + The retrieved object. + + + + Resolve an instance of the requested type with the given name from the container. + + of object to get from the container. + Name of the object to retrieve. + The retrieved object. + + + + Resolve an instance of the default requested type from the container. + + of object to get from the container. + The retrieved object. + + + + Resolve an instance of the requested type with the given name from the container. + + of object to get from the container. + Name of the object to retrieve. + The retrieved object. + + + + Return instances of all registered types requested. + + + + This method is useful if you've registered multiple types with the same + but different names. + + + Be aware that this method does NOT return an instance for the default (unnamed) registration. + + + The type requested. + Set of objects of type . + + + + Return instances of all registered types requested. + + + + This method is useful if you've registered multiple types with the same + but different names. + + + Be aware that this method does NOT return an instance for the default (unnamed) registration. + + + The type requested. + Set of objects of type . + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + + This overload uses the default registrations. + + + of object to perform injection on. + Instance to build up. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + of object to perform injection on. + Instance to build up. + name to use when looking up the typemappings and other configurations. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + + This overload uses the default registrations. + + + of object to perform injection on. + Instance to build up. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + of object to perform injection on. + Instance to build up. + name to use when looking up the typemappings and other configurations. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container, and clean it up. + + The object to tear down. + + + + Add an extension object to the container. + + to add. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Creates a new extension object and adds it to the container. + + Type of to add. The extension type + must have a zero-argument public constructor. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Resolve access to a configuration interface exposed by an extension. + + Extensions can expose configuration interfaces as well as adding + strategies and policies to the container. This method walks the list of + added extensions and returns the first one that implements the requested type. + + The configuration interface required. + The requested extension's configuration interface, or null if not found. + + + + Resolve access to a configuration interface exposed by an extension. + + Extensions can expose configuration interfaces as well as adding + strategies and policies to the container. This method walks the list of + added extensions and returns the first one that implements the requested type. + + of configuration interface required. + The requested extension's configuration interface, or null if not found. + + + + Remove all installed extensions from this container. + + + + This method removes all extensions from the container, including the default ones + that implement the out-of-the-box behavior. After this method, if you want to use + the container again you will need to either readd the default extensions or replace + them with your own. + + + The registered instances and singletons that have already been set up in this container + do not get removed. + + + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Create a child container. + + + A child container shares the parent's configuration, but can be configured with different + settings or lifetime. + The new child container. + + + + The parent of this container. + + The parent container, or null if this container doesn't have one. + + + + A that holds onto the instance given to it. + When the is disposed, + the instance is disposed with it. + + + + + Base class for Lifetime managers which need to synchronize calls to + . + + + + The purpose of this class is to provide a basic implementation of the lifetime manager synchronization pattern. + + + Calls to the method of a + instance acquire a lock, and if the instance has not been initialized with a value yet the lock will only be released + when such an initialization takes place by calling the method or if + the build request which resulted in the call to the GetValue method fails. + + + + + + + Base class for Lifetime managers - classes that control how + and when instances are created by the Unity container. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + + + + Remove the given object from backing store. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + Calls to this method acquire a lock which is released only if a non-null value + has been set for the lifetime manager. + + + + Performs the actual retrieval of a value from the backing store associated + with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + This method is invoked by + after it has acquired its lock. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + Setting a value will attempt to release the lock acquired by + . + + + + Performs the actual storage of the given value into backing store for retrieval later. + + The object being stored. + This method is invoked by + before releasing its lock. + + + + Remove the given object from backing store. + + + + + A method that does whatever is needed to clean up + as part of cleaning up after an exception. + + + Don't do anything that could throw in this method, + it will cause later recover operations to get skipped + and play real havok with the stack trace. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + + + + Remove the given object from backing store. + + + + + Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + + 2 + + + + Standard Dispose pattern implementation. Not needed, but it keeps FxCop happy. + + Always true, since we don't have a finalizer. + + + + A that holds a weak reference to + it's managed instance. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + + + + Remove the given object from backing store. + + + + + An implementation of that + creates instances of the type of the given Lifetime Manager + by resolving them through the container. + + + + + Create a new that will + return instances of the given type, creating them by + resolving through the container. + + Container to resolve with. + Type of LifetimeManager to create. + + + + Create a new instance of . + + The new instance. + + + + A that holds the instances given to it, + keeping one instance per thread. + + + + This LifetimeManager does not dispose the instances it holds. + + + + + + Initializes a new instance of the class. + + + + + Retrieve a value from the backing store associated with this Lifetime policy for the + current thread. + + the object desired, or if no such object is currently + stored for the current thread. + + + + Stores the given value into backing store for retrieval later when requested + in the current thread. + + The object being stored. + + + + Remove the given object from backing store. + + Not implemented for this lifetime manager. + + + + An implementation that does nothing, + thus ensuring that instances are created new every time. + + + + + Retrieve a value from the backing store associated with this Lifetime policy. + + the object desired, or null if no such object is currently stored. + + + + Stores the given value into backing store for retrieval later. + + The object being stored. + + + + Remove the given object from backing store. + + + + + This strategy implements the logic that will call container.ResolveAll + when an array parameter is detected. + + + + + Do the PreBuildUp stage of construction. This is where the actual work is performed. + + Current build context. + + + + An implementation of that is + aware of the build keys used by the Unity container. + + + + + Create a instance for the given + . + + + This implementation looks for the Unity on the + parameter and uses it to create an instance of + for this parameter. + Parameter to create the resolver for. + The resolver object. + + + + An implementation of that is aware + of the build keys used by the Unity container. + + + + + Create a instance for the given + . + + Parameter to create the resolver for. + The resolver object. + + + + An implementation of that is aware of + the build keys used by the unity container. + + + + + Create a for the given + property. + + Property to create resolver for. + The resolver object. + + + + A implementation that returns + the value set in the constructor. + + + + + Create a new instance of + which will return the given value when resolved. + + The value to return. + + + + Get the value for a dependency. + + Current build context. + The value for the dependency. + + + + An implementation of that stores a + type and name, and at resolution time puts them together into a + . + + + + + Create an instance of + with the given type and name. + + The type. + The name (may be null). + + + + Resolve the value for a dependency. + + Current build context. + The value for the dependency. + + + + The type that this resolver resolves. + + + + + The name that this resolver resolves. + + + + + An implementation of that resolves to + to an array populated with the values that result from resolving other instances + of . + + + + + Create an instance of + with the given type and a collection of + instances to use when populating the result. + + The type. + The resolver policies to use when populating an array. + + + + Resolve the value for a dependency. + + Current build context. + An array pupulated with the results of resolving the resolver policies. + + + + An implementation of that selects + the given constructor and creates the appropriate resolvers to call it with + the specified parameters. + + + + + Create an instance of that + will return the given constructor, being passed the given injection values + as parameters. + + The constructor to call. + Set of objects + that describes how to obtain the values for the constructor parameters. + + + + Choose the constructor to call for the given type. + + Current build context + The chosen constructor. + + + + Helper class for implementing selector policies that need to + set up dependency resolver policies. + + + + + Add dependency resolvers to the parameter set. + + Type that's currently being built (used to resolve open generics). + PolicyList to add the resolvers to. + Objects supplying the dependency resolvers. + Result object to store the keys in. + + + + A implementation that calls the specific + methods with the given parameters. + + + + + Add the given method and parameter collection to the list of methods + that will be returned when the selector's + method is called. + + Method to call. + sequence of objects + that describe how to create the method parameter values. + + + + Return the sequence of methods to call while building the target object. + + Current build context. + Sequence of methods to call. + + + + An implemnetation of which returns + the set of specific properties that the selector was configured with. + + + + + Add a property that will be par of the set returned when the + is called. + + The property to set. + object describing + how to create the value to inject. + + + + Returns sequence of properties on the given type that + should be set as part of building that object. + + Current build context. + Sequence of objects + that contain the properties to set. + + + + The exception thrown by the Unity container when + an attempt to resolve a dependency fails. + + + + + Create a new that records + the exception for the given type and name. + + Type requested from the container. + Name requested from the container. + The actual exception that caused the failure of the build. + + + + Constructor to create a from serialized state. + + Serialization info + Serialization context + + + + Serialize this object into the given context. + + Serialization info + Streaming context + + + + The type that was being requested from the container at the time of failure. + + + + + The name that was being requested from the container at the time of failure. + + + + + A class that stores a name and type, and generates a + resolver object that resolves the parameter via the + container. + + + + + Construct a new that + resolves to the given type. + + Type of this parameter. + + + + Construct a new that + resolves the given type and name. + + Type of this parameter. + Name to use when resolving parameter. + + + + Return a instance that will + return this types value for the parameter. + + Type that contains the member that needs this parameter. Used + to resolve open generic parameters. + The . + + + + A generic version of for convenience + when creating them by hand. + + Type of the parameter + + + + Create a new for the given + generic type and the default name. + + + + + Create a new for the given + generic type and name. + + Name to use to resolve this parameter. + + + + A base class for implmenting that provides + reasonable implementations for most of the overloads defined by the interface. + The overloads all call down to the non-generic versions of the methods with + the most parameters. + + + + + Register a type with specific members to be injected. + + Type this registration is for. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container. + + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + + This overload registers a default mapping. + + + that will be requested. + that will actually be returned. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container. + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + that will be requested. + that will actually be returned. + + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a for the given type with the container. + No type mapping is performed for this type. + + The type to apply the to. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type with the container. + No type mapping is performed for this type. + + The type to configure injection on. + Name that will be used to request the type. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a for the given type and name with the container. + No type mapping is performed for this type. + + The type to apply the to. + Name that will be used to request the type. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a type with specific members to be injected. + + Type this registration is for. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container. + + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + + This overload registers a default mapping. + + + that will be requested. + that will actually be returned. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a for the given type and name with the container. + No type mapping is performed for this type. + + The to apply the to. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Register a for the given type and name with the container. + No type mapping is performed for this type. + + The to configure in the container. + Name to use for registration, null if a default registration. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a for the given type and name with the container. + No type mapping is performed for this type. + + The to apply the to. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container. + + + This method is used to tell the container that when asked for type , + actually return an instance of type . This is very useful for + getting instances of interfaces. + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration and has the container take over the lifetime of the instance. + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration (name = null). + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload automatically has the container take ownership of the . + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration and has the container take over the lifetime of the instance. + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload does a default registration (name = null). + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + + object that controls how this instance will be managed by the container. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + This overload automatically has the container take ownership of the . + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + + If true, the container will take over the lifetime of the instance, + calling Dispose on it (if it's ) when the container is Disposed. + + If false, container will not maintain a strong reference to . User is reponsible + for disposing instance, and for keeping the instance from being garbage collected. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Get an instance of the default requested type from the container. + + of object to get from the container. + The retrieved object. + + + + Get an instance of the requested type with the given name from the container. + + of object to get from the container. + Name of the object to retrieve. + The retrieved object. + + + + Get an instance of the default requested type from the container. + + of object to get from the container. + The retrieved object. + + + + Get an instance of the requested type with the given name from the container. + + of object to get from the container. + Name of the object to retrieve. + The retrieved object. + + + + Return instances of all registered types requested. + + + + This method is useful if you've registered multiple types with the same + but different names. + + + Be aware that this method does NOT return an instance for the default (unnamed) registration. + + + The type requested. + Set of objects of type . + + + + Return instances of all registered types requested. + + + + This method is useful if you've registered multiple types with the same + but different names. + + + Be aware that this method does NOT return an instance for the default (unnamed) registration. + + + The type requested. + Set of objects of type . + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + + This overload uses the default registrations. + + + of object to perform injection on. + Instance to build up. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + of object to perform injection on. + Instance to build up. + name to use when looking up the typemappings and other configurations. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + + This overload uses the default registrations. + + + of object to perform injection on. + Instance to build up. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + of object to perform injection on. + Instance to build up. + name to use when looking up the typemappings and other configurations. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container, and clean it up. + + The object to tear down. + + + + Add an extension object to the container. + + to add. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Creates a new extension object and adds it to the container. + + Type of to add. The extension type + must have a zero-argument public constructor. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Get access to a configuration interface exposed by an extension. + + Extensions can expose configuration interfaces as well as adding + strategies and policies to the container. This method walks the list of + added extensions and returns the first one that implements the requested type. + + The configuration interface required. + The requested extension's configuration interface, or null if not found. + + + + Get access to a configuration interface exposed by an extension. + + Extensions can expose configuration interfaces as well as adding + strategies and policies to the container. This method walks the list of + added extensions and returns the first one that implements the requested type. + + of configuration interface required. + The requested extension's configuration interface, or null if not found. + + + + Remove all installed extensions from this container. + + + + This method removes all extensions from the container, including the default ones + that implement the out-of-the-box behavior. After this method, if you want to use + the container again you will need to either readd the default extensions or replace + them with your own. + + + The registered instances and singletons that have already been set up in this container + do not get removed. + + + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Create a child container. + + + A child container shares the parent's configuration, but can be configured with different + settings or lifetime. + The new child container. + + + + Dispose this container instance. + + + Disposing the container also disposes any child containers, + and disposes any instances whose lifetimes are managed + by the container. + + + + + The parent of this container. + + The parent container, or null if this container doesn't have one. + + + + A static helper class that includes various parameter checking routines. + + + + + Throws if the given argument is null. + + if tested value if null. + Argument value to test. + Name of the argument being tested. + + + + Throws an exception if the tested string argument is null or the empty string. + + Thrown if string value is null. + Thrown if the string is empty + Argument value to check. + Name of argument being checked. + + + + Verifies that an argument type is assignable from the provided type (meaning + interfaces are implemented, or classes exist in the base class hierarchy). + + The argument type that will be assigned to. + The type of the value being assigned. + Argument name. + + + + The build stages we use in the Unity container + strategy pipeline. + + + + + First stage. By default, nothing happens here. + + + + + Second stage. Type mapping occurs here. + + + + + Third stage. lifetime managers are checked here, + and if they're available the rest of the pipeline is skipped. + + + + + Fourth stage. Reflection over constructors, properties, etc. is + performed here. + + + + + Fifth stage. Instance creation happens here. + + + + + Sixth stage. Property sets and method injection happens here. + + + + + Seventh and final stage. By default, nothing happens here. + + + + + A strongly-typed resource class, for looking up localized strings, etc. + + + + + Returns the cached ResourceManager instance used by this class. + + + + + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + + + + + Looks up a localized string similar to The provided string argument must not be empty.. + + + + + Looks up a localized string similar to The method {0}.{1}({2}) is an open generic method. Open generic methods cannot be injected.. + + + + + Looks up a localized string similar to The property {0} on type {1} is an indexer. Indexed properties cannot be injected.. + + + + + Looks up a localized string similar to The method {0}.{1}({2}) has at least one out parameter. Methods with out parameters cannot be injected.. + + + + + Looks up a localized string similar to The method {0}.{1}({2}) has at least one ref parameter.Methods with ref parameters cannot be injected.. + + + + + Looks up a localized string similar to The method {0}.{1}({2}) is static. Static methods cannot be injected.. + + + + + Looks up a localized string similar to The lifetime manager is already registered. Lifetime managers cannot be reused, please create a new one.. + + + + + Looks up a localized string similar to The type {0} does not have a generic argument named "{1}". + + + + + Looks up a localized string similar to The type {0} does not have a constructor that takes the parameters ({1}).. + + + + + Looks up a localized string similar to The type {0} does not have a public method named {1} that takes the parameters ({2}).. + + + + + Looks up a localized string similar to The type {0} does not contain a property named {1}.. + + + + + Looks up a localized string similar to The type {0} is not a generic type, and you are attempting to inject a generic parameter named "{1}".. + + + + + Looks up a localized string similar to The type {0} is not an array type with rank 1, and you are attempting to use a [DependencyArray] attribute on a parameter or property with this type.. + + + + + Looks up a localized string similar to The property {0} on type {1} is not settable.. + + + + + Looks up a localized string similar to The property {0} on type {1} is of type {2}, and cannot be injected with a value of type {3}.. + + + + + Looks up a localized string similar to Resolution of the dependency failed, type = "{0}", name = "{1}". Exception message is: {2}. + + + + + Looks up a localized string similar to The type {1} cannot be assigned to variables of type {0}.. + + + + + A simple, extensible dependency injection container. + + + + + Create a default . + + + + + Create a with the given parent container. + + The parent . The current object + will apply its own settings first, and then check the parent for additional ones. + + + + RegisterType a type mapping with the container, where the created instances will use + the given . + + that will be requested. + that will actually be returned. + Name to use for registration, null if a default registration. + The that controls the lifetime + of the returned instance. + Injection configuration objects. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + RegisterType an instance with the container. + + + + Instance registration is much like setting a type as a singleton, except that instead + of the container creating the instance the first time it is requested, the user + creates the instance ahead of type and adds that instance to the container. + + + Type of instance to register (may be an implemented interface instead of the full type). + Object to returned. + Name for registration. + + If true, the container will take over the lifetime of the instance, + calling Dispose on it (if it's ) when the container is Disposed. + + If false, container will not maintain a strong reference to . User is reponsible + for disposing instance, and for keeping the instance from being garbage collected. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Get an instance of the requested type with the given name from the container. + + of object to get from the container. + Name of the object to retrieve. + The retrieved object. + + + + Return instances of all registered types requested. + + + + This method is useful if you've registered multiple types with the same + but different names. + + + Be aware that this method does NOT return an instance for the default (unnamed) registration. + + + The type requested. + Set of objects of type . + + + + Run an existing object through the container and perform injection on it. + + + + This method is useful when you don't control the construction of an + instance (ASP.NET pages or objects created via XAML, for instance) + but you still want properties and other injection performed. + + of object to perform injection on. + Instance to build up. + name to use when looking up the typemappings and other configurations. + The resulting object. By default, this will be , but + container extensions may add things like automatic proxy creation which would + cause this to return a different object (but still type compatible with ). + + + + Run an existing object through the container, and clean it up. + + The object to tear down. + + + + Add an extension object to the container. + + to add. + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Get access to a configuration interface exposed by an extension. + + Extensions can expose configuration interfaces as well as adding + strategies and policies to the container. This method walks the list of + added extensions and returns the first one that implements the requested type. + + of configuration interface required. + The requested extension's configuration interface, or null if not found. + + + + Remove all installed extensions from this container. + + + + This method removes all extensions from the container, including the default ones + that implement the out-of-the-box behavior. After this method, if you want to use + the container again you will need to either readd the default extensions or replace + them with your own. + + + The registered instances and singletons that have already been set up in this container + do not get removed. + + + The object that this method was called on (this in C#, Me in Visual Basic). + + + + Create a child container. + + + A child container shares the parent's configuration, but can be configured with different + settings or lifetime. + The new child container. + + + + Dispose this container instance. + + + Disposing the container also disposes any child containers, + and disposes any instances whose lifetimes are managed + by the container. + + + + + Dispose this container instance. + + + This class doesn't have a finalizer, so will always be true. + True if being called from the IDisposable.Dispose + method, false if being called from a finalizer. + + + + The parent of this container. + + The parent container, or null if this container doesn't have one. + + + + Implementation of the ExtensionContext that is actually used + by the UnityContainer implementation. + + + This is a nested class so that it can access state in the + container that would otherwise be inaccessible. + + + + + This event is raised when the method, + or one of its overloads, is called. + + + + + This extension supplies the default behavior of the UnityContainer API + by handling the context events and setting policies. + + + + + Install the default container behavior into the container. + + + + + Remove the default behavior from the container. + + + + + Helper class to wrap common reflection stuff dealing with + methods. + + + + + Create a new instance that + lets us do more reflection stuff on that method. + + + + + + Given our set of generic type arguments, + + + + + + + Returns true if any of the parameters of this method + are open generics. + + + + + Return the of each parameter for this + method. + + Sequence of objects, one for + each parameter in order. + + + + A helper class that encapsulates two different + data items together into a a single item. + + + + + Create a new containing + the two values give. + + First value + Second value + + + + The first value of the pair. + + + + + The second value of the pair. + + + + + Container for a Pair helper method. + + + + + A helper factory method that lets users take advantage of type inference. + + Type of first value. + Type of second value. + First value. + Second value. + A new instance. + + + + A utility class that handles the logic of matching parameter + lists, so we can find the right constructor and method overloads. + + + + + Create a new that will attempt to + match the given parameter types. + + Target parameters to match against. + + + + Tests to see if the given set of types matches the ones + we're looking for. + + parameter list to look for. + true if they match, false if they don't. + + + + Tests to see if the given set of types matches the ones we're looking for. + + Candidate method signature to look for. + True if they match, false if they don't. + + + + Another reflection helper class that has extra methods + for dealing with ParameterInfos. + + + + + A small helper class to encapsulate details of the + reflection API, particularly around generics. + + + + + Create a new instance that + lets you look at information about the given type. + + Type to do reflection on. + + + + Test the given object, looking at + the parameters. Determine if any of the parameters are + open generic types that need type attributes filled in. + + The method to check. + True if any of the parameters are open generics. False if not. + + + + If this type is an open generic, use the + given array to + determine what the required closed type is and return that. + + If the parameter is not an open type, just + return this parameter's type. + Type arguments to substitute in for + the open type parameters. + Corresponding closed type of this parameter. + + + + Given a generic argument name, return the corresponding type for this + closed type. For example, if the current type is Foo<User>, and the + corresponding definition was Foo<TSomething>, calling this method + and passing "TSomething" will return typeof(User). + + Name of the generic parameter. + Type of the corresponding generic parameter, or null if there + is no matching name. + + + + The object we're reflecting over. + + + + + Is this type generic? + + + + + Is this type an open generic (no type parameter specified) + + + + + Create a new instance of that + lets you query information about the given ParameterInfo object. + + Parameter to query. + + + diff --git a/Tools/MbUnit/MbUnit.Cons.exe.config b/Tools/MbUnit/MbUnit.Cons.exe.config index 7fd5edb1..81d1d92a 100644 --- a/Tools/MbUnit/MbUnit.Cons.exe.config +++ b/Tools/MbUnit/MbUnit.Cons.exe.config @@ -1,12 +1,12 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/Tools/MbUnit/MbUnit.Framework.1.1.XML b/Tools/MbUnit/MbUnit.Framework.1.1.XML index 59492a4d..6047e2a7 100644 --- a/Tools/MbUnit/MbUnit.Framework.1.1.XML +++ b/Tools/MbUnit/MbUnit.Framework.1.1.XML @@ -1,20 +1,20 @@ - - - - MbUnit.Framework.1.1 - - - - - Tags methods to execute database operation in its own database - transaction. - - - - This attribute was invented by Roy Osherove ( - http://weblogs.asp.net/rosherove/). - - - - - + + + + MbUnit.Framework.1.1 + + + + + Tags methods to execute database operation in its own database + transaction. + + + + This attribute was invented by Roy Osherove ( + http://weblogs.asp.net/rosherove/). + + + + + diff --git a/Tools/MbUnit/MbUnit.Framework.XML b/Tools/MbUnit/MbUnit.Framework.XML index cfb23ec5..44fe98c4 100644 --- a/Tools/MbUnit/MbUnit.Framework.XML +++ b/Tools/MbUnit/MbUnit.Framework.XML @@ -1,10995 +1,10995 @@ - - - - MbUnit.Framework - - - - - Array Assertion class - - - - - A private constructor disallows any instances of this object. - - - - - Verifies that both array have the same dimension and elements. - - - - - - - Assertion class - - - - - - The Equals method throws an AssertionException. This is done - to make sure there is no mistake by calling this function. - - - - - - - override the default ReferenceEquals to throw an AssertionException. This - implementation makes sure there is no mistake in calling this function - as part of Assert. - - - - - - - Checks the type of the object, returning true if - the object is a numeric type. - - The object to check - true if the object is a numeric type - - - - Used to compare numeric types. Comparisons between - same types are fine (Int32 to Int32, or Int64 to Int64), - but the Equals method fails across different types. - This method was added to allow any numeric type to - be handled correctly, by using ToString and - comparing the result - - - - - - - - A private constructor disallows any instances of this object. - - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - - The format of the message to display if the condition is false, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Asserts that a condition is true. If the condition is false the method throws - an . - - The evaluated condition - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - - The format of the message to display if the condition is false, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Asserts that a condition is false. If the condition is true the method throws - an . - - The evaluated condition - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equals then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - The message printed out upon failure - - - - Verifies that two doubles are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equals then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - - - - Verifies that two floats are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equals then an is - thrown. - - The message printed out upon failure - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - - - - Verifies that two floats are equal considering a delta. If the - expected value is infinity then the delta value is ignored. If - they are not equals then an is - thrown. - - The expected value - The actual value - The maximum acceptable difference between the - the expected and the actual - - - - Verifies that two decimals are equal. If - they are not equals then an is - thrown. - - The message printed out upon failure - The expected value - The actual value - - - - Verifies that two decimals are equal. If - they are not equals then an is - thrown. - - The expected value - The actual value - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Verifies that two decimals are equal. If - they are not equals then an is - thrown. - - The expected value - The actual value - - - - Verifies that two ints are equal. If - they are not equals then an is - thrown. - - The message printed out upon failure - The expected value - The actual value - - - - Verifies that two ints are equal. If - they are not equals then an is - thrown. - - The expected value - The actual value - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Verifies that two ints are equal. If - they are not equals then an is - thrown. - - The expected value - The actual value - - - - Verifies that two objects are equal. Two objects are considered - equal if both are null, or if both have the same value. All - non-numeric types are compared by using the Equals method. - If they are not equal an is thrown. - - The value that is expected - The actual value - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Verifies that two objects are equal. Two objects are considered - equal if both are null, or if both have the same value. All - non-numeric types are compared by using the Equals method. - If they are not equal an is thrown. - - The value that is expected - The actual value - The message to display if objects are not equal - - - - Verifies that two objects are equal. Two objects are considered - equal if both are null, or if both have the same value. All - non-numeric types are compared by using the Equals method. - If they are not equal an is thrown. - - The value that is expected - The actual value - - - - Verifies that the value of the property described by is the same - in both ojects. - - - Property describing the value to test - - - Reference object - - - Actual object - - - Index of the property. - - - - - Asserts that two objects are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two objects are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two objects are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Asserts that two objects are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two objects are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two objects are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Asserts that two ints are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two ints are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two ints are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Asserts that two uints are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two uints are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two uints are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Asserts that two decimals are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two decimals are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two decimals are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Asserts that two floats are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two floats are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two floats are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Asserts that two doubles are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the two objects are the same object. - Arguments to be used in formatting the message - - - - Asserts that two doubles are not equal. If they are equal - an is thrown. - - The expected object - The actual object - The message to be displayed when the objects are the same - - - - Asserts that two doubles are not equal. If they are equal - an is thrown. - - The expected object - The actual object - - - - Verifies that the object that is passed in is not equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Verifies that the object that is passed in is not equal to null - If the object is not null then an - is thrown. - - The object that is to be tested - - - - Verifies that the object that is passed in is equal to null - If the object is null then an - is thrown. - - The object that is to be tested - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Verifies that the object that is passed in is equal to null - If the object is null then an - is thrown. - - The object that is to be tested - - - - Asserts that two objects refer to the same object. If they - are not the same an is thrown. - - The message to be printed when the two objects are not the same object. - The expected object - The actual object - - - - Asserts that two objects refer to the same object. If they - are not the same an is thrown. - - The expected object - The actual object - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Asserts that two objects refer to the same object. If they - are not the same an is thrown. - - The expected object - The actual object - - - - Throws an with the message that is - passed in. This is used by the other Assert functions. - - - The format of the message to initialize the with. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - Throws an with the message that is - passed in. This is used by the other Assert functions. - - The message to initialize the with. - - - - Throws an with the message that is - passed in. This is used by the other Assert functions. - - - - - Makes the current test ignored using like - formatting - - - - - - - Makes the current test ignored using like - formatting - - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is strictly lower than - . - - - - - Verifies that is lower equal than - . - - - - - Verifies that is lower equal than - . - - - - - Verifies that is lower equal than - . - - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - The message that will be displayed on failure - - - - Verifies that the first value is less than the second - value. If it is not, then an - is thrown. - - The first value, expected to be less - The second value, expected to be greater - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - The message that will be displayed on failure - - - - Verifies that the first value is greater than the second - value. If they are not, then an - is thrown. - - The first value, expected to be greater - The second value, expected to be less - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Verifies that is strictly greater than - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is not between and - . - - - - - Asserts that is in the dic . - - - - - Asserts that is in the dic . - - - - - Asserts that is in the list . - - - - - Asserts that is in the list . - - - - - Asserts that is in the enumerable collection . - - - - - Asserts that is in the enumerable collection . - - - - - Asserts that is not in the dic . - - - - - Asserts that is not in the dic . - - - - - Asserts that is not in the list . - - - - - Asserts that is not in the list . - - - - - Asserts that is not in the enumerable collection . - - - - - Asserts that is not in the enumerable collection . - - - - - Assert that a string is empty - that is equal to string.Empty - - The string to be tested - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that a string is empty - that is equal to string.Emtpy - - The string to be tested - The message to be displayed on failure - - - - Assert that a string is empty - that is equal to string.Emtpy - - The string to be tested - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - The message to be displayed on failure - - - - Assert that an array,list or other collection is empty - - An array, list or other collection implementing ICollection - - - - Assert that a string is empty - that is equal to string.Emtpy - - The string to be tested - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that a string is empty - that is equal to string.Emtpy - - The string to be tested - The message to be displayed on failure - - - - Assert that a string is empty - that is equal to string.Emtpy - - The string to be tested - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - The message to be displayed on failure - Arguments to be used in formatting the message - - - - Assert that an array, list or other collection is empty - - An array, list or other collection implementing ICollection - The message to be displayed on failure - - - - Assert that an array,list or other collection is empty - - An array, list or other collection implementing ICollection - - - - Verifies that the double is passed is an NaN value. - If the object is not NaN then an - is thrown. - - The value that is to be tested - The message to be displayed when the object is not null - Arguments to be used in formatting the message - - - - Verifies that the double is passed is an NaN value. - If the object is not NaN then an - is thrown. - - The object that is to be tested - The message to be displayed when the object is not null - - - - Verifies that the double is passed is an NaN value. - If the object is not NaN then an - is thrown. - - The object that is to be tested - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - The messge to display in case of failure - - - - Asserts that an object may be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - The messge to display in case of failure - - - - Asserts that an object may not be assigned a value of a given Type. - - The expected Type. - The object under examination - The message to display in case of failure - Array of objects to be used in formatting the message - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - A message to display in case of failure - - - - Asserts that an object is an instance of a given type. - - The expected Type - The object being examined - A message to display in case of failure - An array of objects to be used in formatting the message - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - A message to display in case of failure - - - - Asserts that an object is not an instance of a given type. - - The expected Type - The object being examined - A message to display in case of failure - An array of objects to be used in formatting the message - - - - This method is called when two objects have been compared and found to be - different. This prints a nice message to the screen. - - The expected object - The actual object - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - This method is called when the two objects are not the same. - - The expected object - The actual object - - The format of the message to display if the assertion fails, - containing zero or more format items. - - - An array containing zero or more objects to format. - - - - The error message is formatted using . - - - - - - This attribute identifies the author of a test fixture. - - - - - - Assertion helper for the class. - - - - This class contains static helper methods to verify assertions on the - class. - - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property - is synchronized with the number of iterated elements. - - - Collection to test - - - is a null reference (Nothing in Visual Basic) - - - - - Verifies that and - are equal collections. Element count and element wize equality is verified. - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that and - are equal collections. Element count and element wize equality is verified. - - - Expected value. - - - Instance containing the tested value. - - - - - Asserts that all items contained in collection are of the type specified by expectedType. - - ICollection of objects to be considered - System.Type that all objects in collection must be instances of - - - - Asserts that all items contained in collection are of the type specified by expectedType. - - ICollection of objects to be considered - System.Type that all objects in collection must be instances of - The message that will be displayed on failure - - - - Asserts that all items contained in collection are of the type specified by expectedType. - - ICollection of objects to be considered - System.Type that all objects in collection must be instances of - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that all items contained in collection are not equal to null. - - ICollection of objects to be considered - - - - Asserts that all items contained in collection are not equal to null. - - ICollection of objects to be considered - The message that will be displayed on failure - - - - Asserts that all items contained in collection are not equal to null. - - ICollection of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Ensures that every object contained in collection exists within the collection - once and only once. - - ICollection of objects to be considered - - - - Ensures that every object contained in collection exists within the collection - once and only once. - - ICollection of objects to be considered - The message that will be displayed on failure - - - - Ensures that every object contained in collection exists within the collection - once and only once. - - ICollection of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - - - - Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are not exactly equal. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - - - - Asserts that expected and actual are not exactly equal. - If comparer is not null then it will be used to compare the objects. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The IComparer to use in comparing objects from each ICollection - - - - Asserts that expected and actual are not exactly equal. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are not exactly equal. - If comparer is not null then it will be used to compare the objects. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The IComparer to use in comparing objects from each ICollection - The message that will be displayed on failure - - - - Asserts that expected and actual are not exactly equal. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are not exactly equal. - If comparer is not null then it will be used to compare the objects. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The IComparer to use in comparing objects from each ICollection - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that expected and actual are not equivalent. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - - - - Asserts that expected and actual are not equivalent. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The message that will be displayed on failure - - - - Asserts that expected and actual are not equivalent. - - The first ICollection of objects to be considered - The second ICollection of objects to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that collection contains actual as an item. - - ICollection of objects to be considered - Object to be found within collection - - - - Asserts that collection contains actual as an item. - - ICollection of objects to be considered - Object to be found within collection - The message that will be displayed on failure - - - - Asserts that collection contains actual as an item. - - ICollection of objects to be considered - Object to be found within collection - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that collection does not contain actual as an item. - - ICollection of objects to be considered - Object that cannot exist within collection - - - - Asserts that collection does not contain actual as an item. - - ICollection of objects to be considered - Object that cannot exist within collection - The message that will be displayed on failure - - - - Asserts that collection does not contain actual as an item. - - ICollection of objects to be considered - Object that cannot exist within collection - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that superset is not a subject of subset. - - The ICollection superset to be considered - The ICollection subset to be considered - - - - Asserts that superset is not a subject of subset. - - The ICollection superset to be considered - The ICollection subset to be considered - The message that will be displayed on failure - - - - Asserts that superset is not a subject of subset. - - The ICollection superset to be considered - The ICollection subset to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Asserts that superset is a subset of subset. - - The ICollection superset to be considered - The ICollection subset to be considered - - - - Asserts that superset is a subset of subset. - - The ICollection superset to be considered - The ICollection subset to be considered - The message that will be displayed on failure - - - - Asserts that superset is a subset of subset. - - The ICollection superset to be considered - The ICollection subset to be considered - The message that will be displayed on failure - Arguments to be used in formatting the message - - - - Collection indexing pattern. - - - -The implements the Collection Indexing Pattern. - - -The user provides filled collection, index type and index range through -the attribute. - - - - -This example checks the Collection Indexing Pattern for the -and collections: - - - - - - - - Base class for attributes that define test fixtures. - - - - - - Base class for all attributes that are part of the MbUnit framework. - - - Base class for all attributes of MbUnit. - - - - - Gets or sets the fixture timeout in minutes. - - - Default value is 5 minutes. - - - Time out minutes. - - - - - Default constructor - - - - - Constructor with fixture description - - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - -This example checks the Collection Indexing Pattern for the -and collections: - - - - - - - - Different collection order - - - - Tests ascending order collection - - - Tests ascending order collection - - - - Collection Order Pattern implementations. - - -Implements: Collection Order Pattern -Logic: - -{Provider} -[SetUp] -{Fill} -(Order) // internal -[TearDown] - - - -This fixture tests sorted collections. The user must provider a -comparer and the type of desired test based on the -enumeration: ascending, descending. - - -Tested collections are provided by methods tagged with the -attribute. The collection are then filled using methods tagged by the - attribute. The rest of the tests is handled by the framework. - - -SetUp and TearDown methods can be added to set up the fixtue object. - - - - - - Tag use to mark a mark a unit test method. - - - - - - Base class for attributes that define unit test. - - - - - - Assertion helper for compilation. - - - - This class contains static helper methods to verify that snippets are compilable. - - - - - - Verifies that compiles using the provided compiler. - - Compiler instance - Source code to compile - - - - Verifies that compiles using the provided compiler. - - Compiler instance - Source code to compile - - - - Verifies that compiles using the provided compiler. - - Compiler instance - Referenced assemblies - Source code to compile - - - - Verifies that compiles using the provided compiler. - - - instance. - Compilation options - source to compile - - - - Verifies that compiles using the provided compiler. - - - instance. - Compilation options - Source to compile - - true if assertion should throw if any warning. - - - - - Verifies that compiles using the provided compiler. - - - instance. - Compilation options - Stream containing the source to compile - - - - Verifies that compiles using the provided compiler. - - - instance. - Compilation options - Stream containing the source to compile - - true if assertion should throw if any warning. - - - - - Verifies that does not compile using the provided compiler. - - - instance. - Source to compile - - - - Verifies that does not compile using the provided compiler. - - - instance. - Source to compile - - - - Verifies that does not compile using the provided compiler. - - - instance. - Collection of referenced assemblies - Source to compile - - - - Verifies that does not compile using the provided compiler. - - - instance. - Compilation options - Source to compile - - - - Verifies that does not compile using the provided compiler. - - - instance. - Compilation options - Source to compile - - - - Gets the C# compiler from . - - - C# compiler. - - - - - Gets the VB.NET compiler from . - - - VB.NET compiler. - - - - - - - - - This interface defines a type of test/non test run that is used - to define the logic. - - - - - Populates the invoker graph - with generated by the run. - - Invoker tree - parent vertex - class type that is marked by the run - - - - - - Gets a descriptive name of the - - - A descriptive name of the - - - - - Gets a value indicating the run is considered as a test or not. - - - true if the instance is a test - - - - - Populates the invoker graph - with generated by the run. - - Invoker tree - parent vertex - class type that is marked by the run - - TODO - - - - - Gets a descriptive name of the - - - A descriptive name of the - - - - - Gets a value indicating the run is considered as a test or not. - - - true if the instance is a test - - - - - Composite fixture pattern implementation. - - - - - - Creates a fixture for the type. - - - Initializes the attribute with . - - type to apply the fixture to - - - is a null reference - - - - Creates a fixture for the type - and a description - - - Initializes the attribute with . - - type to apply the fixture to - description of the fixture - fixtureType is a null reference - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - - - Gets or sets the fixture type. - - - Fixture instance type. - - - - - This interface defines a method invoker object. - - - -When processing the test fixture, the tests are splitted down to a -tree instance where each denotes -the invokation of a fixture method, or a special processing of the fixture methods. - - -The derived fixture define their logic by returning -an instance. This instance is the generator -for instances. - - - - - - Executes the wrapped method - - - Test fixture instance - - - Method arguments - - - Return value of the invoked method. If the method returns void, null - is returned. - - - - - Gets a value indicating if the instance is related to - - - - A instance - - - true if the instance is related to the member info; - otherwize false - - - - Gets a descriptive name of the - - - A descriptive name of the . - - - - - Gets a reference to the instance that generated - the invoker. - - - Reference to the instance that generated - the invoker. - - - - - Tags method that should throw an exception if a predicate is true. - - - - - Tags method that should throw an exception. - - - - - - This is the base class for attributes that can decorate tests. - - - - - - Assertion helper for the class. - - - - This class contains static helper methods to verify assertions on the - class. - - - This class was automatically generated. Do not edit (or edit the template). - - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - is true. - - - Instance containing the expected value. - - - - - Verifies that the property value - is false. - - - Instance containing the expected value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of and are equal. - - - Instance containing the expected value. - - - Instance containing the tested value. - - - - - Verifies that the property value - of is equal to . - - - Expected value. - - - Instance containing the tested value. - - - - - Tags method that provider a new object and copy the content of the arguments - into the object - - - - - - Tags method that provide new object to be used in the following tests. - - - - - - Constructs a provider attribute for the - type. - - provider type - - - - Constructs a provider attribute for the - type. - - provider type - description of the provider - - - - Gets or sets the provided type - - - Provided type. - - - - - Event argument that contains an assembly. - - - - - Creates a new event argument. - - - - Assembly event delegate - - - - A collection of elements of type Assembly - - - - - Initializes a new empty instance of the AssemblyCollection class. - - - - - Adds an instance of type Assembly to the end of this AssemblyCollection. - - - The Assembly to be added to the end of this AssemblyCollection. - - - - - Determines whether a specfic Assembly value is in this AssemblyCollection. - - - The Assembly value to locate in this AssemblyCollection. - - - true if value is found in this AssemblyCollection; - false otherwise. - - - - - Removes the first occurrence of a specific Assembly from this AssemblyCollection. - - - The Assembly value to remove from this AssemblyCollection. - - - - - Returns an enumerator that can iterate through the elements of this AssemblyCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the Assembly at the given index in this AssemblyCollection. - - - - - Type-specific enumeration class, used by AssemblyCollection.GetEnumerator. - - - - - A dictionary with keys of type Assembly and values of type TypeCollection - - - - - Initializes a new empty instance of the AssemblyTypeCollectionDictionary class - - - - - Adds an element with the specified key and value to this AssemblyTypeCollectionDictionary. - - - The Assembly key of the element to add. - - - - - Determines whether this AssemblyTypeCollectionDictionary contains a specific key. - - - The Assembly key to locate in this AssemblyTypeCollectionDictionary. - - - true if this AssemblyTypeCollectionDictionary contains an element with the specified key; - otherwise, false. - - - - - Removes the element with the specified key from this AssemblyTypeCollectionDictionary. - - - The Assembly key of the element to remove. - - - - - Gets or sets the TypeCollection associated with the given Assembly - - - The Assembly whose value to get or set. - - - - - Gets a collection containing the keys in this AssemblyTypeCollectionDictionary. - - - - - Gets a collection containing the values in this AssemblyTypeCollectionDictionary. - - - - - Summary description for AttributedMethodCollection. - - - - - Summary description for AttributedMethodEnumerator. - - - - - Summary description for AttributedMethodCollection. - - - - - Summary description for AttributedPropertyEnumerator. - - - - - Initializes a new empty instance of the FixtureCollection class. - - - - - Adds an instance of type Fixture to the end of this FixtureCollection. - - - The Fixture to be added to the end of this FixtureCollection. - - - - - Determines whether a specfic Fixture value is in this FixtureCollection. - - - The Fixture value to locate in this FixtureCollection. - - - true if value is found in this FixtureCollection; - false otherwise. - - - - - Removes the first occurrence of a specific Fixture from this FixtureCollection. - - - The Fixture value to remove from this FixtureCollection. - - - - - Returns an enumerator that can iterate through the elements of this FixtureCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Type-specific enumeration class, used by FixtureCollection.GetEnumerator. - - - - - A collection of elements of type IFixtureFactory - - - - - Initializes a new empty instance of the FixtureFactoryCollection class. - - - - - Adds an instance of type IFixtureFactory to the end of this FixtureFactoryCollection. - - - The IFixtureFactory to be added to the end of this FixtureFactoryCollection. - - - - - Determines whether a specfic IFixtureFactory value is in this FixtureFactoryCollection. - - - The IFixtureFactory value to locate in this FixtureFactoryCollection. - - - true if value is found in this FixtureFactoryCollection; - false otherwise. - - - - - Removes the first occurrence of a specific IFixtureFactory from this FixtureFactoryCollection. - - - The IFixtureFactory value to remove from this FixtureFactoryCollection. - - - - - Returns an enumerator that can iterate through the elements of this FixtureFactoryCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Type-specific enumeration class, used by FixtureFactoryCollection.GetEnumerator. - - - - - A collection of elements of type IRun - - - - - Initializes a new empty instance of the RunCollection class. - - - - - Adds an instance of type IRun to the end of this RunCollection. - - - The IRun to be added to the end of this RunCollection. - - - - - Determines whether a specfic IRun value is in this RunCollection. - - - The IRun value to locate in this RunCollection. - - - true if value is found in this RunCollection; - false otherwise. - - - - - Removes the first occurrence of a specific IRun from this RunCollection. - - - The IRun value to remove from this RunCollection. - - - - - Returns an enumerator that can iterate through the elements of this RunCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the IRun at the given index in this RunCollection. - - - - - Type-specific enumeration class, used by RunCollection.GetEnumerator. - - - - - A collection of elements of type IRunInvoker - - - - - Initializes a new empty instance of the IRunInvokerCollection class. - - - - - Adds an instance of type IRunInvoker to the end of this IRunInvokerCollection. - - - The IRunInvoker to be added to the end of this IRunInvokerCollection. - - - - - Determines whether a specfic IRunInvoker value is in this IRunInvokerCollection. - - - The IRunInvoker value to locate in this IRunInvokerCollection. - - - true if value is found in this IRunInvokerCollection; - false otherwise. - - - - - Removes the first occurrence of a specific IRunInvoker from this IRunInvokerCollection. - - - The IRunInvoker value to remove from this IRunInvokerCollection. - - - - - Returns an enumerator that can iterate through the elements of this IRunInvokerCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the IRunInvoker at the given index in this IRunInvokerCollection. - - - - - Type-specific enumeration class, used by IRunInvokerCollection.GetEnumerator. - - - - - A collection of elements of type RunInvokerVertex - - - - - Initializes a new empty instance of the RunInvokerVertexCollection class. - - - - - Adds an instance of type RunInvokerVertex to the end of this RunInvokerVertexCollection. - - - The RunInvokerVertex to be added to the end of this RunInvokerVertexCollection. - - - - - Determines whether a specfic RunInvokerVertex value is in this RunInvokerVertexCollection. - - - The RunInvokerVertex value to locate in this RunInvokerVertexCollection. - - - true if value is found in this RunInvokerVertexCollection; - false otherwise. - - - - - Removes the first occurrence of a specific RunInvokerVertex from this RunInvokerVertexCollection. - - - The RunInvokerVertex value to remove from this RunInvokerVertexCollection. - - - - - Returns an enumerator that can iterate through the elements of this RunInvokerVertexCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the RunInvokerVertex at the given index in this RunInvokerVertexCollection. - - - - - Type-specific enumeration class, used by RunInvokerVertexCollection.GetEnumerator. - - - - - A collection of elements of type RunInvokerVertexCollection - - - - - Initializes a new empty instance of the RunInvokerVertexCollectionCollection class. - - - - - Adds an instance of type RunInvokerVertexCollection to the end of this RunInvokerVertexCollectionCollection. - - - The RunInvokerVertexCollection to be added to the end of this RunInvokerVertexCollectionCollection. - - - - - Determines whether a specfic RunInvokerVertexCollection value is in this RunInvokerVertexCollectionCollection. - - - The RunInvokerVertexCollection value to locate in this RunInvokerVertexCollectionCollection. - - - true if value is found in this RunInvokerVertexCollectionCollection; - false otherwise. - - - - - Removes the first occurrence of a specific RunInvokerVertexCollection from this RunInvokerVertexCollectionCollection. - - - The RunInvokerVertexCollection value to remove from this RunInvokerVertexCollectionCollection. - - - - - Returns an enumerator that can iterate through the elements of this RunInvokerVertexCollectionCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the RunInvokerVertexCollection at the given index in this RunInvokerVertexCollectionCollection. - - - - - Type-specific enumeration class, used by RunInvokerVertexCollectionCollection.GetEnumerator. - - - - - A collection of elements of type RunPipe - - - - - Initializes a new empty instance of the RunPipeCollection class. - - - - - Adds an instance of type RunPipe to the end of this RunPipeCollection. - - - The RunPipe to be added to the end of this RunPipeCollection. - - - - - Determines whether a specfic RunPipe value is in this RunPipeCollection. - - - The RunPipe value to locate in this RunPipeCollection. - - - true if value is found in this RunPipeCollection; - false otherwise. - - - - - Removes the first occurrence of a specific RunPipe from this RunPipeCollection. - - - The RunPipe value to remove from this RunPipeCollection. - - - - - Returns an enumerator that can iterate through the elements of this RunPipeCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the RunPipe at the given index in this RunPipeCollection. - - - - - Type-specific enumeration class, used by RunPipeCollection.GetEnumerator. - - - - - A collection of elements of type IRunPipeListener - - - - - Initializes a new empty instance of the RunPipeListenerCollection class. - - - - - Adds an instance of type IRunPipeListener to the end of this RunPipeListenerCollection. - - - The IRunPipeListener to be added to the end of this RunPipeListenerCollection. - - - - - Determines whether a specfic IRunPipeListener value is in this RunPipeListenerCollection. - - - The IRunPipeListener value to locate in this RunPipeListenerCollection. - - - true if value is found in this RunPipeListenerCollection; - false otherwise. - - - - - Removes the first occurrence of a specific IRunPipeListener from this RunPipeListenerCollection. - - - The IRunPipeListener value to remove from this RunPipeListenerCollection. - - - - - Returns an enumerator that can iterate through the elements of this RunPipeListenerCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Type-specific enumeration class, used by RunPipeListenerCollection.GetEnumerator. - - - - - A collection of elements of type RunPipeStarter - - - - - Initializes a new empty instance of the RunPipeStarterCollection class. - - - - - Adds an instance of type RunPipeStarter to the end of this RunPipeStarterCollection. - - - The RunPipeStarter to be added to the end of this RunPipeStarterCollection. - - - - - Determines whether a specfic RunPipeStarter value is in this RunPipeStarterCollection. - - - The RunPipeStarter value to locate in this RunPipeStarterCollection. - - - true if value is found in this RunPipeStarterCollection; - false otherwise. - - - - - Removes the first occurrence of a specific RunPipeStarter from this RunPipeStarterCollection. - - - The RunPipeStarter value to remove from this RunPipeStarterCollection. - - - - - Returns an enumerator that can iterate through the elements of this RunPipeStarterCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Type-specific enumeration class, used by RunPipeStarterCollection.GetEnumerator. - - - - - A dictionary with keys of type IRun and values of type RunVertex - - - - - Initializes a new empty instance of the RunVertexDictionary class - - - - - Adds an element with the specified key and value to this RunVertexDictionary. - - - The IRun key of the element to add. - - - The RunVertex value of the element to add. - - - - - Determines whether this RunVertexDictionary contains a specific key. - - - The IRun key to locate in this RunVertexDictionary. - - - true if this RunVertexDictionary contains an element with the specified key; - otherwise, false. - - - - - Determines whether this RunVertexDictionary contains a specific value. - - - The RunVertex value to locate in this RunVertexDictionary. - - - true if this RunVertexDictionary contains an element with the specified value; - otherwise, false. - - - - - Removes the element with the specified key from this RunVertexDictionary. - - - The IRun key of the element to remove. - - - - - Gets or sets the RunVertex associated with the given IRun - - - The IRun whose value to get or set. - - - - - Gets a collection containing the keys in this RunVertexDictionary. - - - - - Gets a collection containing the values in this RunVertexDictionary. - - - - - A collection of elements of type Thread - - - - - Initializes a new empty instance of the ThreadCollection class. - - - - - Adds an instance of type Thread to the end of this ThreadCollection. - - - The Thread to be added to the end of this ThreadCollection. - - - - - Determines whether a specfic Thread value is in this ThreadCollection. - - - The Thread value to locate in this ThreadCollection. - - - true if value is found in this ThreadCollection; - false otherwise. - - - - - Removes the first occurrence of a specific Thread from this ThreadCollection. - - - The Thread value to remove from this ThreadCollection. - - - - - Returns an enumerator that can iterate through the elements of this ThreadCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the Thread at the given index in this ThreadCollection. - - - - - Type-specific enumeration class, used by ThreadCollection.GetEnumerator. - - - - - Summary description for ThreadCollectionRunner. - - - - - A collection of elements of type Type - - - - - Initializes a new empty instance of the TypeCollection class. - - - - - Adds an instance of type Type to the end of this TypeCollection. - - - The Type to be added to the end of this TypeCollection. - - - - - Determines whether a specfic Type value is in this TypeCollection. - - - The Type value to locate in this TypeCollection. - - - true if value is found in this TypeCollection; - false otherwise. - - - - - Removes the first occurrence of a specific Type from this TypeCollection. - - - The Type value to remove from this TypeCollection. - - - - - Returns an enumerator that can iterate through the elements of this TypeCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the Type at the given index in this TypeCollection. - - - - - Type-specific enumeration class, used by TypeCollection.GetEnumerator. - - - - - Allows control of command line parsing. - Attach this attribute to instance fields of types used - as the destination of command line argument parsing. - - - - Command line parsing code from Peter Halam, - http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e - - - - - - Allows control of command line parsing. - - Specifies the error checking to be done on the argument. - - - - The error checking to be done on the argument. - - - - - Returns true if the argument did not have an explicit short name specified. - - - - - The short name of the argument. - - - - - Returns true if the argument did not have an explicit long name specified. - - - - - The long name of the argument. - - - - - Parser for command line arguments. - - - - The parser specification is infered from the instance fields of the object - specified as the destination of the parse. - Valid argument types are: int, uint, string, bool, enums - Also argument types of Array of the above types are also valid. - - - Error checking options can be controlled by adding a CommandLineArgumentAttribute - to the instance fields of the destination object. - - - At most one field may be marked with the DefaultCommandLineArgumentAttribute - indicating that arguments without a '-' or '/' prefix will be parsed as that argument. - - - If not specified then the parser will infer default options for parsing each - instance field. The default long name of the argument is the field name. The - default short name is the first character of the long name. Long names and explicitly - specified short names must be unique. Default short names will be used provided that - the default short name does not conflict with a long name or an explicitly - specified short name. - - - Arguments which are array types are collection arguments. Collection - arguments can be specified multiple times. - - - Command line parsing code from Peter Halam, - http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e - - - - - - Creates a new command line argument parser. - - The type of object to parse. - The destination for parse errors. - - - - Parses an argument list into an object - - - - true if an error occurred - - - - Parses an argument list. - - The arguments to parse. - The destination of the parsed arguments. - true if no parse errors were encountered. - - - - A user firendly usage string describing the command line argument syntax. - - - - - Used to control parsing of command line arguments. - - - - Command line parsing code from Peter Halam, - http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e - - - - - - Indicates that this field is required. An error will be displayed - if it is not present when parsing arguments. - - - - - Only valid in conjunction with Multiple. - Duplicate values will result in an error. - - - - - Inidicates that the argument may be specified more than once. - Only valid if the argument is a collection - - - - - The default type for non-collection arguments. - The argument is not required, but an error will be reported if it is specified more than once. - - - - - For non-collection arguments, when the argument is specified more than - once no error is reported and the value of the argument is the last - value which occurs in the argument list. - - - - - The default type for collection arguments. - The argument is permitted to occur multiple times, but duplicate - values will cause an error to be reported. - - - - - Useful Stuff. - - - - Command line parsing code from Peter Halam, - http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e - - - - - - The System Defined new line string. - - - - - Don't ever call this. - - - - - Parses Command Line Arguments. - Errors are output on Console.Error. - Use CommandLineArgumentAttributes to control parsing behaviour. - - The actual arguments. - The resulting parsed arguments. - - - - Parses Command Line Arguments. - Use CommandLineArgumentAttributes to control parsing behaviour. - - The actual arguments. - The resulting parsed arguments. - The destination for parse errors. - - - - Returns a Usage string for command line argument parsing. - Use CommandLineArgumentAttributes to control parsing behaviour. - - The type of the arguments to display usage for. - Printable string containing a user friendly description of command line arguments. - - - - Indicates that this argument is the default argument. - '/' or '-' prefix only the argument value is specified. - - - - Command line parsing code from Peter Halam, - http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e - - - - - - Indicates that this argument is the default argument. - - Specifies the error checking to be done on the argument. - - - - A delegate used in error reporting. - - - - Command line parsing code from Peter Halam, - http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e - - - - - - This method is used to provide assembly location resolver. It is called on event as needed by the CLR. - Refer to document related to AppDomain.CurrentDomain.AssemblyResolve - - - - - Base class for MbUnit exceptions - - - - - Initializes an empty - instance. - - - - - Exception throwed when not finding a vertex. - - - - - Exception throwed when not finding a vertex. - - - - - Creates an exception with a message - and an inner exception. - - Error message - Inner exception - - - - - - - - - - - - - - - - - Returns true if the entire test fixture is ignored. - - - - - This is the base class for attributes that can decorate fixtures. - - - - - - Base class for attributes that tag method that are usualy used to - set up, provide data, tear down tests, etc... - - - - - - An invoker that wraps up the call to a fixture method. - - - - - Default constructor - initializes all fields to default values - - - - - Decorator invorkers are used to modify the way a fixute method is executed. - Popular examples of such is the - or the . - - - - - Default constructor - initializes all fields to default values - - - + + + + MbUnit.Framework + + + + + Array Assertion class + + + + + A private constructor disallows any instances of this object. + + + + + Verifies that both array have the same dimension and elements. + + + + + + + Assertion class + + + + + + The Equals method throws an AssertionException. This is done + to make sure there is no mistake by calling this function. + + + + + + + override the default ReferenceEquals to throw an AssertionException. This + implementation makes sure there is no mistake in calling this function + as part of Assert. + + + + + + + Checks the type of the object, returning true if + the object is a numeric type. + + The object to check + true if the object is a numeric type + + + + Used to compare numeric types. Comparisons between + same types are fine (Int32 to Int32, or Int64 to Int64), + but the Equals method fails across different types. + This method was added to allow any numeric type to + be handled correctly, by using ToString and + comparing the result + + + + + + + + A private constructor disallows any instances of this object. + + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + The format of the message to display if the condition is false, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Asserts that a condition is true. If the condition is false the method throws + an . + + The evaluated condition + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + The format of the message to display if the condition is false, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Asserts that a condition is false. If the condition is true the method throws + an . + + The evaluated condition + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equals then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + The message printed out upon failure + + + + Verifies that two doubles are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equals then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two floats are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equals then an is + thrown. + + The message printed out upon failure + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two floats are equal considering a delta. If the + expected value is infinity then the delta value is ignored. If + they are not equals then an is + thrown. + + The expected value + The actual value + The maximum acceptable difference between the + the expected and the actual + + + + Verifies that two decimals are equal. If + they are not equals then an is + thrown. + + The message printed out upon failure + The expected value + The actual value + + + + Verifies that two decimals are equal. If + they are not equals then an is + thrown. + + The expected value + The actual value + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Verifies that two decimals are equal. If + they are not equals then an is + thrown. + + The expected value + The actual value + + + + Verifies that two ints are equal. If + they are not equals then an is + thrown. + + The message printed out upon failure + The expected value + The actual value + + + + Verifies that two ints are equal. If + they are not equals then an is + thrown. + + The expected value + The actual value + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Verifies that two ints are equal. If + they are not equals then an is + thrown. + + The expected value + The actual value + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. All + non-numeric types are compared by using the Equals method. + If they are not equal an is thrown. + + The value that is expected + The actual value + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. All + non-numeric types are compared by using the Equals method. + If they are not equal an is thrown. + + The value that is expected + The actual value + The message to display if objects are not equal + + + + Verifies that two objects are equal. Two objects are considered + equal if both are null, or if both have the same value. All + non-numeric types are compared by using the Equals method. + If they are not equal an is thrown. + + The value that is expected + The actual value + + + + Verifies that the value of the property described by is the same + in both ojects. + + + Property describing the value to test + + + Reference object + + + Actual object + + + Index of the property. + + + + + Asserts that two objects are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two objects are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two objects are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Asserts that two objects are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two objects are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two objects are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Asserts that two ints are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two ints are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two ints are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Asserts that two uints are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two uints are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two uints are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Asserts that two decimals are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two decimals are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two decimals are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Asserts that two floats are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two floats are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two floats are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Asserts that two doubles are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the two objects are the same object. + Arguments to be used in formatting the message + + + + Asserts that two doubles are not equal. If they are equal + an is thrown. + + The expected object + The actual object + The message to be displayed when the objects are the same + + + + Asserts that two doubles are not equal. If they are equal + an is thrown. + + The expected object + The actual object + + + + Verifies that the object that is passed in is not equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Verifies that the object that is passed in is not equal to null + If the object is not null then an + is thrown. + + The object that is to be tested + + + + Verifies that the object that is passed in is equal to null + If the object is null then an + is thrown. + + The object that is to be tested + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Verifies that the object that is passed in is equal to null + If the object is null then an + is thrown. + + The object that is to be tested + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The message to be printed when the two objects are not the same object. + The expected object + The actual object + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Asserts that two objects refer to the same object. If they + are not the same an is thrown. + + The expected object + The actual object + + + + Throws an with the message that is + passed in. This is used by the other Assert functions. + + + The format of the message to initialize the with. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + Throws an with the message that is + passed in. This is used by the other Assert functions. + + The message to initialize the with. + + + + Throws an with the message that is + passed in. This is used by the other Assert functions. + + + + + Makes the current test ignored using like + formatting + + + + + + + Makes the current test ignored using like + formatting + + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is strictly lower than + . + + + + + Verifies that is lower equal than + . + + + + + Verifies that is lower equal than + . + + + + + Verifies that is lower equal than + . + + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + The message that will be displayed on failure + + + + Verifies that the first value is less than the second + value. If it is not, then an + is thrown. + + The first value, expected to be less + The second value, expected to be greater + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + The message that will be displayed on failure + + + + Verifies that the first value is greater than the second + value. If they are not, then an + is thrown. + + The first value, expected to be greater + The second value, expected to be less + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Verifies that is strictly greater than + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is not between and + . + + + + + Asserts that is in the dic . + + + + + Asserts that is in the dic . + + + + + Asserts that is in the list . + + + + + Asserts that is in the list . + + + + + Asserts that is in the enumerable collection . + + + + + Asserts that is in the enumerable collection . + + + + + Asserts that is not in the dic . + + + + + Asserts that is not in the dic . + + + + + Asserts that is not in the list . + + + + + Asserts that is not in the list . + + + + + Asserts that is not in the enumerable collection . + + + + + Asserts that is not in the enumerable collection . + + + + + Assert that a string is empty - that is equal to string.Empty + + The string to be tested + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that a string is empty - that is equal to string.Emtpy + + The string to be tested + The message to be displayed on failure + + + + Assert that a string is empty - that is equal to string.Emtpy + + The string to be tested + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to be displayed on failure + + + + Assert that an array,list or other collection is empty + + An array, list or other collection implementing ICollection + + + + Assert that a string is empty - that is equal to string.Emtpy + + The string to be tested + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that a string is empty - that is equal to string.Emtpy + + The string to be tested + The message to be displayed on failure + + + + Assert that a string is empty - that is equal to string.Emtpy + + The string to be tested + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to be displayed on failure + Arguments to be used in formatting the message + + + + Assert that an array, list or other collection is empty + + An array, list or other collection implementing ICollection + The message to be displayed on failure + + + + Assert that an array,list or other collection is empty + + An array, list or other collection implementing ICollection + + + + Verifies that the double is passed is an NaN value. + If the object is not NaN then an + is thrown. + + The value that is to be tested + The message to be displayed when the object is not null + Arguments to be used in formatting the message + + + + Verifies that the double is passed is an NaN value. + If the object is not NaN then an + is thrown. + + The object that is to be tested + The message to be displayed when the object is not null + + + + Verifies that the double is passed is an NaN value. + If the object is not NaN then an + is thrown. + + The object that is to be tested + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The messge to display in case of failure + + + + Asserts that an object may be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The messge to display in case of failure + + + + Asserts that an object may not be assigned a value of a given Type. + + The expected Type. + The object under examination + The message to display in case of failure + Array of objects to be used in formatting the message + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + A message to display in case of failure + + + + Asserts that an object is an instance of a given type. + + The expected Type + The object being examined + A message to display in case of failure + An array of objects to be used in formatting the message + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + A message to display in case of failure + + + + Asserts that an object is not an instance of a given type. + + The expected Type + The object being examined + A message to display in case of failure + An array of objects to be used in formatting the message + + + + This method is called when two objects have been compared and found to be + different. This prints a nice message to the screen. + + The expected object + The actual object + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + This method is called when the two objects are not the same. + + The expected object + The actual object + + The format of the message to display if the assertion fails, + containing zero or more format items. + + + An array containing zero or more objects to format. + + + + The error message is formatted using . + + + + + + This attribute identifies the author of a test fixture. + + + + + + Assertion helper for the class. + + + + This class contains static helper methods to verify assertions on the + class. + + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property + is synchronized with the number of iterated elements. + + + Collection to test + + + is a null reference (Nothing in Visual Basic) + + + + + Verifies that and + are equal collections. Element count and element wize equality is verified. + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that and + are equal collections. Element count and element wize equality is verified. + + + Expected value. + + + Instance containing the tested value. + + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + ICollection of objects to be considered + System.Type that all objects in collection must be instances of + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + ICollection of objects to be considered + System.Type that all objects in collection must be instances of + The message that will be displayed on failure + + + + Asserts that all items contained in collection are of the type specified by expectedType. + + ICollection of objects to be considered + System.Type that all objects in collection must be instances of + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that all items contained in collection are not equal to null. + + ICollection of objects to be considered + + + + Asserts that all items contained in collection are not equal to null. + + ICollection of objects to be considered + The message that will be displayed on failure + + + + Asserts that all items contained in collection are not equal to null. + + ICollection of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + ICollection of objects to be considered + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + ICollection of objects to be considered + The message that will be displayed on failure + + + + Ensures that every object contained in collection exists within the collection + once and only once. + + ICollection of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are equivalent, containing the same objects but the match may be in any order. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not exactly equal. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The IComparer to use in comparing objects from each ICollection + + + + Asserts that expected and actual are not exactly equal. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The IComparer to use in comparing objects from each ICollection + The message that will be displayed on failure + + + + Asserts that expected and actual are not exactly equal. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not exactly equal. + If comparer is not null then it will be used to compare the objects. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The IComparer to use in comparing objects from each ICollection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that expected and actual are not equivalent. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + + + + Asserts that expected and actual are not equivalent. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The message that will be displayed on failure + + + + Asserts that expected and actual are not equivalent. + + The first ICollection of objects to be considered + The second ICollection of objects to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that collection contains actual as an item. + + ICollection of objects to be considered + Object to be found within collection + + + + Asserts that collection contains actual as an item. + + ICollection of objects to be considered + Object to be found within collection + The message that will be displayed on failure + + + + Asserts that collection contains actual as an item. + + ICollection of objects to be considered + Object to be found within collection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that collection does not contain actual as an item. + + ICollection of objects to be considered + Object that cannot exist within collection + + + + Asserts that collection does not contain actual as an item. + + ICollection of objects to be considered + Object that cannot exist within collection + The message that will be displayed on failure + + + + Asserts that collection does not contain actual as an item. + + ICollection of objects to be considered + Object that cannot exist within collection + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that superset is not a subject of subset. + + The ICollection superset to be considered + The ICollection subset to be considered + + + + Asserts that superset is not a subject of subset. + + The ICollection superset to be considered + The ICollection subset to be considered + The message that will be displayed on failure + + + + Asserts that superset is not a subject of subset. + + The ICollection superset to be considered + The ICollection subset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Asserts that superset is a subset of subset. + + The ICollection superset to be considered + The ICollection subset to be considered + + + + Asserts that superset is a subset of subset. + + The ICollection superset to be considered + The ICollection subset to be considered + The message that will be displayed on failure + + + + Asserts that superset is a subset of subset. + + The ICollection superset to be considered + The ICollection subset to be considered + The message that will be displayed on failure + Arguments to be used in formatting the message + + + + Collection indexing pattern. + + + +The implements the Collection Indexing Pattern. + + +The user provides filled collection, index type and index range through +the attribute. + + + + +This example checks the Collection Indexing Pattern for the +and collections: + + + + + + + + Base class for attributes that define test fixtures. + + + + + + Base class for all attributes that are part of the MbUnit framework. + + + Base class for all attributes of MbUnit. + + + + + Gets or sets the fixture timeout in minutes. + + + Default value is 5 minutes. + + + Time out minutes. + + + + + Default constructor + + + + + Constructor with fixture description + + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + +This example checks the Collection Indexing Pattern for the +and collections: + + + + + + + + Different collection order + + + + Tests ascending order collection + + + Tests ascending order collection + + + + Collection Order Pattern implementations. + + +Implements: Collection Order Pattern +Logic: + +{Provider} +[SetUp] +{Fill} +(Order) // internal +[TearDown] + + + +This fixture tests sorted collections. The user must provider a +comparer and the type of desired test based on the +enumeration: ascending, descending. + + +Tested collections are provided by methods tagged with the +attribute. The collection are then filled using methods tagged by the + attribute. The rest of the tests is handled by the framework. + + +SetUp and TearDown methods can be added to set up the fixtue object. + + + + + + Tag use to mark a mark a unit test method. + + + + + + Base class for attributes that define unit test. + + + + + + Assertion helper for compilation. + + + + This class contains static helper methods to verify that snippets are compilable. + + + + + + Verifies that compiles using the provided compiler. + + Compiler instance + Source code to compile + + + + Verifies that compiles using the provided compiler. + + Compiler instance + Source code to compile + + + + Verifies that compiles using the provided compiler. + + Compiler instance + Referenced assemblies + Source code to compile + + + + Verifies that compiles using the provided compiler. + + + instance. + Compilation options + source to compile + + + + Verifies that compiles using the provided compiler. + + + instance. + Compilation options + Source to compile + + true if assertion should throw if any warning. + + + + + Verifies that compiles using the provided compiler. + + + instance. + Compilation options + Stream containing the source to compile + + + + Verifies that compiles using the provided compiler. + + + instance. + Compilation options + Stream containing the source to compile + + true if assertion should throw if any warning. + + + + + Verifies that does not compile using the provided compiler. + + + instance. + Source to compile + + + + Verifies that does not compile using the provided compiler. + + + instance. + Source to compile + + + + Verifies that does not compile using the provided compiler. + + + instance. + Collection of referenced assemblies + Source to compile + + + + Verifies that does not compile using the provided compiler. + + + instance. + Compilation options + Source to compile + + + + Verifies that does not compile using the provided compiler. + + + instance. + Compilation options + Source to compile + + + + Gets the C# compiler from . + + + C# compiler. + + + + + Gets the VB.NET compiler from . + + + VB.NET compiler. + + + + + + + + + This interface defines a type of test/non test run that is used + to define the logic. + + + + + Populates the invoker graph + with generated by the run. + + Invoker tree + parent vertex + class type that is marked by the run + + + + + + Gets a descriptive name of the + + + A descriptive name of the + + + + + Gets a value indicating the run is considered as a test or not. + + + true if the instance is a test + + + + + Populates the invoker graph + with generated by the run. + + Invoker tree + parent vertex + class type that is marked by the run + + TODO + + + + + Gets a descriptive name of the + + + A descriptive name of the + + + + + Gets a value indicating the run is considered as a test or not. + + + true if the instance is a test + + + + + Composite fixture pattern implementation. + + + + + + Creates a fixture for the type. + + + Initializes the attribute with . + + type to apply the fixture to + + + is a null reference + + + + Creates a fixture for the type + and a description + + + Initializes the attribute with . + + type to apply the fixture to + description of the fixture + fixtureType is a null reference + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + + + Gets or sets the fixture type. + + + Fixture instance type. + + + + + This interface defines a method invoker object. + + + +When processing the test fixture, the tests are splitted down to a +tree instance where each denotes +the invokation of a fixture method, or a special processing of the fixture methods. + + +The derived fixture define their logic by returning +an instance. This instance is the generator +for instances. + + + + + + Executes the wrapped method + + + Test fixture instance + + + Method arguments + + + Return value of the invoked method. If the method returns void, null + is returned. + + + + + Gets a value indicating if the instance is related to + + + + A instance + + + true if the instance is related to the member info; + otherwize false + + + + Gets a descriptive name of the + + + A descriptive name of the . + + + + + Gets a reference to the instance that generated + the invoker. + + + Reference to the instance that generated + the invoker. + + + + + Tags method that should throw an exception if a predicate is true. + + + + + Tags method that should throw an exception. + + + + + + This is the base class for attributes that can decorate tests. + + + + + + Assertion helper for the class. + + + + This class contains static helper methods to verify assertions on the + class. + + + This class was automatically generated. Do not edit (or edit the template). + + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + is true. + + + Instance containing the expected value. + + + + + Verifies that the property value + is false. + + + Instance containing the expected value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of and are equal. + + + Instance containing the expected value. + + + Instance containing the tested value. + + + + + Verifies that the property value + of is equal to . + + + Expected value. + + + Instance containing the tested value. + + + + + Tags method that provider a new object and copy the content of the arguments + into the object + + + + + + Tags method that provide new object to be used in the following tests. + + + + + + Constructs a provider attribute for the + type. + + provider type + + + + Constructs a provider attribute for the + type. + + provider type + description of the provider + + + + Gets or sets the provided type + + + Provided type. + + + + + Event argument that contains an assembly. + + + + + Creates a new event argument. + + + + Assembly event delegate + + + + A collection of elements of type Assembly + + + + + Initializes a new empty instance of the AssemblyCollection class. + + + + + Adds an instance of type Assembly to the end of this AssemblyCollection. + + + The Assembly to be added to the end of this AssemblyCollection. + + + + + Determines whether a specfic Assembly value is in this AssemblyCollection. + + + The Assembly value to locate in this AssemblyCollection. + + + true if value is found in this AssemblyCollection; + false otherwise. + + + + + Removes the first occurrence of a specific Assembly from this AssemblyCollection. + + + The Assembly value to remove from this AssemblyCollection. + + + + + Returns an enumerator that can iterate through the elements of this AssemblyCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the Assembly at the given index in this AssemblyCollection. + + + + + Type-specific enumeration class, used by AssemblyCollection.GetEnumerator. + + + + + A dictionary with keys of type Assembly and values of type TypeCollection + + + + + Initializes a new empty instance of the AssemblyTypeCollectionDictionary class + + + + + Adds an element with the specified key and value to this AssemblyTypeCollectionDictionary. + + + The Assembly key of the element to add. + + + + + Determines whether this AssemblyTypeCollectionDictionary contains a specific key. + + + The Assembly key to locate in this AssemblyTypeCollectionDictionary. + + + true if this AssemblyTypeCollectionDictionary contains an element with the specified key; + otherwise, false. + + + + + Removes the element with the specified key from this AssemblyTypeCollectionDictionary. + + + The Assembly key of the element to remove. + + + + + Gets or sets the TypeCollection associated with the given Assembly + + + The Assembly whose value to get or set. + + + + + Gets a collection containing the keys in this AssemblyTypeCollectionDictionary. + + + + + Gets a collection containing the values in this AssemblyTypeCollectionDictionary. + + + + + Summary description for AttributedMethodCollection. + + + + + Summary description for AttributedMethodEnumerator. + + + + + Summary description for AttributedMethodCollection. + + + + + Summary description for AttributedPropertyEnumerator. + + + + + Initializes a new empty instance of the FixtureCollection class. + + + + + Adds an instance of type Fixture to the end of this FixtureCollection. + + + The Fixture to be added to the end of this FixtureCollection. + + + + + Determines whether a specfic Fixture value is in this FixtureCollection. + + + The Fixture value to locate in this FixtureCollection. + + + true if value is found in this FixtureCollection; + false otherwise. + + + + + Removes the first occurrence of a specific Fixture from this FixtureCollection. + + + The Fixture value to remove from this FixtureCollection. + + + + + Returns an enumerator that can iterate through the elements of this FixtureCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Type-specific enumeration class, used by FixtureCollection.GetEnumerator. + + + + + A collection of elements of type IFixtureFactory + + + + + Initializes a new empty instance of the FixtureFactoryCollection class. + + + + + Adds an instance of type IFixtureFactory to the end of this FixtureFactoryCollection. + + + The IFixtureFactory to be added to the end of this FixtureFactoryCollection. + + + + + Determines whether a specfic IFixtureFactory value is in this FixtureFactoryCollection. + + + The IFixtureFactory value to locate in this FixtureFactoryCollection. + + + true if value is found in this FixtureFactoryCollection; + false otherwise. + + + + + Removes the first occurrence of a specific IFixtureFactory from this FixtureFactoryCollection. + + + The IFixtureFactory value to remove from this FixtureFactoryCollection. + + + + + Returns an enumerator that can iterate through the elements of this FixtureFactoryCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Type-specific enumeration class, used by FixtureFactoryCollection.GetEnumerator. + + + + + A collection of elements of type IRun + + + + + Initializes a new empty instance of the RunCollection class. + + + + + Adds an instance of type IRun to the end of this RunCollection. + + + The IRun to be added to the end of this RunCollection. + + + + + Determines whether a specfic IRun value is in this RunCollection. + + + The IRun value to locate in this RunCollection. + + + true if value is found in this RunCollection; + false otherwise. + + + + + Removes the first occurrence of a specific IRun from this RunCollection. + + + The IRun value to remove from this RunCollection. + + + + + Returns an enumerator that can iterate through the elements of this RunCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the IRun at the given index in this RunCollection. + + + + + Type-specific enumeration class, used by RunCollection.GetEnumerator. + + + + + A collection of elements of type IRunInvoker + + + + + Initializes a new empty instance of the IRunInvokerCollection class. + + + + + Adds an instance of type IRunInvoker to the end of this IRunInvokerCollection. + + + The IRunInvoker to be added to the end of this IRunInvokerCollection. + + + + + Determines whether a specfic IRunInvoker value is in this IRunInvokerCollection. + + + The IRunInvoker value to locate in this IRunInvokerCollection. + + + true if value is found in this IRunInvokerCollection; + false otherwise. + + + + + Removes the first occurrence of a specific IRunInvoker from this IRunInvokerCollection. + + + The IRunInvoker value to remove from this IRunInvokerCollection. + + + + + Returns an enumerator that can iterate through the elements of this IRunInvokerCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the IRunInvoker at the given index in this IRunInvokerCollection. + + + + + Type-specific enumeration class, used by IRunInvokerCollection.GetEnumerator. + + + + + A collection of elements of type RunInvokerVertex + + + + + Initializes a new empty instance of the RunInvokerVertexCollection class. + + + + + Adds an instance of type RunInvokerVertex to the end of this RunInvokerVertexCollection. + + + The RunInvokerVertex to be added to the end of this RunInvokerVertexCollection. + + + + + Determines whether a specfic RunInvokerVertex value is in this RunInvokerVertexCollection. + + + The RunInvokerVertex value to locate in this RunInvokerVertexCollection. + + + true if value is found in this RunInvokerVertexCollection; + false otherwise. + + + + + Removes the first occurrence of a specific RunInvokerVertex from this RunInvokerVertexCollection. + + + The RunInvokerVertex value to remove from this RunInvokerVertexCollection. + + + + + Returns an enumerator that can iterate through the elements of this RunInvokerVertexCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the RunInvokerVertex at the given index in this RunInvokerVertexCollection. + + + + + Type-specific enumeration class, used by RunInvokerVertexCollection.GetEnumerator. + + + + + A collection of elements of type RunInvokerVertexCollection + + + + + Initializes a new empty instance of the RunInvokerVertexCollectionCollection class. + + + + + Adds an instance of type RunInvokerVertexCollection to the end of this RunInvokerVertexCollectionCollection. + + + The RunInvokerVertexCollection to be added to the end of this RunInvokerVertexCollectionCollection. + + + + + Determines whether a specfic RunInvokerVertexCollection value is in this RunInvokerVertexCollectionCollection. + + + The RunInvokerVertexCollection value to locate in this RunInvokerVertexCollectionCollection. + + + true if value is found in this RunInvokerVertexCollectionCollection; + false otherwise. + + + + + Removes the first occurrence of a specific RunInvokerVertexCollection from this RunInvokerVertexCollectionCollection. + + + The RunInvokerVertexCollection value to remove from this RunInvokerVertexCollectionCollection. + + + + + Returns an enumerator that can iterate through the elements of this RunInvokerVertexCollectionCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the RunInvokerVertexCollection at the given index in this RunInvokerVertexCollectionCollection. + + + + + Type-specific enumeration class, used by RunInvokerVertexCollectionCollection.GetEnumerator. + + + + + A collection of elements of type RunPipe + + + + + Initializes a new empty instance of the RunPipeCollection class. + + + + + Adds an instance of type RunPipe to the end of this RunPipeCollection. + + + The RunPipe to be added to the end of this RunPipeCollection. + + + + + Determines whether a specfic RunPipe value is in this RunPipeCollection. + + + The RunPipe value to locate in this RunPipeCollection. + + + true if value is found in this RunPipeCollection; + false otherwise. + + + + + Removes the first occurrence of a specific RunPipe from this RunPipeCollection. + + + The RunPipe value to remove from this RunPipeCollection. + + + + + Returns an enumerator that can iterate through the elements of this RunPipeCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the RunPipe at the given index in this RunPipeCollection. + + + + + Type-specific enumeration class, used by RunPipeCollection.GetEnumerator. + + + + + A collection of elements of type IRunPipeListener + + + + + Initializes a new empty instance of the RunPipeListenerCollection class. + + + + + Adds an instance of type IRunPipeListener to the end of this RunPipeListenerCollection. + + + The IRunPipeListener to be added to the end of this RunPipeListenerCollection. + + + + + Determines whether a specfic IRunPipeListener value is in this RunPipeListenerCollection. + + + The IRunPipeListener value to locate in this RunPipeListenerCollection. + + + true if value is found in this RunPipeListenerCollection; + false otherwise. + + + + + Removes the first occurrence of a specific IRunPipeListener from this RunPipeListenerCollection. + + + The IRunPipeListener value to remove from this RunPipeListenerCollection. + + + + + Returns an enumerator that can iterate through the elements of this RunPipeListenerCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Type-specific enumeration class, used by RunPipeListenerCollection.GetEnumerator. + + + + + A collection of elements of type RunPipeStarter + + + + + Initializes a new empty instance of the RunPipeStarterCollection class. + + + + + Adds an instance of type RunPipeStarter to the end of this RunPipeStarterCollection. + + + The RunPipeStarter to be added to the end of this RunPipeStarterCollection. + + + + + Determines whether a specfic RunPipeStarter value is in this RunPipeStarterCollection. + + + The RunPipeStarter value to locate in this RunPipeStarterCollection. + + + true if value is found in this RunPipeStarterCollection; + false otherwise. + + + + + Removes the first occurrence of a specific RunPipeStarter from this RunPipeStarterCollection. + + + The RunPipeStarter value to remove from this RunPipeStarterCollection. + + + + + Returns an enumerator that can iterate through the elements of this RunPipeStarterCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Type-specific enumeration class, used by RunPipeStarterCollection.GetEnumerator. + + + + + A dictionary with keys of type IRun and values of type RunVertex + + + + + Initializes a new empty instance of the RunVertexDictionary class + + + + + Adds an element with the specified key and value to this RunVertexDictionary. + + + The IRun key of the element to add. + + + The RunVertex value of the element to add. + + + + + Determines whether this RunVertexDictionary contains a specific key. + + + The IRun key to locate in this RunVertexDictionary. + + + true if this RunVertexDictionary contains an element with the specified key; + otherwise, false. + + + + + Determines whether this RunVertexDictionary contains a specific value. + + + The RunVertex value to locate in this RunVertexDictionary. + + + true if this RunVertexDictionary contains an element with the specified value; + otherwise, false. + + + + + Removes the element with the specified key from this RunVertexDictionary. + + + The IRun key of the element to remove. + + + + + Gets or sets the RunVertex associated with the given IRun + + + The IRun whose value to get or set. + + + + + Gets a collection containing the keys in this RunVertexDictionary. + + + + + Gets a collection containing the values in this RunVertexDictionary. + + + + + A collection of elements of type Thread + + + + + Initializes a new empty instance of the ThreadCollection class. + + + + + Adds an instance of type Thread to the end of this ThreadCollection. + + + The Thread to be added to the end of this ThreadCollection. + + + + + Determines whether a specfic Thread value is in this ThreadCollection. + + + The Thread value to locate in this ThreadCollection. + + + true if value is found in this ThreadCollection; + false otherwise. + + + + + Removes the first occurrence of a specific Thread from this ThreadCollection. + + + The Thread value to remove from this ThreadCollection. + + + + + Returns an enumerator that can iterate through the elements of this ThreadCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the Thread at the given index in this ThreadCollection. + + + + + Type-specific enumeration class, used by ThreadCollection.GetEnumerator. + + + + + Summary description for ThreadCollectionRunner. + + + + + A collection of elements of type Type + + + + + Initializes a new empty instance of the TypeCollection class. + + + + + Adds an instance of type Type to the end of this TypeCollection. + + + The Type to be added to the end of this TypeCollection. + + + + + Determines whether a specfic Type value is in this TypeCollection. + + + The Type value to locate in this TypeCollection. + + + true if value is found in this TypeCollection; + false otherwise. + + + + + Removes the first occurrence of a specific Type from this TypeCollection. + + + The Type value to remove from this TypeCollection. + + + + + Returns an enumerator that can iterate through the elements of this TypeCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the Type at the given index in this TypeCollection. + + + + + Type-specific enumeration class, used by TypeCollection.GetEnumerator. + + + + + Allows control of command line parsing. + Attach this attribute to instance fields of types used + as the destination of command line argument parsing. + + + + Command line parsing code from Peter Halam, + http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e + + + + + + Allows control of command line parsing. + + Specifies the error checking to be done on the argument. + + + + The error checking to be done on the argument. + + + + + Returns true if the argument did not have an explicit short name specified. + + + + + The short name of the argument. + + + + + Returns true if the argument did not have an explicit long name specified. + + + + + The long name of the argument. + + + + + Parser for command line arguments. + + + + The parser specification is infered from the instance fields of the object + specified as the destination of the parse. + Valid argument types are: int, uint, string, bool, enums + Also argument types of Array of the above types are also valid. + + + Error checking options can be controlled by adding a CommandLineArgumentAttribute + to the instance fields of the destination object. + + + At most one field may be marked with the DefaultCommandLineArgumentAttribute + indicating that arguments without a '-' or '/' prefix will be parsed as that argument. + + + If not specified then the parser will infer default options for parsing each + instance field. The default long name of the argument is the field name. The + default short name is the first character of the long name. Long names and explicitly + specified short names must be unique. Default short names will be used provided that + the default short name does not conflict with a long name or an explicitly + specified short name. + + + Arguments which are array types are collection arguments. Collection + arguments can be specified multiple times. + + + Command line parsing code from Peter Halam, + http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e + + + + + + Creates a new command line argument parser. + + The type of object to parse. + The destination for parse errors. + + + + Parses an argument list into an object + + + + true if an error occurred + + + + Parses an argument list. + + The arguments to parse. + The destination of the parsed arguments. + true if no parse errors were encountered. + + + + A user firendly usage string describing the command line argument syntax. + + + + + Used to control parsing of command line arguments. + + + + Command line parsing code from Peter Halam, + http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e + + + + + + Indicates that this field is required. An error will be displayed + if it is not present when parsing arguments. + + + + + Only valid in conjunction with Multiple. + Duplicate values will result in an error. + + + + + Inidicates that the argument may be specified more than once. + Only valid if the argument is a collection + + + + + The default type for non-collection arguments. + The argument is not required, but an error will be reported if it is specified more than once. + + + + + For non-collection arguments, when the argument is specified more than + once no error is reported and the value of the argument is the last + value which occurs in the argument list. + + + + + The default type for collection arguments. + The argument is permitted to occur multiple times, but duplicate + values will cause an error to be reported. + + + + + Useful Stuff. + + + + Command line parsing code from Peter Halam, + http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e + + + + + + The System Defined new line string. + + + + + Don't ever call this. + + + + + Parses Command Line Arguments. + Errors are output on Console.Error. + Use CommandLineArgumentAttributes to control parsing behaviour. + + The actual arguments. + The resulting parsed arguments. + + + + Parses Command Line Arguments. + Use CommandLineArgumentAttributes to control parsing behaviour. + + The actual arguments. + The resulting parsed arguments. + The destination for parse errors. + + + + Returns a Usage string for command line argument parsing. + Use CommandLineArgumentAttributes to control parsing behaviour. + + The type of the arguments to display usage for. + Printable string containing a user friendly description of command line arguments. + + + + Indicates that this argument is the default argument. + '/' or '-' prefix only the argument value is specified. + + + + Command line parsing code from Peter Halam, + http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e + + + + + + Indicates that this argument is the default argument. + + Specifies the error checking to be done on the argument. + + + + A delegate used in error reporting. + + + + Command line parsing code from Peter Halam, + http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e + + + + + + This method is used to provide assembly location resolver. It is called on event as needed by the CLR. + Refer to document related to AppDomain.CurrentDomain.AssemblyResolve + + + + + Base class for MbUnit exceptions + + + + + Initializes an empty + instance. + + + + + Exception throwed when not finding a vertex. + + + + + Exception throwed when not finding a vertex. + + + + + Creates an exception with a message + and an inner exception. + + Error message + Inner exception + + + - - - - TODO - Add class summary - - - created by - dehalleux - created on - 30/01/2004 13:38:05 - - - - - Default constructor - initializes all fields to default values - - - - - Summary description for PropertyGetRunInvoker. - - - + + + + + + - - - - Summary description for RunInvokerTreeEventHandler. - - - - - A implementation, containing a - . - - - - - Builds a new unitialized vertex. Internal use only. - - You should not call this method directly. - - - - Not implemented. - - - always thrown - - - - Serializes informations to the instance. - - serialization device - info is a null reference - - - - Converts the object to string - - - This class outputs the vertex ID and Invoker.ToString(). - - - String representation of the vertex - - - - - Gets a value indicating if the vertex has a - instance attached to it. - - - true if the vertex has a instance attached. - - - - - Gets the attached to the vertex. - - - The instance attached to the vertex - - - the is a null reference - - - - - Internal use - - - - - Functor class that lanches an invoker execution. - - - You can use this method to launch execution - in separate threads. - - - - - Constructs a execute functor - - invoker to execute - .Execute arguments - .Execute arguments - - - Launches the invoker execution - - - - - TODO - Add class summary - - - created by - dehalleux - created on - 30/01/2004 11:35:56 - - - - - Summary description for MemoryTracker. - - - - - Describes the status of the memory. - - - - The code to retreive the total physical and available physical memory - was takened from the AUT project (http://aut.tigris.org). - - - - - - A high performance timer - - - High Precision Timer based on Win32 methods. - - - This example times the execution of a method: - - TimeMonitor timer = new TimeMonitor(); - timer.Start(); - ... // execute code - timer.Stop(); - - Console.WriteLine("Duration: {0}",timer.Duration); - - - - - Default constructor - Initializes the timer. - - - Starts the timer - Resets the duration and starts the timer - - - Stops the timer - Stops the timer - - - Gets the current duration value without stopping the timer - Current duration value - - - Gets the timed duration value in seconds - Timer duration - - - - - The MbUnit.Core namespace and child namespaces - contains the kernel of MbUnit. - - - The MbUnit.Core.Collections namespace contains - stronly typed collections. - - - The Exceptions namespace contains custom exception - classes relative to the MbUnit framework. - - - The MbUnit.Framework namespace contains base class for custom attributes - , for test fixtures. The custom attributes can be used to build new - test fixture. - - - The MbUnit.Core.Invokers namespace contains invokers classes that - are functor-like wrapper for fixture methods. - - - The MbUnit.Core.Monitoring namespace contains time and memory - performance tracers. - - - The MbUnit.Core.Runs namespace contains run object that are generators - for invoker methods. - - - - - - Long living object. (Extracted from NUnit source) - - - - All objects which are marshalled by reference - and whose lifetime is manually controlled by - the app, should derive from this class rather - than MarshalByRefObject. - - - This includes the remote test domain objects - which are accessed by the client and those - client objects which are called back by the - remote test domain. - - - Objects in this category that already inherit - from some other class (e.g. from TextWriter) - which in turn inherits from MarshalByRef object - should override InitializeLifetimeService to - return null to obtain the same effect. - - - Original code from NUnit. - Portions Copyright © 2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole - - - - - - Raises the event. - - - - - Raises the event. - - - - - Raises the event. - - - - - Loads domain and test assembly - - - - - Unload domain - - - - - Unload and reload test domain - - - - - Gets a identifying the - - - - - AssemblyWatcher keeps track of one or more assemblies to - see if they have changed. It incorporates a delayed notification - and uses a standard event to notify any interested parties - about the change. The path to the assembly is provided as - an argument to the event handler so that one routine can - be used to handle events from multiple watchers. - - - - Code takened from NUnit. - - /************************************************************************************ - ' - ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole - ' Copyright 2000-2002 Philip A. Craig - ' - ' This software is provided 'as-is', without any express or implied warranty. In no - ' event will the authors be held liable for any damages arising from the use of this - ' software. - ' - ' Permission is granted to anyone to use this software for any purpose, including - ' commercial applications, and to alter it and redistribute it freely, subject to the - ' following restrictions: - ' - ' 1. The origin of this software must not be misrepresented; you must not claim that - ' you wrote the original software. If you use this software in a product, an - ' acknowledgment (see the following) in the product documentation is required. - ' - ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole - ' or Copyright 2000-2002 Philip A. Craig - ' - ' 2. Altered source versions must be plainly marked as such, and must not be - ' misrepresented as being the original software. - ' - ' 3. This notice may not be removed or altered from any source distribution. - ' - '***********************************************************************************/ - - - - - - - Summary description for AuthorTestTreePopulator. - - - - - Defines a class that can populate a tree of tests - - - - - Defines a class that can populate a tree of tests - - - - - Clears the internal representation of the tree - - - - - Populates the node using the instance - contained in . - - - - node dictionary - - or is a null - reference (Nothing in Visual Basic) - - - - - Clears the internal representation of the tree - - - - - Populates the node using the instance - contained in . - - - or is a null - reference (Nothing in Visual Basic) - - - - - Helper method to delete the cache dir. This method deals - with a bug that occurs when pdb files are marked read-only. - - - - - - Merge a 'dependentAssembly' directive into a given config document. - If any entries exist for the same assembly they will be deleted - before the new entry is merged. - - The config document to merge - The Assembly that should be used - The range of compatable versions (eg. "1.0.0.0-3.0.0.0") - - - - - - - - - specify a URL to define a codeBase otherwise null - - - - - Summary description for FixtureCategoryTestTreePopulator. - - - - - A dictionary with keys of type Guid and values of type TestTreeNode - - - - - Initializes a new empty instance of the GuidTestTreeNodeDictionary class - - - - - Adds an element with the specified key and value to this GuidTestTreeNodeDictionary. - - - The TestTreeNode value of the element to add. - - - - - Determines whether this GuidTestTreeNodeDictionary contains a specific key. - - - The Guid key to locate in this GuidTestTreeNodeDictionary. - - - true if this GuidTestTreeNodeDictionary contains an element with the specified key; - otherwise, false. - - - - - Determines whether this GuidTestTreeNodeDictionary contains a specific key. - - - The Guid key to locate in this GuidTestTreeNodeDictionary. - - - true if this GuidTestTreeNodeDictionary contains an element with the specified key; - otherwise, false. - - - - - Removes the element with the specified key from this GuidTestTreeNodeDictionary. - - - The Guid key of the element to remove. - - - - - Gets or sets the TestTreeNode associated with the given Guid - - - The Guid whose value to get or set. - - - - - Gets a collection containing the keys in this GuidTestTreeNodeDictionary. - - - - - Gets a collection containing the values in this GuidTestTreeNodeDictionary. - - - - - A dictionary with keys of type Guid and values of type TreeNode - - - - - Initializes a new empty instance of the GuidTreeNodeDictionary class - - - - - Adds an element with the specified key and value to this GuidTreeNodeDictionary. - - - The TreeNode value of the element to add. - - - - - Determines whether this GuidTreeNodeDictionary contains a specific key. - - - The Guid key to locate in this GuidTreeNodeDictionary. - - - true if this GuidTreeNodeDictionary contains an element with the specified key; - otherwise, false. - - - - - Determines whether this GuidTreeNodeDictionary contains a specific key. - - - The Guid key to locate in this GuidTreeNodeDictionary. - - - true if this GuidTreeNodeDictionary contains an element with the specified key; - otherwise, false. - - - - - Removes the element with the specified key from this GuidTreeNodeDictionary. - - - The Guid key of the element to remove. - - - - - Gets or sets the TreeNode associated with the given Guid - - - The Guid whose value to get or set. - - - - - Gets a collection containing the keys in this GuidTreeNodeDictionary. - - - - - Gets a collection containing the values in this GuidTreeNodeDictionary. - - - - - Summary description for ImportanceTestTreePopulator. - - - - - Clears the internal representation of the tree - - - - - Populates the node using the instance - contained in . - - - - - Summary description for ImageListBuilder. - - - - - Supports verbose output option of console app. - Added as part of fix to issue MBUNIT-28. - - Marc Stober - December 21, 2005 - - - - Set the location for caching and delete any old cache info - - Our domain - - - - This method is used to provide assembly location resolver. It is called on event as needed by the CLR. - Refer to document related to AppDomain.CurrentDomain.AssemblyResolve - - - - - Creates an AppDomain for the Test Assembly - - - - - - - - - - Gets or sets a value indicating the assemblies have - to be shadow copied - - - - - A dictionary with keys of type String and values of type TestTreeNode - - - - - Initializes a new empty instance of the StringTestTreeNodeDictionary class - - - - - Adds an element with the specified key and value to this StringTestTreeNodeDictionary. - - - The String key of the element to add. - - - The TestTreeNode value of the element to add. - - - - - Determines whether this StringTestTreeNodeDictionary contains a specific key. - - - The String key to locate in this StringTestTreeNodeDictionary. - - - true if this StringTestTreeNodeDictionary contains an element with the specified key; - otherwise, false. - - - - - Removes the element with the specified key from this StringTestTreeNodeDictionary. - - - The String key of the element to remove. - - - - - Gets or sets the TestTreeNode associated with the given String - - - The String whose value to get or set. - - - - - Gets a collection containing the keys in this StringTestTreeNodeDictionary. - - - - - Gets a collection containing the values in this StringTestTreeNodeDictionary. - - - - - Gets the testFilePath - - - - - Summary description for TestsOnTestTreePopulator. - - - - - A collection of elements of type TestTreeNode - - - - - Initializes a new empty instance of the TestTreeNodeCollection class. - - - - - Adds an instance of type TestTreeNode to the end of this TestTreeNodeCollection. - - - The TestTreeNode to be added to the end of this TestTreeNodeCollection. - - - - - Determines whether a specfic TestTreeNode value is in this TestTreeNodeCollection. - - - The TestTreeNode value to locate in this TestTreeNodeCollection. - - - true if value is found in this TestTreeNodeCollection; - false otherwise. - - - - - Removes the first occurrence of a specific TestTreeNode from this TestTreeNodeCollection. - - - The TestTreeNode value to remove from this TestTreeNodeCollection. - - - - - Returns an enumerator that can iterate through the elements of this TestTreeNodeCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Type-specific enumeration class, used by TestTreeNodeCollection.GetEnumerator. - - - - - A collection of elements of type TestTreePopulator - - - - - Initializes a new empty instance of the TestTreePopulatorCollection class. - - - - - Initializes a new instance of the TestTreePopulatorCollection class, containing elements - copied from an array. - - - The array whose elements are to be added to the new TestTreePopulatorCollection. - - - - - Initializes a new instance of the TestTreePopulatorCollection class, containing elements - copied from another instance of TestTreePopulatorCollection - - - The TestTreePopulatorCollection whose elements are to be added to the new TestTreePopulatorCollection. - - - - - Adds the elements of an array to the end of this TestTreePopulatorCollection. - - - The array whose elements are to be added to the end of this TestTreePopulatorCollection. - - - - - Adds the elements of another TestTreePopulatorCollection to the end of this TestTreePopulatorCollection. - - - The TestTreePopulatorCollection whose elements are to be added to the end of this TestTreePopulatorCollection. - - - - - Adds an instance of type TestTreePopulator to the end of this TestTreePopulatorCollection. - - - The TestTreePopulator to be added to the end of this TestTreePopulatorCollection. - - - - - Determines whether a specfic TestTreePopulator value is in this TestTreePopulatorCollection. - - - The TestTreePopulator value to locate in this TestTreePopulatorCollection. - - - true if value is found in this TestTreePopulatorCollection; - false otherwise. - - - - - Removes the first occurrence of a specific TestTreePopulator from this TestTreePopulatorCollection. - - - The TestTreePopulator value to remove from this TestTreePopulatorCollection. - - - - - Returns an enumerator that can iterate through the elements of this TestTreePopulatorCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Type-specific enumeration class, used by TestTreePopulatorCollection.GetEnumerator. - - - - - Gets the assembly watcher - - - - - Render the report result to the specified writer - - Result from the test - Writer to write result output to - - - - Render the report result to a file - - Result from the test - Report output file name - - - - Render the report result to a file - - Result from the test - Output directory - Default format name - Extension of the file - File name of the report - - - - Render the report result to a file - - Result from the test - Output directory - Default format name. If null, the default name will be used - File name of the report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Reports MbUnit result in text format - - - - - Summary description for XmlReport. - - - - - Static helper functions for retreiving resources - - - - - Creates and saves the images in the directory with the specified path. - - The directory path in which to save the images - - - - This class represents the execution pipe of a test. It contains a - sequence of . - - - - - - Default constructor - initializes all fields to default values - - - - - TODO - Add class summary - - - created by - dehalleux - created on - 30/01/2004 14:09:36 - - - - - Default constructor - initializes all fields to default values - - - - - Default constructor - initializes all fields to default values - - - - - Summary description for RunPipeStarterEventArgs. - - - - - Summary description for ProviderFactoryRun. - - - - - TODO - Add class summary - - - created by - dehalleux - created on - 30/01/2004 15:26:18 - - - - - Summary description for FixtureDecoratorRun. - - - - - - - - - Populates the invoker graph - with generated by the run. - - Invoker tree - parent vertex - class type that is marked by the run - - - - - - Gets a descriptive name of the - - - A descriptive name of the - - - - - Gets a value indicating the run is considered as a test or not. - - - true if the instance is a test - - - - - TODO - Add class summary - - - created by - dehalleux - created on - 29/01/2004 14:44:27 - - - - - Summary description for ProviderFactoryRun. - - - - - A sequence of IRuns - - - - - TODO - add method description - - - Inherited method from base class Run - - TODO - add parameter description - - - - Test fixture run with support for decoration by - . - - - - - Builds the test run invoker tree. - - - - - - - - Event argument that carries a instance. - - - - - Type event delegate - - - - - Helper static class for Type related tasks - - - - - - Output the methods and their custom attributes to the console. - (Debugging method) - - type to visit - - You can use this method to display the methods of a class or struct - type. Mainly for debugging purpose. - - - - - is a null reference - - - - is anot a class type. - - - - - Gets a value indicating the class type has - a method that is tagged - by a instance. - - type to test - custom attribute type to search - - true if class type has a method tagged by a - attribute, false otherwise. - - - or - is a null reference - - - You can use this method to check that a type is tagged by an attribute. - - - - - Gets a value indicating if the is tagged - by a instance. - - method to test - custom attribute type to search - - true if is tagged by a - attribute, false otherwise. - - - or - is a null reference - - - You can use this method to check that a method is tagged by a - specified attribute. - - - - - Gets a value indicating if the method info is tagged - by a instance. - - method to test - custom attribute type to search - - true if is tagged by a - attribute, false otherwise. - - - or - is a null reference - - - You can use this method to check that a method is tagged by a - specified attribute. - - - - - Gets the first instance of - from the method custom attributes. - - Method to test - custom attribute type to search - - First instance of - from the method custom attributes. - - - or - is a null reference - - - is not tagged by an attribute of type - - - - You can use this method to retreive a specified attribute - instance of a method. - - - - - Gets the first instance of - from the method custom attributes. - - Method to test - custom attribute type to search - - First instance of - from the method custom attributes; otherwize - a null reference - - - or - is a null reference - - - You can use this method to retreive a specified attribute - instance of a method. - - - - - Gets the first method of the type - that is tagged by a - instance. - - type to test - custom attribute type to search - - First method of that - that is tagged by a - instance, null if no method is tagged by the specified attribute - type. - - - or - is a null reference - - - You can use this method to retreive a tagged method - - - - - Gets all methods of the type - that are tagged by a - instance. - - type to test - custom attribute type to search - - collection of type that - that are tagged by a - instance. - - - or - is a null reference - - - You can use this method to retreive all the methods of a type - tagged by a . - - - - - Gets a value indicating if the type contains - a Method with the signature defined by . - - - Checks if a type has a desired Method. - - type to test - arguments of the Method - true if contains a Method matching - types - t is a null reference - - - - Retreives the that matches the signature. - - type to test - Method parameter types - - The instance of matching - the signature. - - is a null reference - - No Method of type match the signature defined - by . - - - This method tries to retreive a Method matching the signature - and throws if it failed. - - - - - Retreives the that matches the signature, - given the list of arguments. - - type to test - Method arguments from which the signature - is deduced - - The instance of matching - the signature defined by the list of arguments. - - is a null reference - - One of the args item is a null reference - - - No Method of type match the signature defined - by . - - - This methods retreives the types of and - looks for a Method matching that signature. - - - - - Creates an instance of the type using - the default Method. - - type to instanciate - type instance - - - - Creates an instance of the type using - the Method that matches the signature defined by - - - type to instanciate - argument of the Method - type instance initialized using - - - - Gets a value indicating if the type - has an indexer that takes arguments. - - - Checks that an indexer with a given signature exists in the class. - - type that holds the indexer - indexer arguments - true if an indexer that matched the signature was found, - false otherwise - - - - - Retreives the indexer that matches the signature - - - Safe retreival of an indexer, given it's signature - - type that holds the indexer - indexer arguments - - - - Gets the value of the property . - - property - object instnace - property arguments (in case of an indexer - property value - - - - Gets a value indicating if the match - the - - property or method paramter info - tested signature - - - - Assertion class for Database related object. - - - - - A private constructor disallows any instances of this object. - - - - - Asserts that two are equal. - - Expected instance. - Actual instance. - - - - Asserts that two are equal. - - Expected instance. - Actual instance. - - - Insipired from this - - blog entry.. - - - - - - Assert that schemas are equal. - - - - - Assert that schemas and data are equal. - - - - - Assert that data are equal. - - - - - Data Test fixture. - - - - - Default constructor - - - - - - - Constructor with a fixture description - - fixture description - - - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - -This example shows a test fixture class implementing the Simple Test pattern. -It tests image based method of the Graphics class in GDI+. - - -A set up method -(tagged by is used to create a new bitmap, while -a tear down (tagged by ) is used to released the bitmap. - - -[TestFixture("Bitmap")] -public GraphicsAndBitmapTest -{ - private Bitmap bmp; - - [SetUp] - public void SetUp() - { - this.bmp = new Bitmap(300,300); - } - - [Test] - public void CreateGraphics() - { - Graphics g = Graphcis.FromImage(this.bmp); - Assert.IsNotNull(g); - Assert.AreEqual(g.Width,this.bmp.Width); - ... - } - - ... - - [TearDown] - public void TearDownCanHaveOtherNames() - { - if(this.bmp!=null) - this.bmp.Dispose(); - } -} - - - - - - Tags method that provide data for the tests. - - - - - - Tag method that should return in a given time interval. - - - - - - Tags method that fill collections with data. - - - - - - Tags test methods that are ignored. - - - - - - This attribute collects the test importance information. - - - Fixture importance is labelled from 0, critical to higher values - representing less critical tests. - - - - - Tag method that provider a collection, an inde - - - - - - Default constructor - initializes all fields to default values - - - - - Default constructor - initializes all fields to default values - and int iterator - - - - - Required designer variable. - - - - - Clean up any resources being used. - - - - - Required method for Designer support - do not modify - the contents of this method with the code editor. - - - - - Tag method that gives a list of culture that the test should run on. - - - - - - Summary description for ProviderFixtureDecoratorPatternAttribute. - - - - - Performance Assertion class - - - - - Creates a countdown timer that will assert if execution time exceeds maximum duration. - - - - - Runtime statistics on CLR exception handling. - - - - - This counter displays the total number of exceptions thrown since the start of the application. These include both .NET exceptions and unmanaged exceptions that get converted into .NET exceptions e.g. null pointer reference exception in unmanaged code would get re-thrown in managed code as a .NET System.NullReferenceException; this counter includes both handled and unhandled exceptions. Exceptions that are re-thrown would get counted again. Exceptions should only occur in rare situations and not in the normal control flow of the program. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of exceptions thrown per second. These include both .NET exceptions and unmanaged exceptions that get converted into .NET exceptions e.g. null pointer reference exception in unmanaged code would get re-thrown in managed code as a .NET System.NullReferenceException; this counter includes both handled and unhandled exceptions. Exceptions should only occur in rare situations and not in the normal control flow of the program; this counter was designed as an indicator of potential performance problems due to large (>100s) rate of exceptions thrown. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of .NET exception filters executed per second. An exception filter evaluates whether an exception should be handled or not. This counter tracks the rate of exception filters evaluated; irrespective of whether the exception was handled or not. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of finally blocks executed per second. A finally block is guaranteed to be executed regardless of how the try block was exited. Only the finally blocks that are executed for an exception are counted; finally blocks on normal code paths are not counted by this counter. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of stack frames traversed from the frame that threw the .NET exception to the frame that handled the exception per second. This counter resets to 0 when an exception handler is entered; so nested exceptions would show the handler to handler stack depth. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Stats for CLR Remoting. - - - - - This counter displays the number of remote procedure calls invoked per second. A remote procedure call is a call on any object outside the caller;s AppDomain. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of remote procedure calls invoked since the start of this application. A remote procedure call is a call on any object outside the caller;s AppDomain. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of remoting channels registered across all AppDomains since the start of the application. Channels are used to transport messages to and from remote objects. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of remoting proxy objects created in this process since the start of the process. Proxy object acts as a representative of the remote objects and ensures that all calls made on the proxy are forwarded to the correct remote object instance. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of context-bound classes loaded. Classes that can be bound to a context are called context-bound classes; context-bound classes are marked with Context Attributes which provide usage rules for synchronization; thread affinity; transactions etc. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of context-bound objects allocated per second. Instances of classes that can be bound to a context are called context-bound objects; context-bound classes are marked with Context Attributes which provide usage rules for synchronization; thread affinity; transactions etc. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of remoting contexts in the application. A context is a boundary containing a collection of objects with the same usage rules like synchronization; thread affinity; transactions etc. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Help not available. - - - - - The cumulative total number of socket connections established for this process since the process was started. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - The cumulative total number of bytes received over all open socket connections since the process was started. This number includes data and any protocol information that is not defined by the TCP/IP protocol. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - The cumulative total number of bytes sent over all open socket connections since the process was started. This number includes data and any protocol information that is not defined by the TCP/IP protocol. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - The cumulative total number of datagram packets received since the process was started. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - The cumulative total number of datagram packets sent since the process was started. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Counters for CLR Garbage Collected heap. - - - - - This counter displays the number of times the generation 0 objects (youngest; most recently allocated) are garbage collected (Gen 0 GC) since the start of the application. Gen 0 GC occurs when the available memory in generation 0 is not sufficient to satisfy an allocation request. This counter is incremented at the end of a Gen 0 GC. Higher generation GCs include all lower generation GCs. This counter is explicitly incremented when a higher generation (Gen 1 or Gen 2) GC occurs. _Global_ counter value is not accurate and should be ignored. This counter displays the last observed value. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of times the generation 1 objects are garbage collected since the start of the application. The counter is incremented at the end of a Gen 1 GC. Higher generation GCs include all lower generation GCs. This counter is explicitly incremented when a higher generation (Gen 2) GC occurs. _Global_ counter value is not accurate and should be ignored. This counter displays the last observed value. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of times the generation 2 objects (older) are garbage collected since the start of the application. The counter is incremented at the end of a Gen 2 GC (also called full GC). _Global_ counter value is not accurate and should be ignored. This counter displays the last observed value. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the bytes of memory that survive garbage collection (GC) and are promoted from generation 0 to generation 1; objects that are promoted just because they are waiting to be finalized are not included in this counter. This counter displays the value observed at the end of the last GC; its not a cumulative counter. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the bytes of memory that survive garbage collection (GC) and are promoted from generation 1 to generation 2; objects that are promoted just because they are waiting to be finalized are not included in this counter. This counter displays the value observed at the end of the last GC; its not a cumulative counter. This counter is reset to 0 if the last GC was a Gen 0 GC only. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the bytes per second that are promoted from generation 0 (youngest) to generation 1; objects that are promoted just because they are waiting to be finalized are not included in this counter. Memory is promoted when it survives a garbage collection. This counter was designed as an indicator of relatively long-lived objects being created per sec. This counter displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the bytes per second that are promoted from generation 1 to generation 2 (oldest); objects that are promoted just because they are waiting to be finalized are not included in this counter. Memory is promoted when it survives a garbage collection. Nothing is promoted from generation 2 since it is the oldest. This counter was designed as an indicator of very long-lived objects being created per sec. This counter displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the bytes of memory that are promoted from generation 0 to generation 1 just because they are waiting to be finalized. This counter displays the value observed at the end of the last GC; its not a cumulative counter. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the bytes of memory that are promoted from generation 1 to generation 2 just because they are waiting to be finalized. This counter displays the value observed at the end of the last GC; its not a cumulative counter. This counter is reset to 0 if the last GC was a Gen 0 GC only. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the maximum bytes that can be allocated in generation 0 (Gen 0); its does not indicate the current number of bytes allocated in Gen 0. A Gen 0 GC is triggered when the allocations since the last GC exceed this size. The Gen 0 size is tuned by the Garbage Collector and can change during the execution of the application. At the end of a Gen 0 collection the size of the Gen 0 heap is infact 0 bytes; this counter displays the size (in bytes) of allocations that would trigger the next Gen 0 GC. This counter is updated at the end of a GC; its not updated on every allocation. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of bytes in generation 1 (Gen 1); this counter does not display the maximum size of Gen 1. Objects are not directly allocated in this generation; they are promoted from previous Gen 0 GCs. This counter is updated at the end of a GC; its not updated on every allocation. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of bytes in generation 2 (Gen 2). Objects are not directly allocated in this generation; they are promoted from Gen 1 during previous Gen 1 GCs. This counter is updated at the end of a GC; its not updated on every allocation. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current size of the Large Object Heap in bytes. Objects greater than 20 KBytes are treated as large objects by the Garbage Collector and are directly allocated in a special heap; they are not promoted through the generations. This counter is updated at the end of a GC; its not updated on every allocation. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of garbage collected objects that survive a collection because they are waiting to be finalized. If these objects hold references to other objects then those objects also survive but are not counted by this counter; the "Promoted Finalization-Memory from Gen 0" and "Promoted Finalization-Memory from Gen 1" counters represent all the memory that survived due to finalization. This counter is not a cumulative counter; its updated at the end of every GC with count of the survivors during that particular GC only. This counter was designed to indicate the extra overhead that the application might incur because of finalization. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of GC Handles in use. GCHandles are handles to resources external to the CLR and the managed environment. Handles occupy small amounts of memory in the GCHeap but potentially expensive unmanaged resources. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the rate of bytes per second allocated on the GC Heap. This counter is updated at the end of every GC; not at each allocation. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the peak number of times a garbage collection was performed because of an explicit call to GC.Collect. Its a good practice to let the GC tune the frequency of its collections. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - % Time in GC is the percentage of elapsed time that was spent in performing a garbage collection (GC) since the last GC cycle. This counter is usually an indicator of the work done by the Garbage Collector on behalf of the application to collect and compact memory. This counter is updated only at the end of every GC and the counter value reflects the last observed value; its not an average. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Not Displayed. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter is the sum of four other counters; Gen 0 Heap Size; Gen 1 Heap Size; Gen 2 Heap Size and the Large Object Heap Size. This counter indicates the current memory allocated in bytes on the GC Heaps. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the amount of virtual memory (in bytes) currently committed by the Garbage Collector. (Committed memory is the physical memory for which space has been reserved on the disk paging file). - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the amount of virtual memory (in bytes) currently reserved by the Garbage Collector. (Reserved memory is the virtual memory space reserved for the application but no disk or main memory pages have been used.) - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of pinned objects encountered in the last GC. This counter tracks the pinned objects only in the heaps that were garbage collected e.g. a Gen 0 GC would cause enumeration of pinned objects in the generation 0 heap only. A pinned object is one that the Garbage Collector cannot move in memory. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of sync blocks in use. Sync blocks are per-object data structures allocated for storing synchronization information. Sync blocks hold weak references to managed objects and need to be scanned by the Garbage Collector. Sync blocks are not limited to storing synchronization information and can also store COM interop metadata. This counter was designed to indicate performance problems with heavy use of synchronization primitives. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Stats for CLR interop. - - - - - This counter displays the current number of Com-Callable-Wrappers (CCWs). A CCW is a proxy for the .NET managed object being referenced from unmanaged COM client(s). This counter was designed to indicate the number of managed objects being referenced by unmanaged COM code. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of stubs created by the CLR. Stubs are responsible for marshalling arguments and return values from managed to unmanaged code and vice versa; during a COM Interop call or PInvoke call. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of times arguments and return values have been marshaled from managed to unmanaged code and vice versa since the start of the application. This counter is not incremented if the stubs are inlined. (Stubs are responsible for marshalling arguments and return values). Stubs usually get inlined if the marshalling overhead is small. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Reserved for future use. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Reserved for future use. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Counters for System.Data.SqlClient - - - - - The number of actual connections per second that are being made to servers - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of actual disconnects per second that are being made to servers - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections we get from the pool per second - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections we return to the pool per second - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections that are not using connection pooling - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections that are managed by the connection pooler - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of unique connection strings - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of unique connection strings waiting for pruning - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connection pools - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connection pools - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections currently in-use - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections currently available for use - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections currently waiting to be made ready for use - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections we reclaim from GCed from external connections - - - - - Gets the value of the . - - - Value returned by . - - - - - .Net CLR Data - - - - - Current number of connections, pooled or not. - - - - - Gets the value of the . - - - Value returned by . - - - - - Current number of connections in all pools associated with the process. - - - - - Gets the value of the . - - - Value returned by . - - - - - Current number of pools associated with the process. - - - - - Gets the value of the . - - - Value returned by . - - - - - The highest number of connections in all pools since the process started. - - - - - Gets the value of the . - - - Value returned by . - - - - - The total number of connection open attempts that have failed for any reason. - - - - - Gets the value of the . - - - Value returned by . - - - - - The total number of command executes that have failed for any reason. - - - - - Gets the value of the . - - - Value returned by . - - - - - Statistics for CLR Class Loader. - - - - - This counter displays the current number of classes loaded in all Assemblies. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the cumulative number of classes loaded in all Assemblies since the start of this application. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of classes loaded per second in all Assemblies. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of AppDomains loaded in this application. AppDomains (application domains) provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications running in the same process. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the peak number of AppDomains loaded since the start of this application. AppDomains (application domains) provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications running in the same process. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of AppDomains loaded per second. AppDomains (application domains) provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications running in the same process. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current number of Assemblies loaded across all AppDomains in this application. If the Assembly is loaded as domain-neutral from multiple AppDomains then this counter is incremented once only. Assemblies can be loaded as domain-neutral when their code can be shared by all AppDomains or they can be loaded as domain-specific when their code is private to the AppDomain. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of Assemblies loaded since the start of this application. If the Assembly is loaded as domain-neutral from multiple AppDomains then this counter is incremented once only. Assemblies can be loaded as domain-neutral when their code can be shared by all AppDomains or they can be loaded as domain-specific when their code is private to the AppDomain. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of Assemblies loaded across all AppDomains per second. If the Assembly is loaded as domain-neutral from multiple AppDomains then this counter is incremented once only. Assemblies can be loaded as domain-neutral when their code can be shared by all AppDomains or they can be loaded as domain-specific when their code is private to the AppDomain. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Reserved for future use. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Reserved for future use. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the peak number of classes that have failed to load since the start of the application. These load failures could be due to many reasons like inadequate security or illegal format. Full details can be found in the profiling services help. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of classes that failed to load per second. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. These load failures could be due to many reasons like inadequate security or illegal format. Full details can be found in the profiling services help. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the current size (in bytes) of the memory committed by the class loader across all AppDomains. (Committed memory is the physical memory for which space has been reserved on the disk paging file.) - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of AppDomains unloaded since the start of the application. If an AppDomain is loaded and unloaded multiple times this counter would count each of those unloads as separate. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of AppDomains unloaded per second. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Stats for CLR Security. - - - - - This counter displays the total number of runtime Code Access Security (CAS) checks performed since the start of the application. Runtime CAS checks are performed when a caller makes a call to a callee demanding a particular permission; the runtime check is made on every call by the caller; the check is done by examining the current thread stack of the caller. This counter used together with "Stack Walk Depth" is indicative of performance penalty for security checks. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Reserved for future use. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of linktime Code Access Security (CAS) checks since the start of the application. Linktime CAS checks are performed when a caller makes a call to a callee demanding a particular permission at JIT compile time; linktime check is performed once per caller. This count is not indicative of serious performance issues; its indicative of the security system activity. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the percentage of elapsed time spent in performing runtime Code Access Security (CAS) checks since the last such check. CAS allows code to be trusted to varying degrees and enforces these varying levels of trust depending on code identity. This counter is updated at the end of a runtime security check; it represents the last observed value; its not an average. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Not Displayed. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the depth of the stack during that last runtime Code Access Security check. Runtime Code Access Security check is performed by crawling the stack. This counter is not an average; it just displays the last observed value. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Stats for CLR Jit. - - - - - This counter displays the total number of methods compiled Just-In-Time (JIT) by the CLR JIT compiler since the start of the application. This counter does not include the pre-jitted methods. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total IL bytes jitted since the start of the application. This counter is exactly equivalent to the "Total # of IL Bytes Jitted" counter. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total IL bytes jitted since the start of the application. This counter is exactly equivalent to the "# of IL Bytes Jitted" counter. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the rate at which IL bytes are jitted per second. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the peak number of methods the JIT compiler has failed to JIT since the start of the application. This failure can occur if the IL cannot be verified or if there was an internal error in the JIT compiler. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the percentage of elapsed time spent in JIT compilation since the last JIT compilation phase. This counter is updated at the end of every JIT compilation phase. A JIT compilation phase is the phase when a method and its dependencies are being compiled. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Not Displayed. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Stats for CLR Locks and Threads. - - - - - This counter displays the total number of times threads in the CLR have attempted to acquire a managed lock unsuccessfully. Managed locks can be acquired in many ways; by the "lock" statement in C# or by calling System.Monitor.Enter or by using MethodImplOptions.Synchronized custom attribute. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Rate at which threads in the runtime attempt to acquire a managed lock unsuccessfully. Managed locks can be acquired in many ways; by the "lock" statement in C# or by calling System.Monitor.Enter or by using MethodImplOptions.Synchronized custom attribute. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of threads currently waiting to acquire some managed lock in the application. This counter is not an average over time; it displays the last observed value. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of threads that waited to acquire some managed lock since the start of the application. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of threads per second waiting to acquire some lock in the application. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of current .NET thread objects in the application. A .NET thread object is created either by new System.Threading.Thread or when an unmanaged thread enters the managed environment. This counters maintains the count of both running and stopped threads. This counter is not an average over time; it just displays the last observed value. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of native OS threads created and owned by the CLR to act as underlying threads for .NET thread objects. This counters value does not include the threads used by the CLR in its internal operations; it is a subset of the threads in the OS process. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of threads that are currently recognized by the CLR; they have a corresponding .NET thread object associated with them. These threads are not created by the CLR; they are created outside the CLR but have since run inside the CLR at least once. Only unique threads are tracked; threads with same thread ID re-entering the CLR or recreated after thread exit are not counted twice. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the total number of threads that have been recognized by the CLR since the start of this application; these threads have a corresponding .NET thread object associated with them. These threads are not created by the CLR; they are created outside the CLR but have since run inside the CLR at least once. Only unique threads are tracked; threads with same thread ID re-entering the CLR or recreated after thread exit are not counted twice. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - This counter displays the number of threads per second that have been recognized by the CLR; these threads have a corresponding .NET thread object associated with them. These threads are not created by the CLR; they are created outside the CLR but have since run inside the CLR at least once. Only unique threads are tracked; threads with same thread ID re-entering the CLR or recreated after thread exit are not counted twice. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. - - - - - Gets the value of the . - - - Value returned by - for the current instance. - - - - - Counters for System.Data.OracleClient - - - - - The number of actual connections per second that are being made to servers - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of actual disconnects per second that are being made to servers - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections we get from the pool per second - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections we return to the pool per second - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections that are not using connection pooling - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections that are managed by the connection pooler - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of unique connection strings - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of unique connection strings waiting for pruning - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connection pools - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connection pools - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections currently in-use - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections currently available for use - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections currently waiting to be made ready for use - - - - - Gets the value of the . - - - Value returned by . - - - - - The number of connections we reclaim from GCed from external connections - - - - - Gets the value of the . - - - Value returned by . - - - - - Summary description for PostItAttribute. - - - - - Tag use to mark a method that writes data to a device. - - - - - - Reflection Assertion class - - - - - Asserts whether an instance of the - can be assigned from an instance of . - - - Parent instance. - - - Child instance. - - - - - Asserts whether is an instance of the - . - - - instance. - - - Child instance. - - - - - Asserts that the type has a default public constructor - - - - - Asserts that the type has a public instance constructor with a signature defined by parameters. - - - - - Asserts that the type has a constructor, with the specified bindind flags, with a signature defined by parameters. - - - - - Asserts that the type has a public instance method with a signature defined by parameters. - - - - - Asserts that the type has a method, with the specified bindind flags, with a signature defined by parameters. - - - - - Asserts that the type has a public field method with a signature defined by parameters. - - - - - Asserts that the type has a field, with the specified bindind flags, with a signature defined by parameters. - - - - - This tag defines test method that will be repeated the specified number - of times. - - - - - - Provides a row of values using in conjunction with - to bind values to the parameters of a row test method. - - - - - Provides a row of values using in conjunction with - to bind values to the parameters of a row test method. - - The row of values to bind - - - - Gets the row of values. - - The row of values - - - - Gets or sets the type of exception that is expected to be thrown when this - row is tested, or null if none. - - - - - Declares a row test when applied to a test method along with one or more - attributes. - - - - - Security Assertion class - - - - - Asserts that is authenticated. - - - - - Asserts that is not authenticated. - - - - - Asserts that the current windows identity is authenticated. - - - - - Asserts that the current windows identity is not authenticated. - - - - - Asserts that the current windows identity is in . - - - - - Asserts that the current windows identity is in - role. - - - - - Asserts that the current windows identity is in - role. - - - - - Asserts that the current windows identity is in - role. - - - - - Asserts that the current windows identity is in - role. - - - - - Verifies that the type is serializable with the XmlSerializer object. - - - type to test. - - - - - Serializes and deserialies to/from XML and checks that the results are the same. - - - Object to test - - - - - Tag use to mark a method that initiliazes the fixture instance. - - - - - - String Assertion class - - - - - Asserts that two strings are equal, ignoring the case - - - Expected string - - - Actual string - - - - - Asserts that the string is non null and empty - - - String to test. - - - - - Asserts that the string is non null and non empty - - - String to test. - - - - - Asserts the regular expression reg makes a full match on s - - - String to test. - - - Regular expression - - - - - Asserts the regular expression regex makes a full match on - . - - - String to test. - - - Regular expression - - - - - Asserts the regular expression reg makes a match on s - - - String to test. - - - Regular expression - - - - - Asserts the regular expression regex makes a match on s - - - String to test. - - - A instance. - - - - - Asserts the regular expression reg makes a match on s - - - String to test. - - - Regular expression - - - - - Asserts the regular expression regex makes a match on s - - - String to test. - - - A instance. - - - - - Asserts the string does not contain c - - - String to test. - - - Variable list of characeters. - - - - - Tag use to mark a method that cleans up the resource of the fixture instance. - - - - - - Tag use to mark a mark a unit test method. - - - - - - Contributes additional tests and setup or teardown steps to the - lifecycle defined by . - - - - - Called to add runs to perform before setup. - - The collection to update - - - - Called to add runs to perform during the test execution cycle. - - The collection to update - - - - Called to add runs to perform after teardown. - - The collection to update - - - - Creates an order of execution in the fixture. - - - - This fixture is used to implement the Process testing advertised by - Marc Clifton' - Code Project - article. - - - - - - Initializes a new instance of with the given order. - - order of execution - - - - Initializes a new instance of with the given order - and description. - - order of execution - description of the test - - - - Returns a string that represents the instance. - - - String representing the object. - - - - - Gets or sets the order execution - - - The order of execution - - - - - This tag defines test method that will invoke the method in the specified - number of concurrent threads. - - - - - - Gets a list of values separated by ; - - - - - - Enumeration Pattern implementations. - - -Implements:Enumeration Test Pattern -Login: - -{DataProvider} -{CopyToProvider} -[SetUp] -(EnumerationTester) - - GetEnumerator - - Enumerate - - ElementWiseEquality - - Current - - CurrentWithoutMoveNet - - CurrentPastEnd - - Reset - - CollectionChanged -[TearDown] - - - -This example tests the and . - - - - - - - - - - Could not find . - - - - - Creates an exception with a type - and an inner exception. - - Error type - Inner exception - - - - - - - - - - - - - - - - - - - - - Default constructor - - - XPath to the desired data - - - - - - - Constructor with a fixture description - - - XPath to the desired data - - fixture description - - - - - - Summary description for ForEachTestRunInvoker. - - - - - - The MbUnit.Framework contains the set of built-in attributes. - - - Use the static methods of to test your assertions. You can also - do security related assertion using , - data related assertions using and - XML related assertions using (which comes from XmlUnit, http://xmlunit.sourceforge.net) - , Reflection based assertion and - String and text based assertion . - - - - - - Process Test Pattern fixture. - - - Implements: Process Test Fixture - Logic: - - [SetUp] - {TestSequence} - [TearDown] - - - - This fixture implements the Process Test Fixture as described in the - CodeProject - article from Marc Clifton. - - - In this implementation, reverse traversal is not implemented. - A process can be seen as a linear graph, a very simple model. If you - need more evolved models, use Model Based Testing. - - - - -This is the example for the CodeProject -article adapted to MbUnit. - - -[ProcessTestFixture] -public class POSequenceTest -{ - ... - [TestSequence(1)] - public void POConstructor() - { - po=new PurchaseOrder(); - Assert.AreEqual(po.Number,"", "Number not initialized."); - Assert.AreEqual(po.PartCount,0, "PartCount not initialized."); - Assert.AreEqual(po.ChargeCount,0, "ChargeCount not initialized."); - Assert.AreEqual(po.Invoice,null, "Invoice not initialized."); - Assert.AreEqual(po.Vendor,null, "Vendor not initialized."); - } - - [TestSequence(2)] - public void VendorConstructor() - { - vendor=new Vendor(); - Assert.AreEqual(vendor.Name,"", "Name is not an empty string."); - Assert.AreEqual(vendor.PartCount,0, "PartCount is not zero."); - } - ... - - -Use to mark a class as process test fixture and use the - attribute to create the order of the process. The fixture also supports -SetUp and TearDown methods. - - - - - - Initialize a - instance. - - - - - Constructor with a fixture description - - fixture description - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - - - A resource-based data provider - - - - - A file-based data provider - - - - - - - - - Default constructor - - - XPath to the desired data - - - - - - - Constructor with a fixture description - - - XPath to the desired data - - fixture description - - - - - - A single test case of a . - - - - - Initializes a new instance - with name and delegate. - - - Name of the test case - - - Delegate called by the test case - - - Parameters of the delegate - - - or - is a null reference (Nothing in Visual Basic) - - - is empty. - - - - - Invokes using the parameters returned by - . - - - - - - Gets the name of the test case - - - The name of the test case - - - - - Collection indexing test class - - - - - - Collection order tester class. - - - - - Tests for the and . - - - - - - - - Simple Test Pattern fixture. - - -Implements: Simple Test Pattern -Login: - -[SetUp] -{Test} -[TearDown] - - - -This is the classic unit test fixture attribute. It defines a class that contains unit -tests. - - -The test execution logic is described by the following sequence of custom attributes: -where [] denotes an optional attribute, {} denotes a custom attribute -that can tag multiple number of methods. - - -Unit test methods must be tagged with the , return -void and take no arguments: - -[Test] -public void UnitTest() -{ - ... -} - -The same fixture can hold an arbitrary number of unit test methods. - - -If the fixture needs initilization, you can add a set up method tagged with the - attribute. Note that there can be only one -method tagged with . - - -Symmetricaly, you can specify a method that will clean up resources allocated by -the fixture. This method must be tagged with the -and there can be only one method with this attribute. - - - - -This example shows a test fixture class implementing the Simple Test pattern. -It tests image based method of the Graphics class in GDI+. - - -A set up method -(tagged by is used to create a new bitmap, while -a tear down (tagged by ) is used to released the bitmap. - - -[TestFixture("Bitmap")] -public GraphicsAndBitmapTest -{ - private Bitmap bmp; - - [SetUp] - public void SetUp() - { - this.bmp = new Bitmap(300,300); - } - - [Test] - public void CreateGraphics() - { - Graphics g = Graphcis.FromImage(this.bmp); - Assert.IsNotNull(g); - Assert.AreEqual(g.Width,this.bmp.Width); - ... - } - - ... - - [TearDown] - public void TearDownCanHaveOtherNames() - { - if(this.bmp!=null) - this.bmp.Dispose(); - } -} - - - - - - Default constructor - - - - - - - Constructor with a fixture description - - fixture description - - - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - -This example shows a test fixture class implementing the Simple Test pattern. -It tests image based method of the Graphics class in GDI+. - - -A set up method -(tagged by is used to create a new bitmap, while -a tear down (tagged by ) is used to released the bitmap. - - -[TestFixture("Bitmap")] -public GraphicsAndBitmapTest -{ - private Bitmap bmp; - - [SetUp] - public void SetUp() - { - this.bmp = new Bitmap(300,300); - } - - [Test] - public void CreateGraphics() - { - Graphics g = Graphcis.FromImage(this.bmp); - Assert.IsNotNull(g); - Assert.AreEqual(g.Width,this.bmp.Width); - ... - } - - ... - - [TearDown] - public void TearDownCanHaveOtherNames() - { - if(this.bmp!=null) - this.bmp.Dispose(); - } -} - - - - - - A named collection of uniquely named . - - - - - Initializes a instance - with . - - - name of the suite - - - is a null reference - (Nothing in Visual Basic) - - - is empty. - - - - - Adds the test case to the suite - - - instance to add. - - - The suite already contains a test case named . - - - - - Removes the test case from the suite - - - Test case to remove - - - is a null reference - (Nothing in Visual Basic) - - - - - Adds a new to the suite. - - - Name of the new test case - - - invoked by the test case - - - parameters sent to when invoked - - - is a null reference - (Nothing in Visual Basic) - - - is empty. - - - The suite already contains a test case named . - - - - - Gets the name. - - - The name. - - - - - Gets a collection of . - - - A collection of . - - - - - Test Suite fixture. - - - - - Default constructor - - - - - - - Constructor with a fixture description - - fixture description - - - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - -This example shows a test fixture class implementing the Simple Test pattern. -It tests image based method of the Graphics class in GDI+. - - -A set up method -(tagged by is used to create a new bitmap, while -a tear down (tagged by ) is used to released the bitmap. - - -[TestFixture("Bitmap")] -public GraphicsAndBitmapTest -{ - private Bitmap bmp; - - [SetUp] - public void SetUp() - { - this.bmp = new Bitmap(300,300); - } - - [Test] - public void CreateGraphics() - { - Graphics g = Graphcis.FromImage(this.bmp); - Assert.IsNotNull(g); - Assert.AreEqual(g.Width,this.bmp.Width); - ... - } - - ... - - [TearDown] - public void TearDownCanHaveOtherNames() - { - if(this.bmp!=null) - this.bmp.Dispose(); - } -} - - - - - - Type fixture pattern implementation. - - -Implements: Type Test Pattern -Logic: - -{Provider} -[SetUp] -{Test} -[TearDown] - - - -This fixture is quite similar to the Simple Test pattern, but it applies to -any instance of a particular type provided by the user. - - -The test fixture first looks for methods tagged with the -method. These method must return an object assignable with the tested type. This instance will -be feeded to the other methods of the fixture. - - - - -This example shows the squeleton of a fixture tests the IDictionary interface, -the fixture implements the Type Test pattern. - - -The tested instances are feeded by the methods tagged with the . -These methods must return an instance that is assignable with . -Subsequent will receive the created instance as parameter. - - -[TypeFixture(typeof(IDictionary),"IDictionary interface fixture")] -public void DictionaryTest -{ - [Provider(typeof(Hashtable))] - public Hashtable ProvideHashtable() - { - return new Hashtable(); - } - - [Provider(typeof(SortedList))] - public SortedList ProvideSortedList() - { - return new SortedList(); - } - - // tests - [Test] - [ExpectedException(typeof(ArgumentException))] - public void AddDuplicate(IDictionary dic) // dic comes from a provider class - { - dic.Add("key",null); - dic.Add("key",null); // boom - } - -} - - - - - - Creates a fixture for the type. - - - Initializes the attribute with . - - type to apply the fixture to - testedType is a null reference - - - - Creates a fixture for the type - and a description - - - Initializes the attribute with . - - type to apply the fixture to - description of the fixture - testedType is a null reference - - - - Creates the execution logic - - - See summary. - - A instance that represent the type - test logic. - - - -This example shows the squeleton of a fixture tests the IDictionary interface, -the fixture implements the Type Test pattern. - - -The tested instances are feeded by the methods tagged with the . -These methods must return an instance that is assignable with . -Subsequent will receive the created instance as parameter. - - -[TypeFixture(typeof(IDictionary),"IDictionary interface fixture")] -public void DictionaryTest -{ - [Provider(typeof(Hashtable))] - public Hashtable ProvideHashtable() - { - return new Hashtable(); - } - - [Provider(typeof(SortedList))] - public SortedList ProvideSortedList() - { - return new SortedList(); - } - - // tests - [Test] - [ExpectedException(typeof(ArgumentException))] - public void AddDuplicate(IDictionary dic) // dic comes from a provider class - { - dic.Add("key",null); - dic.Add("key",null); // boom - } - -} - - - - - - Gets a list of member names separated by ; - - - - - - A with verified result. - - - - - Web related assertions. - - - - - Verifies that has ViewState enabled. - - - - - Verifies that has not ViewState enabled. - - - - - Verifies that is visible. - - - - - Verifies that is not visible. - - - - - Verifies that ID is equal to . - - - - - Verifies that has child controls. - - - - - Verifies that has no child controls. - - - - - Verifies that the - property of and - are equal. - - - - - Verifies that the - property of is equal to - are equal. - - - - - Verifies that is a child control - of - - - - - Verifies that is the ID of a child control - of - - - - - Verifies that is a not child control - of - - - - - Verifies that is the not ID of a child control - of - - - - - Verifies that the property of - is equal to . - - - - - Verifies that the property of - is equal to . - - - - - Verifies that the property of - is true. - - - - - Verifies that the property of - is false. - - - - - Verifies that the property of - is true. - - - - - Verifies that the property of - is false. - - - - - Verifies that the property of - is true. - - - - - Verifies that the property of - is false. - - - - - Tag use to mark a method that writes data to a device. - - - - - - Comparing 2 attributes with the same name but different values - - - - - Comparing 2 attribute lists with the same attributes in different sequence - - - - - Summary description for FlowControlException. - - - - - - The MbUnit.Framework.Xml contains Xml-specific assertion. - The classes of this namespace are extracted from the XmlUnit project. - - - /* - ****************************************************************** - Copyright (c) 2001, Jeff Martin, Tim Bacon - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - * Neither the name of the xmlunit.sourceforge.net nor the names - of its contributors may be used to endorse or promote products - derived from this software without specific prior written - permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN - ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - POSSIBILITY OF SUCH DAMAGE. - - ****************************************************************** - */ - - - - - + + + + + + Returns true if the entire test fixture is ignored. + + + + + This is the base class for attributes that can decorate fixtures. + + + + + + Base class for attributes that tag method that are usualy used to + set up, provide data, tear down tests, etc... + + + + + + An invoker that wraps up the call to a fixture method. + + + + + Default constructor - initializes all fields to default values + + + + + Decorator invorkers are used to modify the way a fixute method is executed. + Popular examples of such is the + or the . + + + + + Default constructor - initializes all fields to default values + + + + + + + + TODO - Add class summary + + + created by - dehalleux + created on - 30/01/2004 13:38:05 + + + + + Default constructor - initializes all fields to default values + + + + + Summary description for PropertyGetRunInvoker. + + + + + + + + Summary description for RunInvokerTreeEventHandler. + + + + + A implementation, containing a + . + + + + + Builds a new unitialized vertex. Internal use only. + + You should not call this method directly. + + + + Not implemented. + + + always thrown + + + + Serializes informations to the instance. + + serialization device + info is a null reference + + + + Converts the object to string + + + This class outputs the vertex ID and Invoker.ToString(). + + + String representation of the vertex + + + + + Gets a value indicating if the vertex has a + instance attached to it. + + + true if the vertex has a instance attached. + + + + + Gets the attached to the vertex. + + + The instance attached to the vertex + + + the is a null reference + + + + + Internal use + + + + + Functor class that lanches an invoker execution. + + + You can use this method to launch execution + in separate threads. + + + + + Constructs a execute functor + + invoker to execute + .Execute arguments + .Execute arguments + + + Launches the invoker execution + + + + + TODO - Add class summary + + + created by - dehalleux + created on - 30/01/2004 11:35:56 + + + + + Summary description for MemoryTracker. + + + + + Describes the status of the memory. + + + + The code to retreive the total physical and available physical memory + was takened from the AUT project (http://aut.tigris.org). + + + + + + A high performance timer + + + High Precision Timer based on Win32 methods. + + + This example times the execution of a method: + + TimeMonitor timer = new TimeMonitor(); + timer.Start(); + ... // execute code + timer.Stop(); + + Console.WriteLine("Duration: {0}",timer.Duration); + + + + + Default constructor + Initializes the timer. + + + Starts the timer + Resets the duration and starts the timer + + + Stops the timer + Stops the timer + + + Gets the current duration value without stopping the timer + Current duration value + + + Gets the timed duration value in seconds + Timer duration + + + + + The MbUnit.Core namespace and child namespaces + contains the kernel of MbUnit. + + + The MbUnit.Core.Collections namespace contains + stronly typed collections. + + + The Exceptions namespace contains custom exception + classes relative to the MbUnit framework. + + + The MbUnit.Framework namespace contains base class for custom attributes + , for test fixtures. The custom attributes can be used to build new + test fixture. + + + The MbUnit.Core.Invokers namespace contains invokers classes that + are functor-like wrapper for fixture methods. + + + The MbUnit.Core.Monitoring namespace contains time and memory + performance tracers. + + + The MbUnit.Core.Runs namespace contains run object that are generators + for invoker methods. + + + + + + Long living object. (Extracted from NUnit source) + + + + All objects which are marshalled by reference + and whose lifetime is manually controlled by + the app, should derive from this class rather + than MarshalByRefObject. + + + This includes the remote test domain objects + which are accessed by the client and those + client objects which are called back by the + remote test domain. + + + Objects in this category that already inherit + from some other class (e.g. from TextWriter) + which in turn inherits from MarshalByRef object + should override InitializeLifetimeService to + return null to obtain the same effect. + + + Original code from NUnit. + Portions Copyright © 2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole + + + + + + Raises the event. + + + + + Raises the event. + + + + + Raises the event. + + + + + Loads domain and test assembly + + + + + Unload domain + + + + + Unload and reload test domain + + + + + Gets a identifying the + + + + + AssemblyWatcher keeps track of one or more assemblies to + see if they have changed. It incorporates a delayed notification + and uses a standard event to notify any interested parties + about the change. The path to the assembly is provided as + an argument to the event handler so that one routine can + be used to handle events from multiple watchers. + + + + Code takened from NUnit. + + /************************************************************************************ + ' + ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole + ' Copyright 2000-2002 Philip A. Craig + ' + ' This software is provided 'as-is', without any express or implied warranty. In no + ' event will the authors be held liable for any damages arising from the use of this + ' software. + ' + ' Permission is granted to anyone to use this software for any purpose, including + ' commercial applications, and to alter it and redistribute it freely, subject to the + ' following restrictions: + ' + ' 1. The origin of this software must not be misrepresented; you must not claim that + ' you wrote the original software. If you use this software in a product, an + ' acknowledgment (see the following) in the product documentation is required. + ' + ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole + ' or Copyright 2000-2002 Philip A. Craig + ' + ' 2. Altered source versions must be plainly marked as such, and must not be + ' misrepresented as being the original software. + ' + ' 3. This notice may not be removed or altered from any source distribution. + ' + '***********************************************************************************/ + + + + + + + Summary description for AuthorTestTreePopulator. + + + + + Defines a class that can populate a tree of tests + + + + + Defines a class that can populate a tree of tests + + + + + Clears the internal representation of the tree + + + + + Populates the node using the instance + contained in . + + + + node dictionary + + or is a null + reference (Nothing in Visual Basic) + + + + + Clears the internal representation of the tree + + + + + Populates the node using the instance + contained in . + + + or is a null + reference (Nothing in Visual Basic) + + + + + Helper method to delete the cache dir. This method deals + with a bug that occurs when pdb files are marked read-only. + + + + + + Merge a 'dependentAssembly' directive into a given config document. + If any entries exist for the same assembly they will be deleted + before the new entry is merged. + + The config document to merge + The Assembly that should be used + The range of compatable versions (eg. "1.0.0.0-3.0.0.0") + + + + + + + + + specify a URL to define a codeBase otherwise null + + + + + Summary description for FixtureCategoryTestTreePopulator. + + + + + A dictionary with keys of type Guid and values of type TestTreeNode + + + + + Initializes a new empty instance of the GuidTestTreeNodeDictionary class + + + + + Adds an element with the specified key and value to this GuidTestTreeNodeDictionary. + + + The TestTreeNode value of the element to add. + + + + + Determines whether this GuidTestTreeNodeDictionary contains a specific key. + + + The Guid key to locate in this GuidTestTreeNodeDictionary. + + + true if this GuidTestTreeNodeDictionary contains an element with the specified key; + otherwise, false. + + + + + Determines whether this GuidTestTreeNodeDictionary contains a specific key. + + + The Guid key to locate in this GuidTestTreeNodeDictionary. + + + true if this GuidTestTreeNodeDictionary contains an element with the specified key; + otherwise, false. + + + + + Removes the element with the specified key from this GuidTestTreeNodeDictionary. + + + The Guid key of the element to remove. + + + + + Gets or sets the TestTreeNode associated with the given Guid + + + The Guid whose value to get or set. + + + + + Gets a collection containing the keys in this GuidTestTreeNodeDictionary. + + + + + Gets a collection containing the values in this GuidTestTreeNodeDictionary. + + + + + A dictionary with keys of type Guid and values of type TreeNode + + + + + Initializes a new empty instance of the GuidTreeNodeDictionary class + + + + + Adds an element with the specified key and value to this GuidTreeNodeDictionary. + + + The TreeNode value of the element to add. + + + + + Determines whether this GuidTreeNodeDictionary contains a specific key. + + + The Guid key to locate in this GuidTreeNodeDictionary. + + + true if this GuidTreeNodeDictionary contains an element with the specified key; + otherwise, false. + + + + + Determines whether this GuidTreeNodeDictionary contains a specific key. + + + The Guid key to locate in this GuidTreeNodeDictionary. + + + true if this GuidTreeNodeDictionary contains an element with the specified key; + otherwise, false. + + + + + Removes the element with the specified key from this GuidTreeNodeDictionary. + + + The Guid key of the element to remove. + + + + + Gets or sets the TreeNode associated with the given Guid + + + The Guid whose value to get or set. + + + + + Gets a collection containing the keys in this GuidTreeNodeDictionary. + + + + + Gets a collection containing the values in this GuidTreeNodeDictionary. + + + + + Summary description for ImportanceTestTreePopulator. + + + + + Clears the internal representation of the tree + + + + + Populates the node using the instance + contained in . + + + + + Summary description for ImageListBuilder. + + + + + Supports verbose output option of console app. + Added as part of fix to issue MBUNIT-28. + + Marc Stober + December 21, 2005 + + + + Set the location for caching and delete any old cache info + + Our domain + + + + This method is used to provide assembly location resolver. It is called on event as needed by the CLR. + Refer to document related to AppDomain.CurrentDomain.AssemblyResolve + + + + + Creates an AppDomain for the Test Assembly + + + + + + + + + + Gets or sets a value indicating the assemblies have + to be shadow copied + + + + + A dictionary with keys of type String and values of type TestTreeNode + + + + + Initializes a new empty instance of the StringTestTreeNodeDictionary class + + + + + Adds an element with the specified key and value to this StringTestTreeNodeDictionary. + + + The String key of the element to add. + + + The TestTreeNode value of the element to add. + + + + + Determines whether this StringTestTreeNodeDictionary contains a specific key. + + + The String key to locate in this StringTestTreeNodeDictionary. + + + true if this StringTestTreeNodeDictionary contains an element with the specified key; + otherwise, false. + + + + + Removes the element with the specified key from this StringTestTreeNodeDictionary. + + + The String key of the element to remove. + + + + + Gets or sets the TestTreeNode associated with the given String + + + The String whose value to get or set. + + + + + Gets a collection containing the keys in this StringTestTreeNodeDictionary. + + + + + Gets a collection containing the values in this StringTestTreeNodeDictionary. + + + + + Gets the testFilePath + + + + + Summary description for TestsOnTestTreePopulator. + + + + + A collection of elements of type TestTreeNode + + + + + Initializes a new empty instance of the TestTreeNodeCollection class. + + + + + Adds an instance of type TestTreeNode to the end of this TestTreeNodeCollection. + + + The TestTreeNode to be added to the end of this TestTreeNodeCollection. + + + + + Determines whether a specfic TestTreeNode value is in this TestTreeNodeCollection. + + + The TestTreeNode value to locate in this TestTreeNodeCollection. + + + true if value is found in this TestTreeNodeCollection; + false otherwise. + + + + + Removes the first occurrence of a specific TestTreeNode from this TestTreeNodeCollection. + + + The TestTreeNode value to remove from this TestTreeNodeCollection. + + + + + Returns an enumerator that can iterate through the elements of this TestTreeNodeCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Type-specific enumeration class, used by TestTreeNodeCollection.GetEnumerator. + + + + + A collection of elements of type TestTreePopulator + + + + + Initializes a new empty instance of the TestTreePopulatorCollection class. + + + + + Initializes a new instance of the TestTreePopulatorCollection class, containing elements + copied from an array. + + + The array whose elements are to be added to the new TestTreePopulatorCollection. + + + + + Initializes a new instance of the TestTreePopulatorCollection class, containing elements + copied from another instance of TestTreePopulatorCollection + + + The TestTreePopulatorCollection whose elements are to be added to the new TestTreePopulatorCollection. + + + + + Adds the elements of an array to the end of this TestTreePopulatorCollection. + + + The array whose elements are to be added to the end of this TestTreePopulatorCollection. + + + + + Adds the elements of another TestTreePopulatorCollection to the end of this TestTreePopulatorCollection. + + + The TestTreePopulatorCollection whose elements are to be added to the end of this TestTreePopulatorCollection. + + + + + Adds an instance of type TestTreePopulator to the end of this TestTreePopulatorCollection. + + + The TestTreePopulator to be added to the end of this TestTreePopulatorCollection. + + + + + Determines whether a specfic TestTreePopulator value is in this TestTreePopulatorCollection. + + + The TestTreePopulator value to locate in this TestTreePopulatorCollection. + + + true if value is found in this TestTreePopulatorCollection; + false otherwise. + + + + + Removes the first occurrence of a specific TestTreePopulator from this TestTreePopulatorCollection. + + + The TestTreePopulator value to remove from this TestTreePopulatorCollection. + + + + + Returns an enumerator that can iterate through the elements of this TestTreePopulatorCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Type-specific enumeration class, used by TestTreePopulatorCollection.GetEnumerator. + + + + + Gets the assembly watcher + + + + + Render the report result to the specified writer + + Result from the test + Writer to write result output to + + + + Render the report result to a file + + Result from the test + Report output file name + + + + Render the report result to a file + + Result from the test + Output directory + Default format name + Extension of the file + File name of the report + + + + Render the report result to a file + + Result from the test + Output directory + Default format name. If null, the default name will be used + File name of the report + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Reports MbUnit result in text format + + + + + Summary description for XmlReport. + + + + + Static helper functions for retreiving resources + + + + + Creates and saves the images in the directory with the specified path. + + The directory path in which to save the images + + + + This class represents the execution pipe of a test. It contains a + sequence of . + + + + + + Default constructor - initializes all fields to default values + + + + + TODO - Add class summary + + + created by - dehalleux + created on - 30/01/2004 14:09:36 + + + + + Default constructor - initializes all fields to default values + + + + + Default constructor - initializes all fields to default values + + + + + Summary description for RunPipeStarterEventArgs. + + + + + Summary description for ProviderFactoryRun. + + + + + TODO - Add class summary + + + created by - dehalleux + created on - 30/01/2004 15:26:18 + + + + + Summary description for FixtureDecoratorRun. + + + + + + + + + Populates the invoker graph + with generated by the run. + + Invoker tree + parent vertex + class type that is marked by the run + + + + + + Gets a descriptive name of the + + + A descriptive name of the + + + + + Gets a value indicating the run is considered as a test or not. + + + true if the instance is a test + + + + + TODO - Add class summary + + + created by - dehalleux + created on - 29/01/2004 14:44:27 + + + + + Summary description for ProviderFactoryRun. + + + + + A sequence of IRuns + + + + + TODO - add method description + + + Inherited method from base class Run + + TODO - add parameter description + + + + Test fixture run with support for decoration by + . + + + + + Builds the test run invoker tree. + + + + + + + + Event argument that carries a instance. + + + + + Type event delegate + + + + + Helper static class for Type related tasks + + + + + + Output the methods and their custom attributes to the console. + (Debugging method) + + type to visit + + You can use this method to display the methods of a class or struct + type. Mainly for debugging purpose. + + + + + is a null reference + + + + is anot a class type. + + + + + Gets a value indicating the class type has + a method that is tagged + by a instance. + + type to test + custom attribute type to search + + true if class type has a method tagged by a + attribute, false otherwise. + + + or + is a null reference + + + You can use this method to check that a type is tagged by an attribute. + + + + + Gets a value indicating if the is tagged + by a instance. + + method to test + custom attribute type to search + + true if is tagged by a + attribute, false otherwise. + + + or + is a null reference + + + You can use this method to check that a method is tagged by a + specified attribute. + + + + + Gets a value indicating if the method info is tagged + by a instance. + + method to test + custom attribute type to search + + true if is tagged by a + attribute, false otherwise. + + + or + is a null reference + + + You can use this method to check that a method is tagged by a + specified attribute. + + + + + Gets the first instance of + from the method custom attributes. + + Method to test + custom attribute type to search + + First instance of + from the method custom attributes. + + + or + is a null reference + + + is not tagged by an attribute of type + + + + You can use this method to retreive a specified attribute + instance of a method. + + + + + Gets the first instance of + from the method custom attributes. + + Method to test + custom attribute type to search + + First instance of + from the method custom attributes; otherwize + a null reference + + + or + is a null reference + + + You can use this method to retreive a specified attribute + instance of a method. + + + + + Gets the first method of the type + that is tagged by a + instance. + + type to test + custom attribute type to search + + First method of that + that is tagged by a + instance, null if no method is tagged by the specified attribute + type. + + + or + is a null reference + + + You can use this method to retreive a tagged method + + + + + Gets all methods of the type + that are tagged by a + instance. + + type to test + custom attribute type to search + + collection of type that + that are tagged by a + instance. + + + or + is a null reference + + + You can use this method to retreive all the methods of a type + tagged by a . + + + + + Gets a value indicating if the type contains + a Method with the signature defined by . + + + Checks if a type has a desired Method. + + type to test + arguments of the Method + true if contains a Method matching + types + t is a null reference + + + + Retreives the that matches the signature. + + type to test + Method parameter types + + The instance of matching + the signature. + + is a null reference + + No Method of type match the signature defined + by . + + + This method tries to retreive a Method matching the signature + and throws if it failed. + + + + + Retreives the that matches the signature, + given the list of arguments. + + type to test + Method arguments from which the signature + is deduced + + The instance of matching + the signature defined by the list of arguments. + + is a null reference + + One of the args item is a null reference + + + No Method of type match the signature defined + by . + + + This methods retreives the types of and + looks for a Method matching that signature. + + + + + Creates an instance of the type using + the default Method. + + type to instanciate + type instance + + + + Creates an instance of the type using + the Method that matches the signature defined by + + + type to instanciate + argument of the Method + type instance initialized using + + + + Gets a value indicating if the type + has an indexer that takes arguments. + + + Checks that an indexer with a given signature exists in the class. + + type that holds the indexer + indexer arguments + true if an indexer that matched the signature was found, + false otherwise + + + + + Retreives the indexer that matches the signature + + + Safe retreival of an indexer, given it's signature + + type that holds the indexer + indexer arguments + + + + Gets the value of the property . + + property + object instnace + property arguments (in case of an indexer + property value + + + + Gets a value indicating if the match + the + + property or method paramter info + tested signature + + + + Assertion class for Database related object. + + + + + A private constructor disallows any instances of this object. + + + + + Asserts that two are equal. + + Expected instance. + Actual instance. + + + + Asserts that two are equal. + + Expected instance. + Actual instance. + + + Insipired from this + + blog entry.. + + + + + + Assert that schemas are equal. + + + + + Assert that schemas and data are equal. + + + + + Assert that data are equal. + + + + + Data Test fixture. + + + + + Default constructor + + + + + + + Constructor with a fixture description + + fixture description + + + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + +This example shows a test fixture class implementing the Simple Test pattern. +It tests image based method of the Graphics class in GDI+. + + +A set up method +(tagged by is used to create a new bitmap, while +a tear down (tagged by ) is used to released the bitmap. + + +[TestFixture("Bitmap")] +public GraphicsAndBitmapTest +{ + private Bitmap bmp; + + [SetUp] + public void SetUp() + { + this.bmp = new Bitmap(300,300); + } + + [Test] + public void CreateGraphics() + { + Graphics g = Graphcis.FromImage(this.bmp); + Assert.IsNotNull(g); + Assert.AreEqual(g.Width,this.bmp.Width); + ... + } + + ... + + [TearDown] + public void TearDownCanHaveOtherNames() + { + if(this.bmp!=null) + this.bmp.Dispose(); + } +} + + + + + + Tags method that provide data for the tests. + + + + + + Tag method that should return in a given time interval. + + + + + + Tags method that fill collections with data. + + + + + + Tags test methods that are ignored. + + + + + + This attribute collects the test importance information. + + + Fixture importance is labelled from 0, critical to higher values + representing less critical tests. + + + + + Tag method that provider a collection, an inde + + + + + + Default constructor - initializes all fields to default values + + + + + Default constructor - initializes all fields to default values + and int iterator + + + + + Required designer variable. + + + + + Clean up any resources being used. + + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Tag method that gives a list of culture that the test should run on. + + + + + + Summary description for ProviderFixtureDecoratorPatternAttribute. + + + + + Performance Assertion class + + + + + Creates a countdown timer that will assert if execution time exceeds maximum duration. + + + + + Runtime statistics on CLR exception handling. + + + + + This counter displays the total number of exceptions thrown since the start of the application. These include both .NET exceptions and unmanaged exceptions that get converted into .NET exceptions e.g. null pointer reference exception in unmanaged code would get re-thrown in managed code as a .NET System.NullReferenceException; this counter includes both handled and unhandled exceptions. Exceptions that are re-thrown would get counted again. Exceptions should only occur in rare situations and not in the normal control flow of the program. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of exceptions thrown per second. These include both .NET exceptions and unmanaged exceptions that get converted into .NET exceptions e.g. null pointer reference exception in unmanaged code would get re-thrown in managed code as a .NET System.NullReferenceException; this counter includes both handled and unhandled exceptions. Exceptions should only occur in rare situations and not in the normal control flow of the program; this counter was designed as an indicator of potential performance problems due to large (>100s) rate of exceptions thrown. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of .NET exception filters executed per second. An exception filter evaluates whether an exception should be handled or not. This counter tracks the rate of exception filters evaluated; irrespective of whether the exception was handled or not. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of finally blocks executed per second. A finally block is guaranteed to be executed regardless of how the try block was exited. Only the finally blocks that are executed for an exception are counted; finally blocks on normal code paths are not counted by this counter. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of stack frames traversed from the frame that threw the .NET exception to the frame that handled the exception per second. This counter resets to 0 when an exception handler is entered; so nested exceptions would show the handler to handler stack depth. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Stats for CLR Remoting. + + + + + This counter displays the number of remote procedure calls invoked per second. A remote procedure call is a call on any object outside the caller;s AppDomain. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of remote procedure calls invoked since the start of this application. A remote procedure call is a call on any object outside the caller;s AppDomain. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of remoting channels registered across all AppDomains since the start of the application. Channels are used to transport messages to and from remote objects. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of remoting proxy objects created in this process since the start of the process. Proxy object acts as a representative of the remote objects and ensures that all calls made on the proxy are forwarded to the correct remote object instance. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of context-bound classes loaded. Classes that can be bound to a context are called context-bound classes; context-bound classes are marked with Context Attributes which provide usage rules for synchronization; thread affinity; transactions etc. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of context-bound objects allocated per second. Instances of classes that can be bound to a context are called context-bound objects; context-bound classes are marked with Context Attributes which provide usage rules for synchronization; thread affinity; transactions etc. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of remoting contexts in the application. A context is a boundary containing a collection of objects with the same usage rules like synchronization; thread affinity; transactions etc. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Help not available. + + + + + The cumulative total number of socket connections established for this process since the process was started. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + The cumulative total number of bytes received over all open socket connections since the process was started. This number includes data and any protocol information that is not defined by the TCP/IP protocol. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + The cumulative total number of bytes sent over all open socket connections since the process was started. This number includes data and any protocol information that is not defined by the TCP/IP protocol. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + The cumulative total number of datagram packets received since the process was started. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + The cumulative total number of datagram packets sent since the process was started. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Counters for CLR Garbage Collected heap. + + + + + This counter displays the number of times the generation 0 objects (youngest; most recently allocated) are garbage collected (Gen 0 GC) since the start of the application. Gen 0 GC occurs when the available memory in generation 0 is not sufficient to satisfy an allocation request. This counter is incremented at the end of a Gen 0 GC. Higher generation GCs include all lower generation GCs. This counter is explicitly incremented when a higher generation (Gen 1 or Gen 2) GC occurs. _Global_ counter value is not accurate and should be ignored. This counter displays the last observed value. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of times the generation 1 objects are garbage collected since the start of the application. The counter is incremented at the end of a Gen 1 GC. Higher generation GCs include all lower generation GCs. This counter is explicitly incremented when a higher generation (Gen 2) GC occurs. _Global_ counter value is not accurate and should be ignored. This counter displays the last observed value. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of times the generation 2 objects (older) are garbage collected since the start of the application. The counter is incremented at the end of a Gen 2 GC (also called full GC). _Global_ counter value is not accurate and should be ignored. This counter displays the last observed value. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the bytes of memory that survive garbage collection (GC) and are promoted from generation 0 to generation 1; objects that are promoted just because they are waiting to be finalized are not included in this counter. This counter displays the value observed at the end of the last GC; its not a cumulative counter. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the bytes of memory that survive garbage collection (GC) and are promoted from generation 1 to generation 2; objects that are promoted just because they are waiting to be finalized are not included in this counter. This counter displays the value observed at the end of the last GC; its not a cumulative counter. This counter is reset to 0 if the last GC was a Gen 0 GC only. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the bytes per second that are promoted from generation 0 (youngest) to generation 1; objects that are promoted just because they are waiting to be finalized are not included in this counter. Memory is promoted when it survives a garbage collection. This counter was designed as an indicator of relatively long-lived objects being created per sec. This counter displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the bytes per second that are promoted from generation 1 to generation 2 (oldest); objects that are promoted just because they are waiting to be finalized are not included in this counter. Memory is promoted when it survives a garbage collection. Nothing is promoted from generation 2 since it is the oldest. This counter was designed as an indicator of very long-lived objects being created per sec. This counter displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the bytes of memory that are promoted from generation 0 to generation 1 just because they are waiting to be finalized. This counter displays the value observed at the end of the last GC; its not a cumulative counter. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the bytes of memory that are promoted from generation 1 to generation 2 just because they are waiting to be finalized. This counter displays the value observed at the end of the last GC; its not a cumulative counter. This counter is reset to 0 if the last GC was a Gen 0 GC only. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the maximum bytes that can be allocated in generation 0 (Gen 0); its does not indicate the current number of bytes allocated in Gen 0. A Gen 0 GC is triggered when the allocations since the last GC exceed this size. The Gen 0 size is tuned by the Garbage Collector and can change during the execution of the application. At the end of a Gen 0 collection the size of the Gen 0 heap is infact 0 bytes; this counter displays the size (in bytes) of allocations that would trigger the next Gen 0 GC. This counter is updated at the end of a GC; its not updated on every allocation. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of bytes in generation 1 (Gen 1); this counter does not display the maximum size of Gen 1. Objects are not directly allocated in this generation; they are promoted from previous Gen 0 GCs. This counter is updated at the end of a GC; its not updated on every allocation. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of bytes in generation 2 (Gen 2). Objects are not directly allocated in this generation; they are promoted from Gen 1 during previous Gen 1 GCs. This counter is updated at the end of a GC; its not updated on every allocation. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current size of the Large Object Heap in bytes. Objects greater than 20 KBytes are treated as large objects by the Garbage Collector and are directly allocated in a special heap; they are not promoted through the generations. This counter is updated at the end of a GC; its not updated on every allocation. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of garbage collected objects that survive a collection because they are waiting to be finalized. If these objects hold references to other objects then those objects also survive but are not counted by this counter; the "Promoted Finalization-Memory from Gen 0" and "Promoted Finalization-Memory from Gen 1" counters represent all the memory that survived due to finalization. This counter is not a cumulative counter; its updated at the end of every GC with count of the survivors during that particular GC only. This counter was designed to indicate the extra overhead that the application might incur because of finalization. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of GC Handles in use. GCHandles are handles to resources external to the CLR and the managed environment. Handles occupy small amounts of memory in the GCHeap but potentially expensive unmanaged resources. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the rate of bytes per second allocated on the GC Heap. This counter is updated at the end of every GC; not at each allocation. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the peak number of times a garbage collection was performed because of an explicit call to GC.Collect. Its a good practice to let the GC tune the frequency of its collections. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + % Time in GC is the percentage of elapsed time that was spent in performing a garbage collection (GC) since the last GC cycle. This counter is usually an indicator of the work done by the Garbage Collector on behalf of the application to collect and compact memory. This counter is updated only at the end of every GC and the counter value reflects the last observed value; its not an average. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Not Displayed. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter is the sum of four other counters; Gen 0 Heap Size; Gen 1 Heap Size; Gen 2 Heap Size and the Large Object Heap Size. This counter indicates the current memory allocated in bytes on the GC Heaps. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the amount of virtual memory (in bytes) currently committed by the Garbage Collector. (Committed memory is the physical memory for which space has been reserved on the disk paging file). + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the amount of virtual memory (in bytes) currently reserved by the Garbage Collector. (Reserved memory is the virtual memory space reserved for the application but no disk or main memory pages have been used.) + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of pinned objects encountered in the last GC. This counter tracks the pinned objects only in the heaps that were garbage collected e.g. a Gen 0 GC would cause enumeration of pinned objects in the generation 0 heap only. A pinned object is one that the Garbage Collector cannot move in memory. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of sync blocks in use. Sync blocks are per-object data structures allocated for storing synchronization information. Sync blocks hold weak references to managed objects and need to be scanned by the Garbage Collector. Sync blocks are not limited to storing synchronization information and can also store COM interop metadata. This counter was designed to indicate performance problems with heavy use of synchronization primitives. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Stats for CLR interop. + + + + + This counter displays the current number of Com-Callable-Wrappers (CCWs). A CCW is a proxy for the .NET managed object being referenced from unmanaged COM client(s). This counter was designed to indicate the number of managed objects being referenced by unmanaged COM code. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of stubs created by the CLR. Stubs are responsible for marshalling arguments and return values from managed to unmanaged code and vice versa; during a COM Interop call or PInvoke call. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of times arguments and return values have been marshaled from managed to unmanaged code and vice versa since the start of the application. This counter is not incremented if the stubs are inlined. (Stubs are responsible for marshalling arguments and return values). Stubs usually get inlined if the marshalling overhead is small. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Reserved for future use. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Reserved for future use. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Counters for System.Data.SqlClient + + + + + The number of actual connections per second that are being made to servers + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of actual disconnects per second that are being made to servers + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections we get from the pool per second + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections we return to the pool per second + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections that are not using connection pooling + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections that are managed by the connection pooler + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of unique connection strings + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of unique connection strings waiting for pruning + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connection pools + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connection pools + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections currently in-use + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections currently available for use + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections currently waiting to be made ready for use + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections we reclaim from GCed from external connections + + + + + Gets the value of the . + + + Value returned by . + + + + + .Net CLR Data + + + + + Current number of connections, pooled or not. + + + + + Gets the value of the . + + + Value returned by . + + + + + Current number of connections in all pools associated with the process. + + + + + Gets the value of the . + + + Value returned by . + + + + + Current number of pools associated with the process. + + + + + Gets the value of the . + + + Value returned by . + + + + + The highest number of connections in all pools since the process started. + + + + + Gets the value of the . + + + Value returned by . + + + + + The total number of connection open attempts that have failed for any reason. + + + + + Gets the value of the . + + + Value returned by . + + + + + The total number of command executes that have failed for any reason. + + + + + Gets the value of the . + + + Value returned by . + + + + + Statistics for CLR Class Loader. + + + + + This counter displays the current number of classes loaded in all Assemblies. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the cumulative number of classes loaded in all Assemblies since the start of this application. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of classes loaded per second in all Assemblies. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of AppDomains loaded in this application. AppDomains (application domains) provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications running in the same process. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the peak number of AppDomains loaded since the start of this application. AppDomains (application domains) provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications running in the same process. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of AppDomains loaded per second. AppDomains (application domains) provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications running in the same process. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current number of Assemblies loaded across all AppDomains in this application. If the Assembly is loaded as domain-neutral from multiple AppDomains then this counter is incremented once only. Assemblies can be loaded as domain-neutral when their code can be shared by all AppDomains or they can be loaded as domain-specific when their code is private to the AppDomain. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of Assemblies loaded since the start of this application. If the Assembly is loaded as domain-neutral from multiple AppDomains then this counter is incremented once only. Assemblies can be loaded as domain-neutral when their code can be shared by all AppDomains or they can be loaded as domain-specific when their code is private to the AppDomain. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of Assemblies loaded across all AppDomains per second. If the Assembly is loaded as domain-neutral from multiple AppDomains then this counter is incremented once only. Assemblies can be loaded as domain-neutral when their code can be shared by all AppDomains or they can be loaded as domain-specific when their code is private to the AppDomain. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Reserved for future use. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Reserved for future use. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the peak number of classes that have failed to load since the start of the application. These load failures could be due to many reasons like inadequate security or illegal format. Full details can be found in the profiling services help. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of classes that failed to load per second. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. These load failures could be due to many reasons like inadequate security or illegal format. Full details can be found in the profiling services help. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the current size (in bytes) of the memory committed by the class loader across all AppDomains. (Committed memory is the physical memory for which space has been reserved on the disk paging file.) + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of AppDomains unloaded since the start of the application. If an AppDomain is loaded and unloaded multiple times this counter would count each of those unloads as separate. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of AppDomains unloaded per second. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Stats for CLR Security. + + + + + This counter displays the total number of runtime Code Access Security (CAS) checks performed since the start of the application. Runtime CAS checks are performed when a caller makes a call to a callee demanding a particular permission; the runtime check is made on every call by the caller; the check is done by examining the current thread stack of the caller. This counter used together with "Stack Walk Depth" is indicative of performance penalty for security checks. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Reserved for future use. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of linktime Code Access Security (CAS) checks since the start of the application. Linktime CAS checks are performed when a caller makes a call to a callee demanding a particular permission at JIT compile time; linktime check is performed once per caller. This count is not indicative of serious performance issues; its indicative of the security system activity. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the percentage of elapsed time spent in performing runtime Code Access Security (CAS) checks since the last such check. CAS allows code to be trusted to varying degrees and enforces these varying levels of trust depending on code identity. This counter is updated at the end of a runtime security check; it represents the last observed value; its not an average. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Not Displayed. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the depth of the stack during that last runtime Code Access Security check. Runtime Code Access Security check is performed by crawling the stack. This counter is not an average; it just displays the last observed value. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Stats for CLR Jit. + + + + + This counter displays the total number of methods compiled Just-In-Time (JIT) by the CLR JIT compiler since the start of the application. This counter does not include the pre-jitted methods. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total IL bytes jitted since the start of the application. This counter is exactly equivalent to the "Total # of IL Bytes Jitted" counter. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total IL bytes jitted since the start of the application. This counter is exactly equivalent to the "# of IL Bytes Jitted" counter. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the rate at which IL bytes are jitted per second. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the peak number of methods the JIT compiler has failed to JIT since the start of the application. This failure can occur if the IL cannot be verified or if there was an internal error in the JIT compiler. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the percentage of elapsed time spent in JIT compilation since the last JIT compilation phase. This counter is updated at the end of every JIT compilation phase. A JIT compilation phase is the phase when a method and its dependencies are being compiled. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Not Displayed. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Stats for CLR Locks and Threads. + + + + + This counter displays the total number of times threads in the CLR have attempted to acquire a managed lock unsuccessfully. Managed locks can be acquired in many ways; by the "lock" statement in C# or by calling System.Monitor.Enter or by using MethodImplOptions.Synchronized custom attribute. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Rate at which threads in the runtime attempt to acquire a managed lock unsuccessfully. Managed locks can be acquired in many ways; by the "lock" statement in C# or by calling System.Monitor.Enter or by using MethodImplOptions.Synchronized custom attribute. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of threads currently waiting to acquire some managed lock in the application. This counter is not an average over time; it displays the last observed value. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of threads that waited to acquire some managed lock since the start of the application. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of threads per second waiting to acquire some lock in the application. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of current .NET thread objects in the application. A .NET thread object is created either by new System.Threading.Thread or when an unmanaged thread enters the managed environment. This counters maintains the count of both running and stopped threads. This counter is not an average over time; it just displays the last observed value. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of native OS threads created and owned by the CLR to act as underlying threads for .NET thread objects. This counters value does not include the threads used by the CLR in its internal operations; it is a subset of the threads in the OS process. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of threads that are currently recognized by the CLR; they have a corresponding .NET thread object associated with them. These threads are not created by the CLR; they are created outside the CLR but have since run inside the CLR at least once. Only unique threads are tracked; threads with same thread ID re-entering the CLR or recreated after thread exit are not counted twice. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the total number of threads that have been recognized by the CLR since the start of this application; these threads have a corresponding .NET thread object associated with them. These threads are not created by the CLR; they are created outside the CLR but have since run inside the CLR at least once. Only unique threads are tracked; threads with same thread ID re-entering the CLR or recreated after thread exit are not counted twice. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + This counter displays the number of threads per second that have been recognized by the CLR; these threads have a corresponding .NET thread object associated with them. These threads are not created by the CLR; they are created outside the CLR but have since run inside the CLR at least once. Only unique threads are tracked; threads with same thread ID re-entering the CLR or recreated after thread exit are not counted twice. This counter is not an average over time; it displays the difference between the values observed in the last two samples divided by the duration of the sample interval. + + + + + Gets the value of the . + + + Value returned by + for the current instance. + + + + + Counters for System.Data.OracleClient + + + + + The number of actual connections per second that are being made to servers + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of actual disconnects per second that are being made to servers + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections we get from the pool per second + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections we return to the pool per second + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections that are not using connection pooling + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections that are managed by the connection pooler + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of unique connection strings + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of unique connection strings waiting for pruning + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connection pools + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connection pools + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections currently in-use + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections currently available for use + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections currently waiting to be made ready for use + + + + + Gets the value of the . + + + Value returned by . + + + + + The number of connections we reclaim from GCed from external connections + + + + + Gets the value of the . + + + Value returned by . + + + + + Summary description for PostItAttribute. + + + + + Tag use to mark a method that writes data to a device. + + + + + + Reflection Assertion class + + + + + Asserts whether an instance of the + can be assigned from an instance of . + + + Parent instance. + + + Child instance. + + + + + Asserts whether is an instance of the + . + + + instance. + + + Child instance. + + + + + Asserts that the type has a default public constructor + + + + + Asserts that the type has a public instance constructor with a signature defined by parameters. + + + + + Asserts that the type has a constructor, with the specified bindind flags, with a signature defined by parameters. + + + + + Asserts that the type has a public instance method with a signature defined by parameters. + + + + + Asserts that the type has a method, with the specified bindind flags, with a signature defined by parameters. + + + + + Asserts that the type has a public field method with a signature defined by parameters. + + + + + Asserts that the type has a field, with the specified bindind flags, with a signature defined by parameters. + + + + + This tag defines test method that will be repeated the specified number + of times. + + + + + + Provides a row of values using in conjunction with + to bind values to the parameters of a row test method. + + + + + Provides a row of values using in conjunction with + to bind values to the parameters of a row test method. + + The row of values to bind + + + + Gets the row of values. + + The row of values + + + + Gets or sets the type of exception that is expected to be thrown when this + row is tested, or null if none. + + + + + Declares a row test when applied to a test method along with one or more + attributes. + + + + + Security Assertion class + + + + + Asserts that is authenticated. + + + + + Asserts that is not authenticated. + + + + + Asserts that the current windows identity is authenticated. + + + + + Asserts that the current windows identity is not authenticated. + + + + + Asserts that the current windows identity is in . + + + + + Asserts that the current windows identity is in + role. + + + + + Asserts that the current windows identity is in + role. + + + + + Asserts that the current windows identity is in + role. + + + + + Asserts that the current windows identity is in + role. + + + + + Verifies that the type is serializable with the XmlSerializer object. + + + type to test. + + + + + Serializes and deserialies to/from XML and checks that the results are the same. + + + Object to test + + + + + Tag use to mark a method that initiliazes the fixture instance. + + + + + + String Assertion class + + + + + Asserts that two strings are equal, ignoring the case + + + Expected string + + + Actual string + + + + + Asserts that the string is non null and empty + + + String to test. + + + + + Asserts that the string is non null and non empty + + + String to test. + + + + + Asserts the regular expression reg makes a full match on s + + + String to test. + + + Regular expression + + + + + Asserts the regular expression regex makes a full match on + . + + + String to test. + + + Regular expression + + + + + Asserts the regular expression reg makes a match on s + + + String to test. + + + Regular expression + + + + + Asserts the regular expression regex makes a match on s + + + String to test. + + + A instance. + + + + + Asserts the regular expression reg makes a match on s + + + String to test. + + + Regular expression + + + + + Asserts the regular expression regex makes a match on s + + + String to test. + + + A instance. + + + + + Asserts the string does not contain c + + + String to test. + + + Variable list of characeters. + + + + + Tag use to mark a method that cleans up the resource of the fixture instance. + + + + + + Tag use to mark a mark a unit test method. + + + + + + Contributes additional tests and setup or teardown steps to the + lifecycle defined by . + + + + + Called to add runs to perform before setup. + + The collection to update + + + + Called to add runs to perform during the test execution cycle. + + The collection to update + + + + Called to add runs to perform after teardown. + + The collection to update + + + + Creates an order of execution in the fixture. + + + + This fixture is used to implement the Process testing advertised by + Marc Clifton' + Code Project + article. + + + + + + Initializes a new instance of with the given order. + + order of execution + + + + Initializes a new instance of with the given order + and description. + + order of execution + description of the test + + + + Returns a string that represents the instance. + + + String representing the object. + + + + + Gets or sets the order execution + + + The order of execution + + + + + This tag defines test method that will invoke the method in the specified + number of concurrent threads. + + + + + + Gets a list of values separated by ; + + + + + + Enumeration Pattern implementations. + + +Implements:Enumeration Test Pattern +Login: + +{DataProvider} +{CopyToProvider} +[SetUp] +(EnumerationTester) + - GetEnumerator + - Enumerate + - ElementWiseEquality + - Current + - CurrentWithoutMoveNet + - CurrentPastEnd + - Reset + - CollectionChanged +[TearDown] + + + +This example tests the and . + + + + + + + + + + Could not find . + + + + + Creates an exception with a type + and an inner exception. + + Error type + Inner exception + + + + + + + + + + + + + + + + + + + + + Default constructor + + + XPath to the desired data + + + + + + + Constructor with a fixture description + + + XPath to the desired data + + fixture description + + + + + + Summary description for ForEachTestRunInvoker. + + + + + + The MbUnit.Framework contains the set of built-in attributes. + + + Use the static methods of to test your assertions. You can also + do security related assertion using , + data related assertions using and + XML related assertions using (which comes from XmlUnit, http://xmlunit.sourceforge.net) + , Reflection based assertion and + String and text based assertion . + + + + + + Process Test Pattern fixture. + + + Implements: Process Test Fixture + Logic: + + [SetUp] + {TestSequence} + [TearDown] + + + + This fixture implements the Process Test Fixture as described in the + CodeProject + article from Marc Clifton. + + + In this implementation, reverse traversal is not implemented. + A process can be seen as a linear graph, a very simple model. If you + need more evolved models, use Model Based Testing. + + + + +This is the example for the CodeProject +article adapted to MbUnit. + + +[ProcessTestFixture] +public class POSequenceTest +{ + ... + [TestSequence(1)] + public void POConstructor() + { + po=new PurchaseOrder(); + Assert.AreEqual(po.Number,"", "Number not initialized."); + Assert.AreEqual(po.PartCount,0, "PartCount not initialized."); + Assert.AreEqual(po.ChargeCount,0, "ChargeCount not initialized."); + Assert.AreEqual(po.Invoice,null, "Invoice not initialized."); + Assert.AreEqual(po.Vendor,null, "Vendor not initialized."); + } + + [TestSequence(2)] + public void VendorConstructor() + { + vendor=new Vendor(); + Assert.AreEqual(vendor.Name,"", "Name is not an empty string."); + Assert.AreEqual(vendor.PartCount,0, "PartCount is not zero."); + } + ... + + +Use to mark a class as process test fixture and use the + attribute to create the order of the process. The fixture also supports +SetUp and TearDown methods. + + + + + + Initialize a + instance. + + + + + Constructor with a fixture description + + fixture description + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + + + A resource-based data provider + + + + + A file-based data provider + + + + + + + + + Default constructor + + + XPath to the desired data + + + + + + + Constructor with a fixture description + + + XPath to the desired data + + fixture description + + + + + + A single test case of a . + + + + + Initializes a new instance + with name and delegate. + + + Name of the test case + + + Delegate called by the test case + + + Parameters of the delegate + + + or + is a null reference (Nothing in Visual Basic) + + + is empty. + + + + + Invokes using the parameters returned by + . + + + + + + Gets the name of the test case + + + The name of the test case + + + + + Collection indexing test class + + + + + + Collection order tester class. + + + + + Tests for the and . + + + + + + + + Simple Test Pattern fixture. + + +Implements: Simple Test Pattern +Login: + +[SetUp] +{Test} +[TearDown] + + + +This is the classic unit test fixture attribute. It defines a class that contains unit +tests. + + +The test execution logic is described by the following sequence of custom attributes: +where [] denotes an optional attribute, {} denotes a custom attribute +that can tag multiple number of methods. + + +Unit test methods must be tagged with the , return +void and take no arguments: + +[Test] +public void UnitTest() +{ + ... +} + +The same fixture can hold an arbitrary number of unit test methods. + + +If the fixture needs initilization, you can add a set up method tagged with the + attribute. Note that there can be only one +method tagged with . + + +Symmetricaly, you can specify a method that will clean up resources allocated by +the fixture. This method must be tagged with the +and there can be only one method with this attribute. + + + + +This example shows a test fixture class implementing the Simple Test pattern. +It tests image based method of the Graphics class in GDI+. + + +A set up method +(tagged by is used to create a new bitmap, while +a tear down (tagged by ) is used to released the bitmap. + + +[TestFixture("Bitmap")] +public GraphicsAndBitmapTest +{ + private Bitmap bmp; + + [SetUp] + public void SetUp() + { + this.bmp = new Bitmap(300,300); + } + + [Test] + public void CreateGraphics() + { + Graphics g = Graphcis.FromImage(this.bmp); + Assert.IsNotNull(g); + Assert.AreEqual(g.Width,this.bmp.Width); + ... + } + + ... + + [TearDown] + public void TearDownCanHaveOtherNames() + { + if(this.bmp!=null) + this.bmp.Dispose(); + } +} + + + + + + Default constructor + + + + + + + Constructor with a fixture description + + fixture description + + + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + +This example shows a test fixture class implementing the Simple Test pattern. +It tests image based method of the Graphics class in GDI+. + + +A set up method +(tagged by is used to create a new bitmap, while +a tear down (tagged by ) is used to released the bitmap. + + +[TestFixture("Bitmap")] +public GraphicsAndBitmapTest +{ + private Bitmap bmp; + + [SetUp] + public void SetUp() + { + this.bmp = new Bitmap(300,300); + } + + [Test] + public void CreateGraphics() + { + Graphics g = Graphcis.FromImage(this.bmp); + Assert.IsNotNull(g); + Assert.AreEqual(g.Width,this.bmp.Width); + ... + } + + ... + + [TearDown] + public void TearDownCanHaveOtherNames() + { + if(this.bmp!=null) + this.bmp.Dispose(); + } +} + + + + + + A named collection of uniquely named . + + + + + Initializes a instance + with . + + + name of the suite + + + is a null reference + (Nothing in Visual Basic) + + + is empty. + + + + + Adds the test case to the suite + + + instance to add. + + + The suite already contains a test case named . + + + + + Removes the test case from the suite + + + Test case to remove + + + is a null reference + (Nothing in Visual Basic) + + + + + Adds a new to the suite. + + + Name of the new test case + + + invoked by the test case + + + parameters sent to when invoked + + + is a null reference + (Nothing in Visual Basic) + + + is empty. + + + The suite already contains a test case named . + + + + + Gets the name. + + + The name. + + + + + Gets a collection of . + + + A collection of . + + + + + Test Suite fixture. + + + + + Default constructor + + + + + + + Constructor with a fixture description + + fixture description + + + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + +This example shows a test fixture class implementing the Simple Test pattern. +It tests image based method of the Graphics class in GDI+. + + +A set up method +(tagged by is used to create a new bitmap, while +a tear down (tagged by ) is used to released the bitmap. + + +[TestFixture("Bitmap")] +public GraphicsAndBitmapTest +{ + private Bitmap bmp; + + [SetUp] + public void SetUp() + { + this.bmp = new Bitmap(300,300); + } + + [Test] + public void CreateGraphics() + { + Graphics g = Graphcis.FromImage(this.bmp); + Assert.IsNotNull(g); + Assert.AreEqual(g.Width,this.bmp.Width); + ... + } + + ... + + [TearDown] + public void TearDownCanHaveOtherNames() + { + if(this.bmp!=null) + this.bmp.Dispose(); + } +} + + + + + + Type fixture pattern implementation. + + +Implements: Type Test Pattern +Logic: + +{Provider} +[SetUp] +{Test} +[TearDown] + + + +This fixture is quite similar to the Simple Test pattern, but it applies to +any instance of a particular type provided by the user. + + +The test fixture first looks for methods tagged with the +method. These method must return an object assignable with the tested type. This instance will +be feeded to the other methods of the fixture. + + + + +This example shows the squeleton of a fixture tests the IDictionary interface, +the fixture implements the Type Test pattern. + + +The tested instances are feeded by the methods tagged with the . +These methods must return an instance that is assignable with . +Subsequent will receive the created instance as parameter. + + +[TypeFixture(typeof(IDictionary),"IDictionary interface fixture")] +public void DictionaryTest +{ + [Provider(typeof(Hashtable))] + public Hashtable ProvideHashtable() + { + return new Hashtable(); + } + + [Provider(typeof(SortedList))] + public SortedList ProvideSortedList() + { + return new SortedList(); + } + + // tests + [Test] + [ExpectedException(typeof(ArgumentException))] + public void AddDuplicate(IDictionary dic) // dic comes from a provider class + { + dic.Add("key",null); + dic.Add("key",null); // boom + } + +} + + + + + + Creates a fixture for the type. + + + Initializes the attribute with . + + type to apply the fixture to + testedType is a null reference + + + + Creates a fixture for the type + and a description + + + Initializes the attribute with . + + type to apply the fixture to + description of the fixture + testedType is a null reference + + + + Creates the execution logic + + + See summary. + + A instance that represent the type + test logic. + + + +This example shows the squeleton of a fixture tests the IDictionary interface, +the fixture implements the Type Test pattern. + + +The tested instances are feeded by the methods tagged with the . +These methods must return an instance that is assignable with . +Subsequent will receive the created instance as parameter. + + +[TypeFixture(typeof(IDictionary),"IDictionary interface fixture")] +public void DictionaryTest +{ + [Provider(typeof(Hashtable))] + public Hashtable ProvideHashtable() + { + return new Hashtable(); + } + + [Provider(typeof(SortedList))] + public SortedList ProvideSortedList() + { + return new SortedList(); + } + + // tests + [Test] + [ExpectedException(typeof(ArgumentException))] + public void AddDuplicate(IDictionary dic) // dic comes from a provider class + { + dic.Add("key",null); + dic.Add("key",null); // boom + } + +} + + + + + + Gets a list of member names separated by ; + + + + + + A with verified result. + + + + + Web related assertions. + + + + + Verifies that has ViewState enabled. + + + + + Verifies that has not ViewState enabled. + + + + + Verifies that is visible. + + + + + Verifies that is not visible. + + + + + Verifies that ID is equal to . + + + + + Verifies that has child controls. + + + + + Verifies that has no child controls. + + + + + Verifies that the + property of and + are equal. + + + + + Verifies that the + property of is equal to + are equal. + + + + + Verifies that is a child control + of + + + + + Verifies that is the ID of a child control + of + + + + + Verifies that is a not child control + of + + + + + Verifies that is the not ID of a child control + of + + + + + Verifies that the property of + is equal to . + + + + + Verifies that the property of + is equal to . + + + + + Verifies that the property of + is true. + + + + + Verifies that the property of + is false. + + + + + Verifies that the property of + is true. + + + + + Verifies that the property of + is false. + + + + + Verifies that the property of + is true. + + + + + Verifies that the property of + is false. + + + + + Tag use to mark a method that writes data to a device. + + + + + + Comparing 2 attributes with the same name but different values + + + + + Comparing 2 attribute lists with the same attributes in different sequence + + + + + Summary description for FlowControlException. + + + + + + The MbUnit.Framework.Xml contains Xml-specific assertion. + The classes of this namespace are extracted from the XmlUnit project. + + + /* + ****************************************************************** + Copyright (c) 2001, Jeff Martin, Tim Bacon + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of the xmlunit.sourceforge.net nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + + ****************************************************************** + */ + + + + + diff --git a/Tools/MbUnit/MbUnit.GUI.exe.config b/Tools/MbUnit/MbUnit.GUI.exe.config index 46bf22b3..dd055b5a 100644 --- a/Tools/MbUnit/MbUnit.GUI.exe.config +++ b/Tools/MbUnit/MbUnit.GUI.exe.config @@ -1,14 +1,14 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/Tools/MbUnit/TestFu.XML b/Tools/MbUnit/TestFu.XML index 30fe067d..e132c2b4 100644 --- a/Tools/MbUnit/TestFu.XML +++ b/Tools/MbUnit/TestFu.XML @@ -1,5483 +1,5483 @@ - - - - TestFu - - - - - Static helper class for creating data binders - - - - - Summary description for DataGeneratorCollection. - - - - - A collection of . - - - - - - Adds a to the collection. - - - to add to the collection. - - - is a null reference - (Nothing in Visual Basic) - - - - - Removes a from the collection. - - - to remove from the collection. - - - is a null reference - (Nothing in Visual Basic) - - - - - Removes a associated to - from the collection. - - - whose generator is to be removed from the collection. - - - is a null reference - (Nothing in Visual Basic) - - - - - Removes a associated to - from the collection. - - - Column named whose generator is to be removed from the collection. - - - is a null reference - (Nothing in Visual Basic) - - - - - Gets the associated to the - . - - - is a null reference - (Nothing in Visual Basic) - - - - - Gets the associated to the column named - . - - - is a null reference - (Nothing in Visual Basic) - - - - - A collection of . - - - - - - Summary description for TablePopulatorCollection. - - - - - A collection of . - - - - - - A collection of . - - - - - - Abstract class to perform administrative tasks on a database - - - - - - Initializes an instance of with the connection string. - - - Connection string to the SQL server without initial catalog - - - Catalog name - - - is a null reference (Nothing in Visual Basic) - - - - - Creates a backup of the specified database using the specified - and . - - - A defining the type of output device. - - - Device path. - - - is a null - reference (Nothing in Visual Basic) - - - - - Restores a backup of the specified database using the specified - and . - - - A defining the type of output device. - - - Device path. - - - is a null - reference (Nothing in Visual Basic) - - - - If you plan to override an existing database, you must first drop this database. - This method takes a conservative behavior and will not override an existing database. - - - - - - Creates a new database on the server - - - - - Drops an existing new database on the server - - - is a null - reference (Nothing in Visual Basic) - - - - - Gets a value indicating if the current database exists. - - - true if it exists; otherwise, false. - - - - - Drops the table. - - - Name of the table to drop - - - - This method takes care of removing the constraints associated - to the table before removing the table. - - - - - - Gets a value indicating if the database contains - the table. - - - Name of the table to search - - - true if a table named is contained - in the databse;oterwise false. - - - - - Executes a non-query in a safe, transactional environement. - - - Query to execute. - - - - - Gets or sets the connection string with Initial Catalog information - - - Connection string. - - - - - Gets or sets the database name - - - The database name. - - - - - Gets or sets the database owner. - - - Database owner name. - - - - - Gets the connection string with Initial Catalog information. - - - Connection string with Initial catalog information. - - - - - Enumeration of available SQL backup devices - - - - - - DISK device - - - - - TAPE device - - - - - Output to named dump - - - - - A factory for and - instances. - - - - - - Creates a instance. - - - Connection string to server - - - A instance. - - - - - An abstract base class for test fixtures involving database testing. - - -The DbFixture (SqlFixture for MsSQL server) can be used as a base class for the -fixtures involving database testing. - -[TestFixture] -public class DatabaseTest : SqlFixture -{ - public DatabaseTest() - :base("Data Source=testserver;...","MyTestDatabase") - {} - - [SetUp] - public void SetUp() - { - this.Open(); - this.BeginTransaction(); - } - - [Test] - public void Selec() - { - IDbCollection cmd = this.Connection.CreateCommand("select * from anytable",this.Transaction); - ... - } - - [TearDown] - public void TearDown() - { - this.Close(); - } -} - - - - - - Initializes a with a connection string. - - - Connection string for accessing the test database. - - - is a null reference - (Nothing in Visual Basic) - - - - - Opens a instance with the - . - - - - This method must be implemented in inherited classes for different factorys. - - - - - - Executes a non-query command with the given parameters - - - Query format string - - - Query arguments for the format string - - - Number of affected rows - - - - The connection is automatically opened if necessary. - - - - - - Executes a scalar query with the given parameters - - - Query format string - - - Query arguments for the format string - - - Query result - - - - The connection is automatically opened if necessary. - - - - - - Executes query and returns the - instance - - - Query format string - - - Query arguments for the format string - - - A resulting from the query. - - - - The connection is automatically opened if necessary and the reader - is created with - option. - - - - - - Begins a new transaction. - - - - If a previous transaction was opened, by default, it is rolled back. - - - - The current connection is not created or not opened. - - - - - Commits the current transaction if any. - - - - - Rollsback the current transaction if any. - - - - - Closes the current connection. - - - - If a transaction was opened, it is first rolled back. - - - - - - Gets the database instance - - - A instance. - - - - - Gets the current connection instance. - - - instance. - - - - - Gets the current transaction. - - - A instance if was called - and the connection not closed; otherwise, a null reference (Nothing in Visual Basic) - - - - - Gets the connection string to access the db server (without - database information. - - - - - Gets the test database name. - - - - - - Gets the connection string to connecto the test database. - - - - - A random data generator for values. - - - - This method generates Byte arrays with length in the range - [, ]. - - - - - - Abstract base class from instance. - - - - - An random data generator. - - - - - - Resets the generator - - - - - Generates a new value and fills it in the corresponding . - - - - It is the user job to ensure that the instance - provided is compatible with the generator definition and more - specifically the it is associated with. - - - - - - Gets the generated type - - - Generated . - - - - - Gets or sets the probability to produce a NULL - - - This value determines the probability to produce a null value. - The probability ranges from - 0 - never, to 1 - always. - - - The probability to produce a null object. - - - - - Gets the target column - - - Target instance. - - - - - Resets the generator - - - - - Generates a new value - - - New random data. - - - - - Updates the internal data and verifies column information. - - - - - Gets the generated type - - - Generated type. - - - - - Gets the target column - - - Target instance. - - - - - Gets or sets the probability to produce a NULL - - - This value determines the probability to produce a null value. The probability ranges from - 0, never to 1 always. - - - The probability to produce a null object. - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum length of the generated value - - - Minimum generated length. Default is 16. - - - - - Gets or sets the maximum generated value - - - Maximum generated length. Default is 16. - - - - - A random generator of values. - - - - - Creates an instance with equal to 0.5. - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the probability to return true. - - - Probability to return true. - - - is not in [0,1]. - - - - - A random data generator for values. - - - - This method generates byte values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random data generator for values. - - - - This method generates DateTime values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random data generator for values. - - - - This method generates decimal values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random data generator for values. - - - - This method generates double values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random generator of values. - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - A random data generator for binary values. - - - - This method generates a bitmap of size - [ by ]. - - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the pixel format - - - - - - A random data generator for values. - - - - This method generates int values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random data generator for values. - - - - This method generates int values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random data generator for values. - - - - This method generates int values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - A random generator of instances. - - - - - Initializes a new instance of . - - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum length of the string - - - Minimum length of the string. - - - set proprety, the value is negative. - - - - - Gets or sets the maximum length of the string - - - Maximum length of the string. - - - set proprety, the value is less than 1. - - - - - A random data generator for values. - - - - This method generates float values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is - - - - - Generates a new value - - - New random data. - - - - - Generates a new value - - - New random data. - - - - - - - - This method generates float values in a range [, ]. - - - - - - Generates a new value - - - New random data. - - - - - Gets the generated type - - - Generated type. - - - - - Gets or sets the minimum generated value - - - Minimum generated value. Default is 0 - - - - - Gets or sets the maximum generated value - - - Maximum generated value. Default is 0 - - - - - A random generator of instances. - - - - - Initializes a new instance of . - - - - - - Generates a new value - - - New random data. - - - - - Gets or sets the string containing the generated characters - - - - - - A graph of (vertices) and - (edges). - - - - - Builds a new empty directed graph with default vertex and edge - provider. - - - - - - - Remove all of the edges and vertices from the graph. - - - - - Add a new DataTableVertex to the graph and returns it. - - - Created vertex - - - - - Removes the vertex from the graph. - - vertex to remove - v is null - - - - Add a new vertex from source to target - - Complexity: 2 search + 1 insertion - - Source vertex - Target vertex - Created Edge - - source or target is a null reference - - source or target are not part of the graph - - - - Remove all edges to and from vertex u from the graph. - - - - - - Removes an edge from the graph. - - Complexity: 2 edges removed from the vertex edge list + 1 edge - removed from the edge list. - - edge to remove - - e is a null reference (Nothing in Visual Basic) - - - is not part of the graph - - - - - Remove the edge (u,v) from the graph. - If the graph allows parallel edges this remove all occurrences of - (u,v). - - source vertex - target vertex - - - - Add a new vertex to the graph and returns it. - - Create vertex - - - - Used for serialization. Not for private use. - - edge to add. - - - - Gets a value indicating if the set of out-edges is empty - - - - Usually faster that calling . - - - - true if the out-edge set is empty, false otherwise. - - - v is a null reference (Nothing in Visual Basic) - - - v is not part of the graph. - - - - - Returns the number of out-degree edges of v - - vertex - number of out-edges of the v - - v is a null reference (Nothing in Visual Basic) - - - v is not part of the graph. - - - - - Returns an iterable collection over the edge connected to v - - - out-edges of v - - v is a null reference. - - - v is not part of the graph. - - - - - Test is an edge (u,v) is part of the graph - - source vertex - target vertex - true if part of the graph - - - - Returns the first out-edge that matches the predicate - - - Edge predicate - null if not found, otherwize the first Edge that - matches the predicate. - v or ep is null - - - - Returns the collection of out-edges that matches the predicate - - - Edge predicate - enumerable colleciton of vertices that matches the - criteron - v or ep is null - - - - Remove all the edges from graph g for which the predicate pred - returns true. - - edge predicate - - - - Remove all the out-edges of vertex u for which the predicate pred - returns true. - - vertex - edge predicate - - - - Tests if a is part of the graph - - Vertex to test - true if is part of the graph, false otherwize - - - - Returns the first that matches the predicate - - vertex predicate - null if not found, otherwize the first vertex that - matches the predicate. - vp is null - - - - Returns the collection of vertices that matches the predicate - - vertex predicate - enumerable colleciton of vertices that matches the - criteron - vp is null - - - - Tests if a () is part of the graph - - Edge to test - true if is part of the graph, false otherwize - - - - Returns the first Edge that matches the predicate - - Edge predicate - null if not found, otherwize the first Edge that - matches the predicate. - ep is null - - - - Returns the collection of edges that matches the predicate - - Edge predicate - enumerable colleciton of vertices that matches the - criteron - ep is null - - - - Gets an enumerable collection of adjacent vertices - - - Enumerable collection of adjacent vertices - - - - Gets a value indicating if the set of in-edges is empty - - - - Usually faster that calling . - - - - true if the in-edge set is empty, false otherwise. - - - v is a null reference (Nothing in Visual Basic) - - - is not part of the graph. - - - - - Returns the number of in-degree edges of v - - - number of in-edges of the vertex v - - v is a null reference (Nothing in Visual Basic) - - - is not part of the graph. - - - - - Returns an iterable collection over the in-edge connected to v - - - in-edges of v - - v is a null reference (Nothing in Visual Basic) - - - is not part of the graph. - - - - - Incidence graph implementation - - - - - Gets a value indicating if the set of edges connected to v is empty - - - - Usually faster that calling . - - - - true if the adjacent edge set is empty, false otherwise. - - v is a null reference - - - - Returns the number of in-edges plus out-edges. - - - - - - - Returns the first in-edge that matches the predicate - - - Edge predicate - null if not found, otherwize the first Edge that - matches the predicate. - v or ep is null - - - - Returns the collection of in-edges that matches the predicate - - - Edge predicate - enumerable colleciton of vertices that matches the - criteron - v or ep is null - - - - - - - - - - - - Remove all the out-edges of vertex u for which the predicate pred - returns true. - - vertex - edge predicate - - - - Gets a value indicating if the - is directed. - - - true if the graph is directed, false if undirected. - - - - - Gets a value indicating if the allows parallel edges. - - - true if the is a multi-graph, false otherwise - - - - - Gets the provider - - - provider - - - - - Gets the provider - - - provider - - - - - Gets a value indicating if the vertex set is empty - - - Usually faster (O(1)) that calling VertexCount. - - - true if the vertex set is empty, false otherwise. - - - - - Gets the number of vertices - - - Number of vertices in the graph - - - - - Enumerable collection of vertices. - - - - - Gets a value indicating if the vertex set is empty - - - - Usually faster that calling . - - - - true if the vertex set is empty, false otherwise. - - - - - Gets the edge count - - - Edges count - - - - - Enumerable collection of edges. - - - - - Initializes a new empty instance of the - class. - - - - - Adds an instance of type to the end of this - . - - - The Edge to be added to the end of this EdgeCollection. - - - - - Removes the first occurrence of a specific Edge from this EdgeCollection. - - - The Edge value to remove from this EdgeCollection. - - - - - Determines whether a specfic value is in this EdgeCollection. - - - edge value to locate in this . - - - true if value is found in this collection; - false otherwise. - - - - - Returns an enumerator that can iterate through the elements of this EdgeCollection. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the Edge at the given index in this EdgeCollection. - - - - - Create a new enumerator on the collection - - collection to enumerate - - - - Moves cursor to next element. - - true if current is valid, false otherwize - - - - Resets the cursor to the position before the first element. - - - - - The current element. - - - - - A populator of instance. - - - - - A with a instance. - - - - - A validator check checks constraints - - - - - Preprocesses the row modifies it to fullfill the constraint - - - - - - A database populator instance. - - - - - - Sets up the generators for the given - instance. - - - A representing the structure of the - database to populate. - - - is a null reference (Nothing in - Visual Basic) - - - - - Gets the instance associated - to this populator. - - - A schema used to set-up the generators. - - - - - Gets a collection associated - to each table. - - - A containing - populator associated to each . - - - - - Gets the associated to the - database. - - - - - - An instance that can fill a with - data that are compatible with a - given . - - - - - - Fill the row with data that is compatible with - the foreign key. - - - instance to fill. - - - is a null reference (Nothing - in Visual Basic). - - - - - Gets the table populator associated to the foreign table. - - - The instance - associated to the foreign - table. - - - - - Gets the foreign constraint that needs to be satisfied. - - - The associated to this - provider. - - - - - Gets a value indicating that the foreign table is empty and - cannot provide keys. - - - true if the foreign table is empty; otherwise false. - - - - - An random generator compatible with the schema - of a given . - - - -This example shows how the data generator can be used to create unit tests on database. In this example, -we setup the dummy UserOrderProductDatabase and -the populator in the SetUp method. - - -using System; -using System.Data; -using MbUnit.Core.Framework; -using MbUnit.Framework; -using TestFu.Data; -using TestFu.Data.Populators; - -namespace TestFu.Tests.Data -{ - [TestFixture] - public class DatabasePopulatorTest - { - private UserOrderProductDatabase db; - private DatabasePopulator pop; - private ITablePopulator users; - private ITablePopulator orders; - private ITablePopulator products; - private ITablePopulator orderProducts; - - [SetUp] - public void SetUp() - { - this.db=new UserOrderProductDatabase(); - this.pop = new DatabasePopulator(); - this.pop.Populate(this.db.DataSet); - - this.users=this.pop.Tables[this.db.Users]; - this.orders=this.pop.Tables[this.db.Orders]; - this.products=this.pop.Tables[this.db.Products]; - this.orderProducts=this.pop.Tables[this.db.OrderProducts]; - } - - [Test] - public void AddOneUser() - { - DataRow row = users.Generate(); - this.db.Users.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrder() - { - this.AddOneUser(); - DataRow row = orders.Generate(); - this.db.Orders.Rows.Add(row); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrder() - { - DataRow row = orders.Generate(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrderProduct() - { - DataRow row = orderProducts.Generate(); - } - - [Test] - public void AddOneUserOneOrderOneProduct() - { - this.AddOneUserOneOrder(); - - DataRow row = products.Generate(); - this.db.Products.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrderOneProductOneProductOrder() - { - this.AddOneUserOneOrderOneProduct(); - DataRow row=orderProducts.Generate(); - this.db.OrderProducts.Rows.Add(row); - } - - [Test] - public void AddTwoUsers() - { - AddOneUser(); - AddOneUser(); - } - - [TearDown] - public void Check() - { - this.db.AcceptChanges(); - Console.WriteLine(db.ToString()); - } - } -} - - - - - - Generates a new . - - - Generated instance. - - - - - Updates randomly a number of rows - - - - - - Updates randomly a number of rows - - - - - - Gets an instance of the $ - that contains this populator. - - - Parent instance. - - - - - Gets the instance that is the model - to be populated. - - - A instance whos schema is used to create - new . - - - - - Gets a collection of - associated to each . - - - A instance - containing the validators associated to each unique constraint. - - - - - Gets a collection of - associated to each . - - - A instance - containing the providers associated to each foreign key. - - - - - Gets a collection of associated - to each column of the table. - - - A instance - containing the generators associated to each column. - - - - - Gets the that ensures CHECK constraints. - - - A instance if any check constraint to verify; - otherwize a null reference. - - - - - Gets the latest generated . - - - Latest generated . - - - - - A validator for constraints. - - - - - - - The TestFu.Data namespace contains a - Random generator - to help developer test databases, data layers, business layers, - etc... - - - - -This example shows some usage of the class. This class can be used to easily backup, restore, create or drop -databases on a server. is the implementation for the MSSQL server: -[C#] -using System; -using TestFu.Data; - -public class Demo -{ - public static void Main(string[] args) - { - DbAdministrator admin = new SqlAdministrator("..."); - - // backup Northwind - admin.Backup("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); - - // drop Northwind - admin.Drop("Northwind"); - - // restore Northwind - admin.Restore("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); - } -} - - - -The DbFixture (SqlFixture for MsSQL server) can be used as a base class for the -fixtures involving database testing. - -[TestFixture] -public class DatabaseTest : SqlFixture -{ - public DatabaseTest() - :base("Data Source=testserver;...","MyTestDatabase") - {} - - [SetUp] - public void SetUp() - { - this.Open(); - this.BeginTransaction(); - } - - [Test] - public void Selec() - { - IDbCollection cmd = this.Connection.CreateCommand("select * from anytable",this.Transaction); - ... - } - - [TearDown] - public void TearDown() - { - this.Close(); - } -} - - -This example shows how the data generator can be used to create unit tests on database. In this example, -we setup the dummy UserOrderProductDatabase and -the populator in the SetUp method. - - -using System; -using System.Data; -using MbUnit.Core.Framework; -using MbUnit.Framework; -using TestFu.Data; -using TestFu.Data.Populators; - -namespace TestFu.Tests.Data -{ - [TestFixture] - public class DatabasePopulatorTest - { - private UserOrderProductDatabase db; - private DatabasePopulator pop; - private ITablePopulator users; - private ITablePopulator orders; - private ITablePopulator products; - private ITablePopulator orderProducts; - - [SetUp] - public void SetUp() - { - this.db=new UserOrderProductDatabase(); - this.pop = new DatabasePopulator(); - this.pop.Populate(this.db.DataSet); - - this.users=this.pop.Tables[this.db.Users]; - this.orders=this.pop.Tables[this.db.Orders]; - this.products=this.pop.Tables[this.db.Products]; - this.orderProducts=this.pop.Tables[this.db.OrderProducts]; - } - - [Test] - public void AddOneUser() - { - DataRow row = users.Generate(); - this.db.Users.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrder() - { - this.AddOneUser(); - DataRow row = orders.Generate(); - this.db.Orders.Rows.Add(row); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrder() - { - DataRow row = orders.Generate(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrderProduct() - { - DataRow row = orderProducts.Generate(); - } - - [Test] - public void AddOneUserOneOrderOneProduct() - { - this.AddOneUserOneOrder(); - - DataRow row = products.Generate(); - this.db.Products.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrderOneProductOneProductOrder() - { - this.AddOneUserOneOrderOneProduct(); - DataRow row=orderProducts.Generate(); - this.db.OrderProducts.Rows.Add(row); - } - - [Test] - public void AddTwoUsers() - { - AddOneUser(); - AddOneUser(); - } - - [TearDown] - public void Check() - { - this.db.AcceptChanges(); - Console.WriteLine(db.ToString()); - } - } -} - - -The following codes decribes a simple User - Order - Product database contains 4 tables: -Users, Orders, Products and OrderProducts. - - -using System; -using System.Data; -using System.IO; -using System.Xml; - -namespace TestFu.Tests.Data -{ - public class UserOrderProductDatabase - { - private DataSet dataSet; - private DataTable users; - private DataColumn userID; - private DataColumn userName; - - private DataTable orders; - private DataColumn orderID; - private DataColumn orderDate; - private DataColumn oUserID; - - private DataTable products; - private DataColumn productID; - private DataColumn productName; - private DataColumn productPrice; - - private DataTable orderProducts; - private DataColumn opOrderID; - private DataColumn opProductID; - private DataColumn quantity; - - public UserOrderProductDatabase() - { - this.dataSet=new DataSet(); - - this.users=this.dataSet.Tables.Add("Users"); - this.userID = this.users.Columns.Add("UserID",typeof(int)); - this.userName=this.Users.Columns.Add("UserName",typeof(string)); - this.userName.AllowDBNull=false; - - this.orders=this.dataSet.Tables.Add("Orders"); - this.orderID=this.orders.Columns.Add("OrderID",typeof(int)); - this.orderDate = this.orders.Columns.Add("OrderDate",typeof(DateTime)); - this.oUserID = this.orders.Columns.Add("UserID",typeof(int)); - - this.products=this.dataSet.Tables.Add("Products"); - this.productID=this.products.Columns.Add("ProductID",typeof(int)); - this.productName = this.products.Columns.Add("ProductName",typeof(string)); - this.productPrice = this.products.Columns.Add("ProductPrice",typeof(decimal)); - - this.orderProducts=this.dataSet.Tables.Add("OrderProducts"); - this.opOrderID=this.orderProducts.Columns.Add("OrderID",typeof(int)); - this.opProductID=this.orderProducts.Columns.Add("ProductID",typeof(int)); - this.quantity=this.orderProducts.Columns.Add("Quantity",typeof(int)); - - // pks - users.Constraints.Add("PK_Users",userID,true); - orders.Constraints.Add("PK_Orders",orderID,true); - products.Constraints.Add("PK_Products",productID,true); - orderProducts.Constraints.Add("PK_OrderProducts", - new DataColumn[]{ opOrderID, opProductID} - ,true); - - // fks - orders.Constraints.Add("FK_Orders_Users",userID,oUserID); - orderProducts.Constraints.Add("FK_OrderProducts_Orders",orderID,opOrderID); - orderProducts.Constraints.Add("FK_OrderProducts_Products",productID,opProductID); - } - } -} - - - - - - Default implementation. - - - -This example shows how the data generator can be used to create unit tests on database. In this example, -we setup the dummy UserOrderProductDatabase and -the populator in the SetUp method. - - -using System; -using System.Data; -using MbUnit.Core.Framework; -using MbUnit.Framework; -using TestFu.Data; -using TestFu.Data.Populators; - -namespace TestFu.Tests.Data -{ - [TestFixture] - public class DatabasePopulatorTest - { - private UserOrderProductDatabase db; - private DatabasePopulator pop; - private ITablePopulator users; - private ITablePopulator orders; - private ITablePopulator products; - private ITablePopulator orderProducts; - - [SetUp] - public void SetUp() - { - this.db=new UserOrderProductDatabase(); - this.pop = new DatabasePopulator(); - this.pop.Populate(this.db.DataSet); - - this.users=this.pop.Tables[this.db.Users]; - this.orders=this.pop.Tables[this.db.Orders]; - this.products=this.pop.Tables[this.db.Products]; - this.orderProducts=this.pop.Tables[this.db.OrderProducts]; - } - - [Test] - public void AddOneUser() - { - DataRow row = users.Generate(); - this.db.Users.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrder() - { - this.AddOneUser(); - DataRow row = orders.Generate(); - this.db.Orders.Rows.Add(row); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrder() - { - DataRow row = orders.Generate(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrderProduct() - { - DataRow row = orderProducts.Generate(); - } - - [Test] - public void AddOneUserOneOrderOneProduct() - { - this.AddOneUserOneOrder(); - - DataRow row = products.Generate(); - this.db.Products.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrderOneProductOneProductOrder() - { - this.AddOneUserOneOrderOneProduct(); - DataRow row=orderProducts.Generate(); - this.db.OrderProducts.Rows.Add(row); - } - - [Test] - public void AddTwoUsers() - { - AddOneUser(); - AddOneUser(); - } - - [TearDown] - public void Check() - { - this.db.AcceptChanges(); - Console.WriteLine(db.ToString()); - } - } -} - - - - - - Initiliazes a instance. - - - - - A querying the databse. - - - - - - Base class for implementation. - - - - - - A based on a . - - - - - - Default implementation of - - - - - - Default implementation of - - - - - - An smart random generator. - - - -This example shows how the data generator can be used to create unit tests on database. In this example, -we setup the dummy UserOrderProductDatabase and -the populator in the SetUp method. - - -using System; -using System.Data; -using MbUnit.Core.Framework; -using MbUnit.Framework; -using TestFu.Data; -using TestFu.Data.Populators; - -namespace TestFu.Tests.Data -{ - [TestFixture] - public class DatabasePopulatorTest - { - private UserOrderProductDatabase db; - private DatabasePopulator pop; - private ITablePopulator users; - private ITablePopulator orders; - private ITablePopulator products; - private ITablePopulator orderProducts; - - [SetUp] - public void SetUp() - { - this.db=new UserOrderProductDatabase(); - this.pop = new DatabasePopulator(); - this.pop.Populate(this.db.DataSet); - - this.users=this.pop.Tables[this.db.Users]; - this.orders=this.pop.Tables[this.db.Orders]; - this.products=this.pop.Tables[this.db.Products]; - this.orderProducts=this.pop.Tables[this.db.OrderProducts]; - } - - [Test] - public void AddOneUser() - { - DataRow row = users.Generate(); - this.db.Users.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrder() - { - this.AddOneUser(); - DataRow row = orders.Generate(); - this.db.Orders.Rows.Add(row); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrder() - { - DataRow row = orders.Generate(); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void AddOneOrderProduct() - { - DataRow row = orderProducts.Generate(); - } - - [Test] - public void AddOneUserOneOrderOneProduct() - { - this.AddOneUserOneOrder(); - - DataRow row = products.Generate(); - this.db.Products.Rows.Add(row); - } - - [Test] - public void AddOneUserOneOrderOneProductOneProductOrder() - { - this.AddOneUserOneOrderOneProduct(); - DataRow row=orderProducts.Generate(); - this.db.OrderProducts.Rows.Add(row); - } - - [Test] - public void AddTwoUsers() - { - AddOneUser(); - AddOneUser(); - } - - [TearDown] - public void Check() - { - this.db.AcceptChanges(); - Console.WriteLine(db.ToString()); - } - } -} - - - - - - Helper class to performe task on a SQL server. - - - -This example shows some usage of the class. This class can be used to easily backup, restore, create or drop -databases on a server. is the implementation for the MSSQL server: -[C#] -using System; -using TestFu.Data; - -public class Demo -{ - public static void Main(string[] args) - { - DbAdministrator admin = new SqlAdministrator("..."); - - // backup Northwind - admin.Backup("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); - - // drop Northwind - admin.Drop("Northwind"); - - // restore Northwind - admin.Restore("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); - } -} - - - - - - - Initializes an instance of with the connection string. - - - Connection string to the SQL server without initial catalog - - - Catalog name - - - is a null reference (Nothing in Visual Basic) - - - - - Creates a backup of the specified database using the specified - and . - - - A defining the type of output device. - - - Device path. - - - is a null - reference (Nothing in Visual Basic) - - - - - Restores a backup of the specified database using the specified - and . - - - A defining the type of output device. - - - Device path. - - - is a null - reference (Nothing in Visual Basic) - - - - If you plan to override an existing database, you must first drop this database. - This method takes a conservative behavior and will not override an existing database. - - - Priorly to restore the database, the method kills all the processes associeted - to the database. - - - - - - Creates a new database on the server - - - - - Drops an existing new database on the server - - - is a null - reference (Nothing in Visual Basic) - - - - - Gets the connection string with Initial Catalog information. - - - Connection string with Initial catalog information. - - - - - A implementation for MSSQL server. - - - - - - Creates a instance. - - - - - - - - Creates a instance. - - - Connection string to server - - - A instance. - - - - - Abstract base class for MSSQL server database testing. - - -The DbFixture (SqlFixture for MsSQL server) can be used as a base class for the -fixtures involving database testing. - -[TestFixture] -public class DatabaseTest : SqlFixture -{ - public DatabaseTest() - :base("Data Source=testserver;...","MyTestDatabase") - {} - - [SetUp] - public void SetUp() - { - this.Open(); - this.BeginTransaction(); - } - - [Test] - public void Selec() - { - IDbCollection cmd = this.Connection.CreateCommand("select * from anytable",this.Transaction); - ... - } - - [TearDown] - public void TearDown() - { - this.Close(); - } -} - - - - - Initializes a with a connection string. - - - Connection string for accessing the test database. - - - database name - - - is a null reference - (Nothing in Visual Basic) - - - - - Gets the current connection instance. - - - instance. - - - - - Gets the current transaction. - - - A instance if was called - and the connection not closed; otherwise, a null reference (Nothing in Visual Basic) - - - - - Provides functions to capture the entire screen, or a particular window, and save it to a file. - - - - Source code takened from - http://www.developerfusion.com/show/4630/ - - - - - - Creates an Image object containing a screen shot of the entire desktop - - - - - - Creates an Image object containing a screen shot of the entire desktop - - - - - - Creates an Image object containing a screen shot of the - - - - - Creates an Image object containing a screen shot of a specific window - - The handle to the window. (In windows forms, this is obtained by the Handle property) - - - - - Helper class containing Gdi32 API functions - - - - - Helper class containing User32 API functions - - - - - A that simulates a MouseDown event. - - - - - Abstract base class for - instance. - - - - - Abstract base class for - implementation. - - - - - A user gesture. - - - - User gesture can be a combination of keyboard or mouse - interactions. - - - - - - Executes the gesture - - - - This method should be executed on separate thread - from the main thread, otherwize event will not be - fired correctly. - - - - - - Gets the CodeDom statement creating this gesture - - - - - - Gets the that is targeted - by the gesture - - - - - - Initializes an empty . - - - - - Initializes a new - instance with a form - - - - - - Raises the event. - - - - - - Converts the target from client to - screen coordinates - - - Position in client coordinates - - Position converted into screen coordinates - - - - This method makes a thread safe invokation of the - Form.PointToScreen method. - - - - - - Converts the target from screen to - client coordinates - - - Position in screen coordinates - - Position converted into client coordinates - - - - This method makes a thread safe invokation of the - Form.PointToClient method. - - - - - - Executes the gesture. - - - - - Gets or sets the instance targeted - by the - - - A instance - - - - - Raised when the target is changed - - - - - A mouse gesture. - - - - - Gets or sets a value indicating the - involved in the gesture. - - - A combined value of flags. - - - - - Initializes an new . - - - - - Initializes a new - with a instance and the buttons - involved in the gesture. - - - Target instance - - value representing the - involved in the gesture - - - - - Gets or sets a value indicating the - involved in the gesture. - - - A combined value of flags. - - - - - Initializes a new - - - - - Initializes a new with - a target instance and the left button - - - Target form - - - - Initializes a new with - a target instance and the buttons - - - Target form - - value representing the - involved in the gesture - - - - - Executes the mouse down event - - - - - A that simulates a MouseUp event - - - - - Initialiazes a new . - - - - - Initialiazes a new with - a target . - - - Target form - - - - - Initialiazes a new with - a target . - - - Target form - - - value representing the - involved in the gesture - - - - - Executes the mouse up event - - - - - A that simulates a button click - - - - - Initializes a new - - - - - Initializes a new - with a instance and the left button - - - Target instance - - - - - Initializes a new - with a instance - - - Target instance - - - value representing the - involved in the gesture - - - - - Executes the mouse click - - - - - A that moves the cursor to the - center of a . - - - - - An abstract base class for - implementations - that simulates a mouse movement - - - - - Initializes a new - - - - - Initialiazes a new - with a target form and no buttons - - - Target - - - - - Initialiazes a new - with a target form and the buttons - - - Target - - - value representing the - involved in the gesture - - - - - Steers the mouse towards the target - - - - - Gets the target of the movement, in client coordinates - - - A in client coordinates - - - - - Gets or sets a value indicating the maximum velocity of the - cursor - - - A representing the maximum velocity of the cursor - - - - - Initializes a new - - - - - Initializes a new - with a target and a target - - - - Target form - - Target control - - - - - Initializes a new - with a target , a target - and the buttons pushed during the move - - - Target form - - Target control - - - value representing the - involved in the gesture - - - - - Gets or sets the target - - - A instance where the cursor has to move - - - - - Gets the center of the target . - - - A representing the center of the - target control in client coordiantes - - - - - Offset of the target on the - - - - - - A that steers the cursor to a target - - - - - Initializes a new - - - - - Initializes a new - with a target and a target - - - Target form - - Target in client coordinates - - - - - Initializes a new - with a target and a target - - - Target form - - Target in client coordinates - - - value representing the - involved in the gesture - - - - - Gets the target of the movement, in client coordinates. - - - A in client coordinates - - - - The property value is equal to . - - - - - - Gets or sets the target of the movement, in client coordinates - - - A in client coordinates - - - - - A implementation. - - - - - A mutable collection of - - - - - Adds a instance - to the collection - - - A instance to add to the - collection - - - - - Gets or sets the - at position - - - index of the gesture - - get property, the - at position - - - - - A helper factory of instance. - - - - - Initializes a new - with a instance - - - Target form - - - - Creates a for the - method and starts it. - - - The to execute - - - The started instance - - - - - Creates a instance - with a variable list of instances. - - - gestures to execute in sequence. - - - A instance - - - - Creates a that makes the - thread sleep a given number of milliseconds - - - Duration in milliseconds of the sleep - - - A instance - - - - - Creates a new with - the gesture and the repeat count - - - Target instance - - - Number of repetition - - - A instance - - - - - Creates a - that simulates a left click of the mouse - - - A instance - - - - - Creates a - that simulates a left click of the mouse - - - A instance - - - Control to click - - - - - Creates a - that simulates a left click of the mouse - - - A instance - - - Control to click - - - - - Creates a - that simulates a left click of the mouse - - - value representing the - involved in the gesture - - - A instance - - - - - Creates a new instance - that simulates a Mouse down event (left click) - - - A instance - - - - - Creates a new instance - that simulates a Mouse down event with the buttons - - - value representing the - involved in the gesture - - - A instance - - - - - Creates a new instance - that simulates a Mouse up event (left click) - - - A instance - - - - - Creates a new instance - that simulates a Mouse up event with the buttons - - - value representing the - involved in the gesture - - - A instance - - - - - Creates a - that simulates the movement of the mouse to the target - - - Target client coordinate - - - A instance - - - - - Creates a - that simulates the movement of the mouse to the target - and the buttons down - - - Target client coordinate - - - value representing the - involved in the gesture - - - A instance - - - - - Creates a - that simulates the movement of the mouse to the center - of the - - - Target instance - - - A instance - - - - - Creates a - that simulates the movement of the mouse to the center - of the with the buttons down - - - Target instance - - - value representing the - involved in the gesture - - - A instance - - - - - Creates a instance that simulates - a drag and drop between - and - - - Source client coordinate - - Target client coordinate - - - A instance that simulates the drag and drop - - - - - Creates a instance that simulates - a drag and drop between - and - - - Source client coordinate - - Target - - - A instance that simulates the drag and drop - - - - - Creates a instance that simulates - a drag and drop between - and - - - Source - - - Target client coordinate - - - A instance that simulates the drag and drop - - - - - Creates a instance that simulates - a drag and drop between - and - - - Source - - - Target - - - A instance that simulates the drag and drop - - - - - Creates a instance that simulates - a drag and drop between - and - - - Source - - - Target client coordinate - - - A instance that simulates the drag and drop - - - - - Gets the target instance - - - A instance that is targetted by the gestures - - - - - - The TestFu.Gestures namespace contains classes ( - instances) to simulate user mouse and keyboard interactions. - - - The user interaction are simulated by using native methods - mouse_event and keybd_event. - - - The can be used to rapidly generate - instances. - - - The gestures should not be executed in the main thread but in a worker thread. Otherwize, - you will miss message notifications. All gesture methods on - and are thread safe. - - - - - - A that executes a Repeat of - instances. - - - - - Initializes a new instance - - - - - Initialiazes a new instance - with a instance. - - - Target - - - The gesture to be repeated - - - The number of repetition - - - - Executes the contained in - in Repeat. - - - - - Gets the collection of to execute in Repeat - - - A instance - - - - - Gets or sets the number of gesture repetition - - - The repetition count - - - - - A that executes a sequence of - instances. - - - - - Initializes a new instance - - - - - Initialiazes a new instance - with a instance. - - - Target - - - - - Executes the contained in - in sequence. - - - - - Gets the collection of to execute in sequence - - - A instance - - - - - A that makes the - sleep. - - - - - Initialiazes a new instance. - - - - - Initialiazes a new instance - with a instance and a sleep duration - - - Target instance - - Sleep duration in milliseconds - - - - - Executes the sleep gestures - - - - - Gets or sets the sleep duration (in milliseconds) - - - Number of milliseconds of sleep - - - - - A static helper for artificially generationg mouse - and keyboard input. - - - - This class uses mouse_event and keybd_event native - methods (through interop) to simulate user mouse or keyboard input. - - - - - - Generates a mouse event - - - Combined flag describing the mouse event - - - - - Mouse event with additional data - - - Combined flag describing the mouse event - - - Relative horizontal movement of the cursor - - - Relative vertical movement of the cursor - - Additional data - - - - - Move mouse of units - - - horizontal movement - - vertical movement - - - - - Notfies that a mouse movement is starting - with the buttons settings - - - Combined flag describing the current button - state - - - - - Notfies that a mouse movement is finishing - with the buttons settings - - - Combined flag describing the current button - state - - - - - Mouse click using button state - - - Combined flag describing the current button - state - - - - - Mouse down event - - - - - - Mouse up event - - - - - - Mouse wheel event - - - Wheel movement - - - - Simulates a Key action (KeyDown, Key, KeyUp message sequence) - - character pressed - handle of control to receive the event - - - - Simulates a Backspace - - handle of control to receive the event - - - - Simulates a user typing text - - text to enter - handle of control to receive the event - - - - Mouse even type enumeration - - - - - No event - - - - - Mouse move where dx,dy are in absolute coordinate - - - - - Left button bown - - - - - Left button up - - - - - Middle button down - - - - - middle button up - - - - - Mouse moved - - - - - Right button down - - - - - Right button up - - - - - Mouse wheel movement - - - - - Additional button down - - - - - Additional button up - - - - - A that choose from a set of sub-. - - - - - Abstract rule containing other rules. - - - - - Abstract rule class - - - - - A production rule - - - - A instance is used to execute a production. - - - - - - Executes the production using the rule. - - - A production token authorizing production. - - - is a null reference (Nothing in Visual Basic) - - - - - Gets or sets a value indicating the rule importance - - - Value indicating the rule importance - - - set property, value is negative. - - - - - Semantic actions event. - - - - Semantic action are triggered upon each successful rule execution. - - - - - - Gets a value indicating if the rule is terminal - - - true if the rule is terminal; otherwise, false. - - - - - Gets or sets the rule name (for debugging purpose) - - - The rule name. - - - - - Creates an empty rule - - - true if the rule is terminal; otherwise, false. - - - - - Raises the event. - - - - - Executes the production using the rule (abstract class). - - - A production token authorizing production. - - - is a null reference (Nothing in Visual Basic) - - - - - Gets a value indicating if the rule is terminal - - - true if the rule is terminal; otherwise, false. - - - - - Gets or sets the rule name - - - The rule name - - - - - Gets or sets the rule weight - - - The rule weight - - - set property, weight is negative - - - - - Semantic action event. - - - - - Creates an empty instance. - - - - - Gets the list of rules stored in the rule. - - - containing the child rules. - - - - - Choose a and launch its production. - - - Authorizing token - - - - - Gets or sets the instance - - - instance. - - - - - If then else rule fashion. - - - - This rule uses the results of a - instance to select which to execute: - - if (predicate.Test(...)) - rule.Produce(...); - else - elseRule.Produce(...); - - - - - - - Creates a with a - instance and - instance. - - - instance used for testing - - - rule to execute. - - - or - is a null reference. - - - - - Creates a with a - instance and - instance. If the predicate returns - false, is executed. - - - instance used for testing - - - rule to execute. - - - rule to execute if predicate is false. - - - or - is a null reference. - - - - - Executes one of the rules depending on the predicate result. - - - A production token authorizing production. - - - is a null reference (Nothing in Visual Basic) - - - - - Gets or sets the predicate for the condition. - - - instance used for testing the condition. - - - set property, value is a null reference - - - - - Gets or sets the rule executed when the predicate is true - - - instance executed when - is true. - - - set property, value is a null reference - - - - - Gets or sets the rule executed when the predicate is false - - - instance executed when - is false. - - - - - Method that returns a bool. - - - Current instance. - - - - - A instance that executes - a . - - - - - Predicate that checks a given condition. - - - - - Checks a condition and returns result. - - - Predicate result - - - Current production token - - - - - Creates a new instance arounda - - - to attach. - - - is a null reference. - - - - - Invokes the instance - and returns the result. - - - - - - - A class that limits the number of - terminal execution. - - - - - A production done by a grammar and its set of rules. - - - - - Processes the request for a - done by a rule and returns the token or throws. - - - instance that requests the token. - - - A valid instance. - - - The request was defined using the internal production - logic. - - - - - Gets the seed that created the production - - - Seed used to create the production - - - - - Creates an instance that limits the number of terminal rule execution - to . - - - Maximum number of terminal execution. - - - - - Processes the request for a - done by a rule and returns the token or throws. - - - instance that requests the token. - - - A valid instance. - - - The maximum number of terminal rule execution was hitted. - - - - - Factory for instance. - - - - - A factory for instances. - - - - - Creates a new instance. - - - A valid instance. - - - - - Creates a factory of . - - - - - Creates new instances of - - - A instance - - - - - A that wraps a - call. - - - - - Creates an instance with a - attached. - - - Handler to attach - - - is a null reference - - - - - Invokes handler. - - - - - - A grammar containing a set of rules, a . - - - - - A grammar containing a set of rules, a . - - - - - Launches a production. - - - - - Gets or sets the starting rule. - - - The start . - - - - - Raised when production is finished. - - - - - Creates an empty grammar. - - - - - Launches a production. - - - - - - - - - Gets or sets the instance. - - - instance used for creating new - productions. - - - - - Gets or sets the starting rule. - - - The start . - - - - - A that guard an inner instance - execution from a specific exceptionType. - - - - - Creates an instance with the guarded rule and the expected - exception type. - - - Guarded instance - - - Expected type. - - - or - is a null reference. - - - - - Creates an instance with the guarded rule, the expected - exception type and the regular expression to match the message. - - - Guarded instance - - - Expected type. - - - Regular expression used to match the exception message - - - or - is a null reference. - - - - - Raises the event. - - - - - Executes the inner and guards for - a particular exception type. - - - Authorization token - - - - - Semantic actions event - - - - - Gets or sets the regular expression to match the message. - - - The instance used to mach the message. - - - - If this property is set to null, no message matching is performed. - - - - - - Gets or sets the rule name (for debugging purpose) - - - The rule name. - - - - - Gets or sets a value indicating the rule importance - - - Value indicating the rule importance - - - - - Gets a value indicating if the rule is terminal. - - - Always returns true. - - - - - An authorization to execute a production. - - - - - Gets a value indicating if the production is authorized - - - true if authorized, otherwise false. - - - - - Gets the that emited the token. - - - The instance that emited the token. - - - - - A class that creates random values. - - - - - Returns a nonnegative random number. - - - A 32-bit signed integer greater than or equal to zero and less than - . - - - - - Returns a nonnegative random number less than the specified maximum. - - - - A 32-bit signed integer greater than or equal to zero and less than - . - - - - - Returns a random number within a specified range. - - - The lower bound of the random number returned. - - - The upper bound of the random number returned. - maxValue must be greater than or equal to minValue. - - - A 32-bit signed integer greater than or equal to minValue and less - than maxValue; that is, the range of return values includes - minValue but not MaxValue. If minValue equals maxValue, minValue - is returned. - - - - - Returns a random number between 0.0 and 1.0. - - - A double-precision floating point number greater than or equal - to 0.0, and less than 1.0. - - - - - A collection of . - - - - - Gets an instance of the rules. - - - A valid instance. - - - - - An enumerator over instance. - - - - - Gets the current instance - - - Current instance. - - - - - A list of - - - - - Adds a to the list. - - - to add - - - - - Inserts a instance at position - - - position to insert the rule - - - to insert - - - - - Removes the first occurence of . - - - to remove - - - - - Gets a value indicating if is in the - list. - - - to test. - - - true if is in the list; otherwise, false. - - - - - Clears the list. - - - - - Gets or sets the at position . - - - index. - - - - - A object that select a rule between a collection of rules. - - - - - Select a from - - - array to select from - - - Select instance - - - is a null reference - - - is empty - - - - - Select a from - - - collection to select from - - - Select instance - - - is a null reference - - - is empty - - - - - A rule that executes a . - - - - - Creates a new instance around a - - - to attach. - - - is a null reference. - - - - - Invokes the instance. - - - Autorization token - - - - - The TestFu.Grammars namespace contains a framwork for - implementing - Production Grammars. - - - - - - Exception throwed when an exception is catched and is - not from the expected type. - - - - - Creates an instance with the expected exception type - and the actual exception. - - - Expected exception - - - Actual catch instance - - - - - Exception throwed when an exception message does not match - with the message regular expression - - - - - Creates an instance with the message regular expression and - the actual catched exception. - - - The instance used to match the message - - - The actual instance. - - - - - Gets the instance used to match the exception message - - - message matcher. - - - - - A static helper class for creating . - - - - - Creates a around - - - - condition to wrap - - A - - - - - Expection class used to stop production. - - - - - - - - - - - Gets the production that stopped. - - - - - Default implementation of - - - - - Creates a token from - - - production to wrap. - - - is a null reference (Nothing in - Visual Basic). - - - - - Gets the that emited the token. - - - The instance that emited the token. - - - - - Gets a value indicating if the production is authorized - - - true if authorized, otherwise false. - - - - - A rule that executes a . - - - - - Creates a new instance around a - - - to attach. - - - is a null reference. - - - - - Invokes the instance. - - - Autorization token - - - - - Summary description for ProductionTokenEventArgs. - - - - - System implementation of - - - - - Creates an instance initialized using .Now.Ticks. - - - - - Uniform random rule selector. - - - - - Select a from - - - array to select from - - - Select instance - - - is a null reference - - - is empty - - - - - Select a from - - - collection to select from - - - Select instance - - - is a null reference - - - is empty - - - - - Gets or sets the random generator - - - The instance used for random data generation - - - set property, value is a null reference - - - - - A that executes repeatidely an inner - - - - - Creates an instance that executes the rule between - and - times. - - - to repeat - - - Minimum number of occurence - - - Maximum number of occurence - - - - - Executes repeatidely the inner rule. - - - Authorization token - - - - - Converts rule to EBNF like representation - - - EBNF-like string representing the rule. - - - - - Gets or sets the random generator used for selection repetition - counts - - - The random generator. - - - set property, value is a null reference - - - - - Gets the inner instance - - - Repeated instance. - - - - - Gets the minimum of rule execution - - - Minimum of rule execution - - - - - Gets the maximum of rule execution - - - Maximum of rule execution - - - - - Round Robin rule selector. - - - - - Select a from - - - array to select from - - - Select instance - - - is a null reference - - - is empty - - - - - Select a from - - - collection to select from - - - Select instance - - - is a null reference - - - is empty - - - - - Gets or sets the current rule index. - - - Current rule index - - - - - A collection of elements of type IRule - - - - - Initializes a new empty instance of the RuleList class. - - - - - Adds an instance of type IRule to the end of this RuleList. - - - The IRule to be added to the end of this RuleList. - - - - - Determines whether a specfic IRule value is in this RuleList. - - - The IRule value to locate in this RuleList. - - - true if value is found in this RuleList; - false otherwise. - - - - - Inserts an element into the RuleList at the specified index - - - The index at which the IRule is to be inserted. - - - The IRule to insert. - - - - - Removes the first occurrence of a specific IRule from this RuleList. - - - The IRule value to remove from this RuleList. - - - - - Returns an enumerator that can iterate through the elements of this RuleList. - - - An object that implements System.Collections.IEnumerator. - - - - - Gets or sets the IRule at the given index in this RuleList. - - - - - Type-specific enumeration class, used by RuleList.GetEnumerator. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Static helper class for creating rules. - - - - - Creates an alternative of rules. - - - Set of rule to choose from alternatively. - - - - [EBNF] - rule := A | B | C - - [C#] - IRule rule = Rules.Alt(A,B,C); - - - - An instance implementing - the alternative rule choosing. - - - - - Creates a weighted alternative of rules. - - - Set of rule to choose from alternatively. - - - - The property of each rule is used to - weight the probability to choose the rule. - - - [EBNF] - rule := A | B | C where A is chosen with P(A)=A.Weight / ABC.Weight - and ABC.Weight = A.Weight + B.Weight + C.Weight - - [C#] - IRule rule = Rules.WeightedAlt(A,B,C); - - - - An instance implementing - the alternative rule choosing. - - - - - Creates a sequence of rules. - - - Set of rule to execute in sequence. - - - - [EBNF] - rule := A B C - - [C#] - IRule rule = Rules.Seq(A,B,C); - - - - An instance implementing - the sequence of rules. - - - - - Creates an optional rule. - - - Rule to execute optionaly. - - - - [EBNF] - rule := A? - - [C#] - IRule rule = Rules.Opt(A); - - - - An instance implementing - the ? operator. - - - - - Creates a rule to be execute one or more times. - - - Rule to be executed. - - - - [EBNF] - rule := A+ - - [C#] - IRule rule = Rules.Pos(A); - - - - An instance implementing - the + operator. - - - - - Creates a rule to be execute zero or more times. - - - Rule to be executed. - - - - [EBNF] - rule := A* - - [C#] - IRule rule = Rules.Kleene(A); - - - - An instance implementing - the * operator. - - - - - Creates a rule to be execute between - and times. - - - Rule to be executed. - - - - [EBNF] - rule := A{m,n} - - [C#] - IRule rule = Rules.Repetition(A,m,n); - - - - minimum number of execution of - - - maximum number of execution of - - - An instance implementing - the {m,n} operator. - - - - - Creates a that executes an . - - - to execute - - - instance that contains - - - - - Creates a that executes an . - - - to execute - - - instance that contains - - - - - - Creates a that executes an . - - - to execute - - - instance that contains - - - - - - Guards the execution of a from an expected - type. - - - instance to guard. - - - Expected throwed exception when is executed - - - A instance guarding - - - - - Creates a conditional rule with "if" rule. - - - Condition expression - - - to execute if condition is true. - - - A implementing condition rule execution. - - - - - Creates a conditional rule with "if" rule and "else" rule. - - - Condition expression - - - to execute if condition is true. - - - to execute if condition is false. - - - A implementing condition rule execution. - - - - - Creates a conditional rule with "if" rule. - - - Condition expression - - - to execute if condition is true. - - - to execute if condition is false. - - - A implementing condition rule execution. - - - - - Creates a conditional rule with "if" rule and "else" rule. - - - Condition expression - - - to execute if condition is true. - - - A implementing condition rule execution. - - - - - A sequence of rules. - - - - - Executes sub-rule production in sequence. - - - to authorize production. - - - - - Weighted random rule selector. - - - - - Select a from - - - array to select from - - - Select instance - - - is a null reference - - - is empty - - - - - Select a from - - - collection to select from - - - Select instance - - - is a null reference - - - is empty - - - - - - TestFu, the Art of Testing. - - - The TestFu assembly contains a bunch of framework to help - developper build automated tests using random generators, - models, grammars, etc... - - - - - - - The TestFu.Operations namespace contains classes for building - Combinatorial Test suites. - - - The algorithms for generating the covergate suites are extracted - from Efficient Algorithms for Generation of Combinatorial Covering Suites, - by Adrian Dumitrescu. - - - - - - A class to generate permutations. - - - - This class can generate any sequence of permutation of order . - The method returns the next permutation, while - can be used to iterates all the rest of the permutations. - - - The permutation can be applied to an array using , it can also - be inverted using . - - - This class was extracted from - - Using Permutations in .NET for Improved Systems Security by - Dr. James McCaffrey. - - - - - - - Creates a new idenity permutation - - - order of the new permutation - - - - - Creates the -th permutation of - order . - - - - - - - Checks that the permutation is correct - - - - - Converts the permutation to a string representation. - - - - - - Applis the permutation to the array - - - A array of Length equal - to . - - A new array containing the permutated element of - - - - - Creates the inverse of the permutation. - - - - - - Creates the next permutation in lexicographic order. - - - The next instance if there remain any; - otherwize a null reference. - - - - - Gets an enumerable collection of successors. - - - - - - Gets the order of the permutation - - - - - + + + + TestFu + + + + + Static helper class for creating data binders + + + + + Summary description for DataGeneratorCollection. + + + + + A collection of . + + + + + + Adds a to the collection. + + + to add to the collection. + + + is a null reference + (Nothing in Visual Basic) + + + + + Removes a from the collection. + + + to remove from the collection. + + + is a null reference + (Nothing in Visual Basic) + + + + + Removes a associated to + from the collection. + + + whose generator is to be removed from the collection. + + + is a null reference + (Nothing in Visual Basic) + + + + + Removes a associated to + from the collection. + + + Column named whose generator is to be removed from the collection. + + + is a null reference + (Nothing in Visual Basic) + + + + + Gets the associated to the + . + + + is a null reference + (Nothing in Visual Basic) + + + + + Gets the associated to the column named + . + + + is a null reference + (Nothing in Visual Basic) + + + + + A collection of . + + + + + + Summary description for TablePopulatorCollection. + + + + + A collection of . + + + + + + A collection of . + + + + + + Abstract class to perform administrative tasks on a database + + + + + + Initializes an instance of with the connection string. + + + Connection string to the SQL server without initial catalog + + + Catalog name + + + is a null reference (Nothing in Visual Basic) + + + + + Creates a backup of the specified database using the specified + and . + + + A defining the type of output device. + + + Device path. + + + is a null + reference (Nothing in Visual Basic) + + + + + Restores a backup of the specified database using the specified + and . + + + A defining the type of output device. + + + Device path. + + + is a null + reference (Nothing in Visual Basic) + + + + If you plan to override an existing database, you must first drop this database. + This method takes a conservative behavior and will not override an existing database. + + + + + + Creates a new database on the server + + + + + Drops an existing new database on the server + + + is a null + reference (Nothing in Visual Basic) + + + + + Gets a value indicating if the current database exists. + + + true if it exists; otherwise, false. + + + + + Drops the table. + + + Name of the table to drop + + + + This method takes care of removing the constraints associated + to the table before removing the table. + + + + + + Gets a value indicating if the database contains + the table. + + + Name of the table to search + + + true if a table named is contained + in the databse;oterwise false. + + + + + Executes a non-query in a safe, transactional environement. + + + Query to execute. + + + + + Gets or sets the connection string with Initial Catalog information + + + Connection string. + + + + + Gets or sets the database name + + + The database name. + + + + + Gets or sets the database owner. + + + Database owner name. + + + + + Gets the connection string with Initial Catalog information. + + + Connection string with Initial catalog information. + + + + + Enumeration of available SQL backup devices + + + + + + DISK device + + + + + TAPE device + + + + + Output to named dump + + + + + A factory for and + instances. + + + + + + Creates a instance. + + + Connection string to server + + + A instance. + + + + + An abstract base class for test fixtures involving database testing. + + +The DbFixture (SqlFixture for MsSQL server) can be used as a base class for the +fixtures involving database testing. + +[TestFixture] +public class DatabaseTest : SqlFixture +{ + public DatabaseTest() + :base("Data Source=testserver;...","MyTestDatabase") + {} + + [SetUp] + public void SetUp() + { + this.Open(); + this.BeginTransaction(); + } + + [Test] + public void Selec() + { + IDbCollection cmd = this.Connection.CreateCommand("select * from anytable",this.Transaction); + ... + } + + [TearDown] + public void TearDown() + { + this.Close(); + } +} + + + + + + Initializes a with a connection string. + + + Connection string for accessing the test database. + + + is a null reference + (Nothing in Visual Basic) + + + + + Opens a instance with the + . + + + + This method must be implemented in inherited classes for different factorys. + + + + + + Executes a non-query command with the given parameters + + + Query format string + + + Query arguments for the format string + + + Number of affected rows + + + + The connection is automatically opened if necessary. + + + + + + Executes a scalar query with the given parameters + + + Query format string + + + Query arguments for the format string + + + Query result + + + + The connection is automatically opened if necessary. + + + + + + Executes query and returns the + instance + + + Query format string + + + Query arguments for the format string + + + A resulting from the query. + + + + The connection is automatically opened if necessary and the reader + is created with + option. + + + + + + Begins a new transaction. + + + + If a previous transaction was opened, by default, it is rolled back. + + + + The current connection is not created or not opened. + + + + + Commits the current transaction if any. + + + + + Rollsback the current transaction if any. + + + + + Closes the current connection. + + + + If a transaction was opened, it is first rolled back. + + + + + + Gets the database instance + + + A instance. + + + + + Gets the current connection instance. + + + instance. + + + + + Gets the current transaction. + + + A instance if was called + and the connection not closed; otherwise, a null reference (Nothing in Visual Basic) + + + + + Gets the connection string to access the db server (without + database information. + + + + + Gets the test database name. + + + + + + Gets the connection string to connecto the test database. + + + + + A random data generator for values. + + + + This method generates Byte arrays with length in the range + [, ]. + + + + + + Abstract base class from instance. + + + + + An random data generator. + + + + + + Resets the generator + + + + + Generates a new value and fills it in the corresponding . + + + + It is the user job to ensure that the instance + provided is compatible with the generator definition and more + specifically the it is associated with. + + + + + + Gets the generated type + + + Generated . + + + + + Gets or sets the probability to produce a NULL + + + This value determines the probability to produce a null value. + The probability ranges from + 0 - never, to 1 - always. + + + The probability to produce a null object. + + + + + Gets the target column + + + Target instance. + + + + + Resets the generator + + + + + Generates a new value + + + New random data. + + + + + Updates the internal data and verifies column information. + + + + + Gets the generated type + + + Generated type. + + + + + Gets the target column + + + Target instance. + + + + + Gets or sets the probability to produce a NULL + + + This value determines the probability to produce a null value. The probability ranges from + 0, never to 1 always. + + + The probability to produce a null object. + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum length of the generated value + + + Minimum generated length. Default is 16. + + + + + Gets or sets the maximum generated value + + + Maximum generated length. Default is 16. + + + + + A random generator of values. + + + + + Creates an instance with equal to 0.5. + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the probability to return true. + + + Probability to return true. + + + is not in [0,1]. + + + + + A random data generator for values. + + + + This method generates byte values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random data generator for values. + + + + This method generates DateTime values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random data generator for values. + + + + This method generates decimal values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random data generator for values. + + + + This method generates double values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random generator of values. + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + A random data generator for binary values. + + + + This method generates a bitmap of size + [ by ]. + + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the pixel format + + + + + + A random data generator for values. + + + + This method generates int values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random data generator for values. + + + + This method generates int values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random data generator for values. + + + + This method generates int values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + A random generator of instances. + + + + + Initializes a new instance of . + + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum length of the string + + + Minimum length of the string. + + + set proprety, the value is negative. + + + + + Gets or sets the maximum length of the string + + + Maximum length of the string. + + + set proprety, the value is less than 1. + + + + + A random data generator for values. + + + + This method generates float values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is + + + + + Generates a new value + + + New random data. + + + + + Generates a new value + + + New random data. + + + + + + + + This method generates float values in a range [, ]. + + + + + + Generates a new value + + + New random data. + + + + + Gets the generated type + + + Generated type. + + + + + Gets or sets the minimum generated value + + + Minimum generated value. Default is 0 + + + + + Gets or sets the maximum generated value + + + Maximum generated value. Default is 0 + + + + + A random generator of instances. + + + + + Initializes a new instance of . + + + + + + Generates a new value + + + New random data. + + + + + Gets or sets the string containing the generated characters + + + + + + A graph of (vertices) and + (edges). + + + + + Builds a new empty directed graph with default vertex and edge + provider. + + + + + + + Remove all of the edges and vertices from the graph. + + + + + Add a new DataTableVertex to the graph and returns it. + + + Created vertex + + + + + Removes the vertex from the graph. + + vertex to remove + v is null + + + + Add a new vertex from source to target + + Complexity: 2 search + 1 insertion + + Source vertex + Target vertex + Created Edge + + source or target is a null reference + + source or target are not part of the graph + + + + Remove all edges to and from vertex u from the graph. + + + + + + Removes an edge from the graph. + + Complexity: 2 edges removed from the vertex edge list + 1 edge + removed from the edge list. + + edge to remove + + e is a null reference (Nothing in Visual Basic) + + + is not part of the graph + + + + + Remove the edge (u,v) from the graph. + If the graph allows parallel edges this remove all occurrences of + (u,v). + + source vertex + target vertex + + + + Add a new vertex to the graph and returns it. + + Create vertex + + + + Used for serialization. Not for private use. + + edge to add. + + + + Gets a value indicating if the set of out-edges is empty + + + + Usually faster that calling . + + + + true if the out-edge set is empty, false otherwise. + + + v is a null reference (Nothing in Visual Basic) + + + v is not part of the graph. + + + + + Returns the number of out-degree edges of v + + vertex + number of out-edges of the v + + v is a null reference (Nothing in Visual Basic) + + + v is not part of the graph. + + + + + Returns an iterable collection over the edge connected to v + + + out-edges of v + + v is a null reference. + + + v is not part of the graph. + + + + + Test is an edge (u,v) is part of the graph + + source vertex + target vertex + true if part of the graph + + + + Returns the first out-edge that matches the predicate + + + Edge predicate + null if not found, otherwize the first Edge that + matches the predicate. + v or ep is null + + + + Returns the collection of out-edges that matches the predicate + + + Edge predicate + enumerable colleciton of vertices that matches the + criteron + v or ep is null + + + + Remove all the edges from graph g for which the predicate pred + returns true. + + edge predicate + + + + Remove all the out-edges of vertex u for which the predicate pred + returns true. + + vertex + edge predicate + + + + Tests if a is part of the graph + + Vertex to test + true if is part of the graph, false otherwize + + + + Returns the first that matches the predicate + + vertex predicate + null if not found, otherwize the first vertex that + matches the predicate. + vp is null + + + + Returns the collection of vertices that matches the predicate + + vertex predicate + enumerable colleciton of vertices that matches the + criteron + vp is null + + + + Tests if a () is part of the graph + + Edge to test + true if is part of the graph, false otherwize + + + + Returns the first Edge that matches the predicate + + Edge predicate + null if not found, otherwize the first Edge that + matches the predicate. + ep is null + + + + Returns the collection of edges that matches the predicate + + Edge predicate + enumerable colleciton of vertices that matches the + criteron + ep is null + + + + Gets an enumerable collection of adjacent vertices + + + Enumerable collection of adjacent vertices + + + + Gets a value indicating if the set of in-edges is empty + + + + Usually faster that calling . + + + + true if the in-edge set is empty, false otherwise. + + + v is a null reference (Nothing in Visual Basic) + + + is not part of the graph. + + + + + Returns the number of in-degree edges of v + + + number of in-edges of the vertex v + + v is a null reference (Nothing in Visual Basic) + + + is not part of the graph. + + + + + Returns an iterable collection over the in-edge connected to v + + + in-edges of v + + v is a null reference (Nothing in Visual Basic) + + + is not part of the graph. + + + + + Incidence graph implementation + + + + + Gets a value indicating if the set of edges connected to v is empty + + + + Usually faster that calling . + + + + true if the adjacent edge set is empty, false otherwise. + + v is a null reference + + + + Returns the number of in-edges plus out-edges. + + + + + + + Returns the first in-edge that matches the predicate + + + Edge predicate + null if not found, otherwize the first Edge that + matches the predicate. + v or ep is null + + + + Returns the collection of in-edges that matches the predicate + + + Edge predicate + enumerable colleciton of vertices that matches the + criteron + v or ep is null + + + + + + + + + + + + Remove all the out-edges of vertex u for which the predicate pred + returns true. + + vertex + edge predicate + + + + Gets a value indicating if the + is directed. + + + true if the graph is directed, false if undirected. + + + + + Gets a value indicating if the allows parallel edges. + + + true if the is a multi-graph, false otherwise + + + + + Gets the provider + + + provider + + + + + Gets the provider + + + provider + + + + + Gets a value indicating if the vertex set is empty + + + Usually faster (O(1)) that calling VertexCount. + + + true if the vertex set is empty, false otherwise. + + + + + Gets the number of vertices + + + Number of vertices in the graph + + + + + Enumerable collection of vertices. + + + + + Gets a value indicating if the vertex set is empty + + + + Usually faster that calling . + + + + true if the vertex set is empty, false otherwise. + + + + + Gets the edge count + + + Edges count + + + + + Enumerable collection of edges. + + + + + Initializes a new empty instance of the + class. + + + + + Adds an instance of type to the end of this + . + + + The Edge to be added to the end of this EdgeCollection. + + + + + Removes the first occurrence of a specific Edge from this EdgeCollection. + + + The Edge value to remove from this EdgeCollection. + + + + + Determines whether a specfic value is in this EdgeCollection. + + + edge value to locate in this . + + + true if value is found in this collection; + false otherwise. + + + + + Returns an enumerator that can iterate through the elements of this EdgeCollection. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the Edge at the given index in this EdgeCollection. + + + + + Create a new enumerator on the collection + + collection to enumerate + + + + Moves cursor to next element. + + true if current is valid, false otherwize + + + + Resets the cursor to the position before the first element. + + + + + The current element. + + + + + A populator of instance. + + + + + A with a instance. + + + + + A validator check checks constraints + + + + + Preprocesses the row modifies it to fullfill the constraint + + + + + + A database populator instance. + + + + + + Sets up the generators for the given + instance. + + + A representing the structure of the + database to populate. + + + is a null reference (Nothing in + Visual Basic) + + + + + Gets the instance associated + to this populator. + + + A schema used to set-up the generators. + + + + + Gets a collection associated + to each table. + + + A containing + populator associated to each . + + + + + Gets the associated to the + database. + + + + + + An instance that can fill a with + data that are compatible with a + given . + + + + + + Fill the row with data that is compatible with + the foreign key. + + + instance to fill. + + + is a null reference (Nothing + in Visual Basic). + + + + + Gets the table populator associated to the foreign table. + + + The instance + associated to the foreign + table. + + + + + Gets the foreign constraint that needs to be satisfied. + + + The associated to this + provider. + + + + + Gets a value indicating that the foreign table is empty and + cannot provide keys. + + + true if the foreign table is empty; otherwise false. + + + + + An random generator compatible with the schema + of a given . + + + +This example shows how the data generator can be used to create unit tests on database. In this example, +we setup the dummy UserOrderProductDatabase and +the populator in the SetUp method. + + +using System; +using System.Data; +using MbUnit.Core.Framework; +using MbUnit.Framework; +using TestFu.Data; +using TestFu.Data.Populators; + +namespace TestFu.Tests.Data +{ + [TestFixture] + public class DatabasePopulatorTest + { + private UserOrderProductDatabase db; + private DatabasePopulator pop; + private ITablePopulator users; + private ITablePopulator orders; + private ITablePopulator products; + private ITablePopulator orderProducts; + + [SetUp] + public void SetUp() + { + this.db=new UserOrderProductDatabase(); + this.pop = new DatabasePopulator(); + this.pop.Populate(this.db.DataSet); + + this.users=this.pop.Tables[this.db.Users]; + this.orders=this.pop.Tables[this.db.Orders]; + this.products=this.pop.Tables[this.db.Products]; + this.orderProducts=this.pop.Tables[this.db.OrderProducts]; + } + + [Test] + public void AddOneUser() + { + DataRow row = users.Generate(); + this.db.Users.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrder() + { + this.AddOneUser(); + DataRow row = orders.Generate(); + this.db.Orders.Rows.Add(row); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrder() + { + DataRow row = orders.Generate(); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrderProduct() + { + DataRow row = orderProducts.Generate(); + } + + [Test] + public void AddOneUserOneOrderOneProduct() + { + this.AddOneUserOneOrder(); + + DataRow row = products.Generate(); + this.db.Products.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrderOneProductOneProductOrder() + { + this.AddOneUserOneOrderOneProduct(); + DataRow row=orderProducts.Generate(); + this.db.OrderProducts.Rows.Add(row); + } + + [Test] + public void AddTwoUsers() + { + AddOneUser(); + AddOneUser(); + } + + [TearDown] + public void Check() + { + this.db.AcceptChanges(); + Console.WriteLine(db.ToString()); + } + } +} + + + + + + Generates a new . + + + Generated instance. + + + + + Updates randomly a number of rows + + + + + + Updates randomly a number of rows + + + + + + Gets an instance of the $ + that contains this populator. + + + Parent instance. + + + + + Gets the instance that is the model + to be populated. + + + A instance whos schema is used to create + new . + + + + + Gets a collection of + associated to each . + + + A instance + containing the validators associated to each unique constraint. + + + + + Gets a collection of + associated to each . + + + A instance + containing the providers associated to each foreign key. + + + + + Gets a collection of associated + to each column of the table. + + + A instance + containing the generators associated to each column. + + + + + Gets the that ensures CHECK constraints. + + + A instance if any check constraint to verify; + otherwize a null reference. + + + + + Gets the latest generated . + + + Latest generated . + + + + + A validator for constraints. + + + + + + + The TestFu.Data namespace contains a + Random generator + to help developer test databases, data layers, business layers, + etc... + + + + +This example shows some usage of the class. This class can be used to easily backup, restore, create or drop +databases on a server. is the implementation for the MSSQL server: +[C#] +using System; +using TestFu.Data; + +public class Demo +{ + public static void Main(string[] args) + { + DbAdministrator admin = new SqlAdministrator("..."); + + // backup Northwind + admin.Backup("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); + + // drop Northwind + admin.Drop("Northwind"); + + // restore Northwind + admin.Restore("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); + } +} + + + +The DbFixture (SqlFixture for MsSQL server) can be used as a base class for the +fixtures involving database testing. + +[TestFixture] +public class DatabaseTest : SqlFixture +{ + public DatabaseTest() + :base("Data Source=testserver;...","MyTestDatabase") + {} + + [SetUp] + public void SetUp() + { + this.Open(); + this.BeginTransaction(); + } + + [Test] + public void Selec() + { + IDbCollection cmd = this.Connection.CreateCommand("select * from anytable",this.Transaction); + ... + } + + [TearDown] + public void TearDown() + { + this.Close(); + } +} + + +This example shows how the data generator can be used to create unit tests on database. In this example, +we setup the dummy UserOrderProductDatabase and +the populator in the SetUp method. + + +using System; +using System.Data; +using MbUnit.Core.Framework; +using MbUnit.Framework; +using TestFu.Data; +using TestFu.Data.Populators; + +namespace TestFu.Tests.Data +{ + [TestFixture] + public class DatabasePopulatorTest + { + private UserOrderProductDatabase db; + private DatabasePopulator pop; + private ITablePopulator users; + private ITablePopulator orders; + private ITablePopulator products; + private ITablePopulator orderProducts; + + [SetUp] + public void SetUp() + { + this.db=new UserOrderProductDatabase(); + this.pop = new DatabasePopulator(); + this.pop.Populate(this.db.DataSet); + + this.users=this.pop.Tables[this.db.Users]; + this.orders=this.pop.Tables[this.db.Orders]; + this.products=this.pop.Tables[this.db.Products]; + this.orderProducts=this.pop.Tables[this.db.OrderProducts]; + } + + [Test] + public void AddOneUser() + { + DataRow row = users.Generate(); + this.db.Users.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrder() + { + this.AddOneUser(); + DataRow row = orders.Generate(); + this.db.Orders.Rows.Add(row); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrder() + { + DataRow row = orders.Generate(); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrderProduct() + { + DataRow row = orderProducts.Generate(); + } + + [Test] + public void AddOneUserOneOrderOneProduct() + { + this.AddOneUserOneOrder(); + + DataRow row = products.Generate(); + this.db.Products.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrderOneProductOneProductOrder() + { + this.AddOneUserOneOrderOneProduct(); + DataRow row=orderProducts.Generate(); + this.db.OrderProducts.Rows.Add(row); + } + + [Test] + public void AddTwoUsers() + { + AddOneUser(); + AddOneUser(); + } + + [TearDown] + public void Check() + { + this.db.AcceptChanges(); + Console.WriteLine(db.ToString()); + } + } +} + + +The following codes decribes a simple User - Order - Product database contains 4 tables: +Users, Orders, Products and OrderProducts. + + +using System; +using System.Data; +using System.IO; +using System.Xml; + +namespace TestFu.Tests.Data +{ + public class UserOrderProductDatabase + { + private DataSet dataSet; + private DataTable users; + private DataColumn userID; + private DataColumn userName; + + private DataTable orders; + private DataColumn orderID; + private DataColumn orderDate; + private DataColumn oUserID; + + private DataTable products; + private DataColumn productID; + private DataColumn productName; + private DataColumn productPrice; + + private DataTable orderProducts; + private DataColumn opOrderID; + private DataColumn opProductID; + private DataColumn quantity; + + public UserOrderProductDatabase() + { + this.dataSet=new DataSet(); + + this.users=this.dataSet.Tables.Add("Users"); + this.userID = this.users.Columns.Add("UserID",typeof(int)); + this.userName=this.Users.Columns.Add("UserName",typeof(string)); + this.userName.AllowDBNull=false; + + this.orders=this.dataSet.Tables.Add("Orders"); + this.orderID=this.orders.Columns.Add("OrderID",typeof(int)); + this.orderDate = this.orders.Columns.Add("OrderDate",typeof(DateTime)); + this.oUserID = this.orders.Columns.Add("UserID",typeof(int)); + + this.products=this.dataSet.Tables.Add("Products"); + this.productID=this.products.Columns.Add("ProductID",typeof(int)); + this.productName = this.products.Columns.Add("ProductName",typeof(string)); + this.productPrice = this.products.Columns.Add("ProductPrice",typeof(decimal)); + + this.orderProducts=this.dataSet.Tables.Add("OrderProducts"); + this.opOrderID=this.orderProducts.Columns.Add("OrderID",typeof(int)); + this.opProductID=this.orderProducts.Columns.Add("ProductID",typeof(int)); + this.quantity=this.orderProducts.Columns.Add("Quantity",typeof(int)); + + // pks + users.Constraints.Add("PK_Users",userID,true); + orders.Constraints.Add("PK_Orders",orderID,true); + products.Constraints.Add("PK_Products",productID,true); + orderProducts.Constraints.Add("PK_OrderProducts", + new DataColumn[]{ opOrderID, opProductID} + ,true); + + // fks + orders.Constraints.Add("FK_Orders_Users",userID,oUserID); + orderProducts.Constraints.Add("FK_OrderProducts_Orders",orderID,opOrderID); + orderProducts.Constraints.Add("FK_OrderProducts_Products",productID,opProductID); + } + } +} + + + + + + Default implementation. + + + +This example shows how the data generator can be used to create unit tests on database. In this example, +we setup the dummy UserOrderProductDatabase and +the populator in the SetUp method. + + +using System; +using System.Data; +using MbUnit.Core.Framework; +using MbUnit.Framework; +using TestFu.Data; +using TestFu.Data.Populators; + +namespace TestFu.Tests.Data +{ + [TestFixture] + public class DatabasePopulatorTest + { + private UserOrderProductDatabase db; + private DatabasePopulator pop; + private ITablePopulator users; + private ITablePopulator orders; + private ITablePopulator products; + private ITablePopulator orderProducts; + + [SetUp] + public void SetUp() + { + this.db=new UserOrderProductDatabase(); + this.pop = new DatabasePopulator(); + this.pop.Populate(this.db.DataSet); + + this.users=this.pop.Tables[this.db.Users]; + this.orders=this.pop.Tables[this.db.Orders]; + this.products=this.pop.Tables[this.db.Products]; + this.orderProducts=this.pop.Tables[this.db.OrderProducts]; + } + + [Test] + public void AddOneUser() + { + DataRow row = users.Generate(); + this.db.Users.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrder() + { + this.AddOneUser(); + DataRow row = orders.Generate(); + this.db.Orders.Rows.Add(row); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrder() + { + DataRow row = orders.Generate(); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrderProduct() + { + DataRow row = orderProducts.Generate(); + } + + [Test] + public void AddOneUserOneOrderOneProduct() + { + this.AddOneUserOneOrder(); + + DataRow row = products.Generate(); + this.db.Products.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrderOneProductOneProductOrder() + { + this.AddOneUserOneOrderOneProduct(); + DataRow row=orderProducts.Generate(); + this.db.OrderProducts.Rows.Add(row); + } + + [Test] + public void AddTwoUsers() + { + AddOneUser(); + AddOneUser(); + } + + [TearDown] + public void Check() + { + this.db.AcceptChanges(); + Console.WriteLine(db.ToString()); + } + } +} + + + + + + Initiliazes a instance. + + + + + A querying the databse. + + + + + + Base class for implementation. + + + + + + A based on a . + + + + + + Default implementation of + + + + + + Default implementation of + + + + + + An smart random generator. + + + +This example shows how the data generator can be used to create unit tests on database. In this example, +we setup the dummy UserOrderProductDatabase and +the populator in the SetUp method. + + +using System; +using System.Data; +using MbUnit.Core.Framework; +using MbUnit.Framework; +using TestFu.Data; +using TestFu.Data.Populators; + +namespace TestFu.Tests.Data +{ + [TestFixture] + public class DatabasePopulatorTest + { + private UserOrderProductDatabase db; + private DatabasePopulator pop; + private ITablePopulator users; + private ITablePopulator orders; + private ITablePopulator products; + private ITablePopulator orderProducts; + + [SetUp] + public void SetUp() + { + this.db=new UserOrderProductDatabase(); + this.pop = new DatabasePopulator(); + this.pop.Populate(this.db.DataSet); + + this.users=this.pop.Tables[this.db.Users]; + this.orders=this.pop.Tables[this.db.Orders]; + this.products=this.pop.Tables[this.db.Products]; + this.orderProducts=this.pop.Tables[this.db.OrderProducts]; + } + + [Test] + public void AddOneUser() + { + DataRow row = users.Generate(); + this.db.Users.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrder() + { + this.AddOneUser(); + DataRow row = orders.Generate(); + this.db.Orders.Rows.Add(row); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrder() + { + DataRow row = orders.Generate(); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void AddOneOrderProduct() + { + DataRow row = orderProducts.Generate(); + } + + [Test] + public void AddOneUserOneOrderOneProduct() + { + this.AddOneUserOneOrder(); + + DataRow row = products.Generate(); + this.db.Products.Rows.Add(row); + } + + [Test] + public void AddOneUserOneOrderOneProductOneProductOrder() + { + this.AddOneUserOneOrderOneProduct(); + DataRow row=orderProducts.Generate(); + this.db.OrderProducts.Rows.Add(row); + } + + [Test] + public void AddTwoUsers() + { + AddOneUser(); + AddOneUser(); + } + + [TearDown] + public void Check() + { + this.db.AcceptChanges(); + Console.WriteLine(db.ToString()); + } + } +} + + + + + + Helper class to performe task on a SQL server. + + + +This example shows some usage of the class. This class can be used to easily backup, restore, create or drop +databases on a server. is the implementation for the MSSQL server: +[C#] +using System; +using TestFu.Data; + +public class Demo +{ + public static void Main(string[] args) + { + DbAdministrator admin = new SqlAdministrator("..."); + + // backup Northwind + admin.Backup("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); + + // drop Northwind + admin.Drop("Northwind"); + + // restore Northwind + admin.Restore("Northwind",SqlBackupDevice.Disk,@"c:\Backups\Northwind.bkp"); + } +} + + + + + + + Initializes an instance of with the connection string. + + + Connection string to the SQL server without initial catalog + + + Catalog name + + + is a null reference (Nothing in Visual Basic) + + + + + Creates a backup of the specified database using the specified + and . + + + A defining the type of output device. + + + Device path. + + + is a null + reference (Nothing in Visual Basic) + + + + + Restores a backup of the specified database using the specified + and . + + + A defining the type of output device. + + + Device path. + + + is a null + reference (Nothing in Visual Basic) + + + + If you plan to override an existing database, you must first drop this database. + This method takes a conservative behavior and will not override an existing database. + + + Priorly to restore the database, the method kills all the processes associeted + to the database. + + + + + + Creates a new database on the server + + + + + Drops an existing new database on the server + + + is a null + reference (Nothing in Visual Basic) + + + + + Gets the connection string with Initial Catalog information. + + + Connection string with Initial catalog information. + + + + + A implementation for MSSQL server. + + + + + + Creates a instance. + + + + + + + + Creates a instance. + + + Connection string to server + + + A instance. + + + + + Abstract base class for MSSQL server database testing. + + +The DbFixture (SqlFixture for MsSQL server) can be used as a base class for the +fixtures involving database testing. + +[TestFixture] +public class DatabaseTest : SqlFixture +{ + public DatabaseTest() + :base("Data Source=testserver;...","MyTestDatabase") + {} + + [SetUp] + public void SetUp() + { + this.Open(); + this.BeginTransaction(); + } + + [Test] + public void Selec() + { + IDbCollection cmd = this.Connection.CreateCommand("select * from anytable",this.Transaction); + ... + } + + [TearDown] + public void TearDown() + { + this.Close(); + } +} + + + + + Initializes a with a connection string. + + + Connection string for accessing the test database. + + + database name + + + is a null reference + (Nothing in Visual Basic) + + + + + Gets the current connection instance. + + + instance. + + + + + Gets the current transaction. + + + A instance if was called + and the connection not closed; otherwise, a null reference (Nothing in Visual Basic) + + + + + Provides functions to capture the entire screen, or a particular window, and save it to a file. + + + + Source code takened from + http://www.developerfusion.com/show/4630/ + + + + + + Creates an Image object containing a screen shot of the entire desktop + + + + + + Creates an Image object containing a screen shot of the entire desktop + + + + + + Creates an Image object containing a screen shot of the + + + + + Creates an Image object containing a screen shot of a specific window + + The handle to the window. (In windows forms, this is obtained by the Handle property) + + + + + Helper class containing Gdi32 API functions + + + + + Helper class containing User32 API functions + + + + + A that simulates a MouseDown event. + + + + + Abstract base class for + instance. + + + + + Abstract base class for + implementation. + + + + + A user gesture. + + + + User gesture can be a combination of keyboard or mouse + interactions. + + + + + + Executes the gesture + + + + This method should be executed on separate thread + from the main thread, otherwize event will not be + fired correctly. + + + + + + Gets the CodeDom statement creating this gesture + + + + + + Gets the that is targeted + by the gesture + + + + + + Initializes an empty . + + + + + Initializes a new + instance with a form + + + + + + Raises the event. + + + + + + Converts the target from client to + screen coordinates + + + Position in client coordinates + + Position converted into screen coordinates + + + + This method makes a thread safe invokation of the + Form.PointToScreen method. + + + + + + Converts the target from screen to + client coordinates + + + Position in screen coordinates + + Position converted into client coordinates + + + + This method makes a thread safe invokation of the + Form.PointToClient method. + + + + + + Executes the gesture. + + + + + Gets or sets the instance targeted + by the + + + A instance + + + + + Raised when the target is changed + + + + + A mouse gesture. + + + + + Gets or sets a value indicating the + involved in the gesture. + + + A combined value of flags. + + + + + Initializes an new . + + + + + Initializes a new + with a instance and the buttons + involved in the gesture. + + + Target instance + + value representing the + involved in the gesture + + + + + Gets or sets a value indicating the + involved in the gesture. + + + A combined value of flags. + + + + + Initializes a new + + + + + Initializes a new with + a target instance and the left button + + + Target form + + + + Initializes a new with + a target instance and the buttons + + + Target form + + value representing the + involved in the gesture + + + + + Executes the mouse down event + + + + + A that simulates a MouseUp event + + + + + Initialiazes a new . + + + + + Initialiazes a new with + a target . + + + Target form + + + + + Initialiazes a new with + a target . + + + Target form + + + value representing the + involved in the gesture + + + + + Executes the mouse up event + + + + + A that simulates a button click + + + + + Initializes a new + + + + + Initializes a new + with a instance and the left button + + + Target instance + + + + + Initializes a new + with a instance + + + Target instance + + + value representing the + involved in the gesture + + + + + Executes the mouse click + + + + + A that moves the cursor to the + center of a . + + + + + An abstract base class for + implementations + that simulates a mouse movement + + + + + Initializes a new + + + + + Initialiazes a new + with a target form and no buttons + + + Target + + + + + Initialiazes a new + with a target form and the buttons + + + Target + + + value representing the + involved in the gesture + + + + + Steers the mouse towards the target + + + + + Gets the target of the movement, in client coordinates + + + A in client coordinates + + + + + Gets or sets a value indicating the maximum velocity of the + cursor + + + A representing the maximum velocity of the cursor + + + + + Initializes a new + + + + + Initializes a new + with a target and a target + + + + Target form + + Target control + + + + + Initializes a new + with a target , a target + and the buttons pushed during the move + + + Target form + + Target control + + + value representing the + involved in the gesture + + + + + Gets or sets the target + + + A instance where the cursor has to move + + + + + Gets the center of the target . + + + A representing the center of the + target control in client coordiantes + + + + + Offset of the target on the + + + + + + A that steers the cursor to a target + + + + + Initializes a new + + + + + Initializes a new + with a target and a target + + + Target form + + Target in client coordinates + + + + + Initializes a new + with a target and a target + + + Target form + + Target in client coordinates + + + value representing the + involved in the gesture + + + + + Gets the target of the movement, in client coordinates. + + + A in client coordinates + + + + The property value is equal to . + + + + + + Gets or sets the target of the movement, in client coordinates + + + A in client coordinates + + + + + A implementation. + + + + + A mutable collection of + + + + + Adds a instance + to the collection + + + A instance to add to the + collection + + + + + Gets or sets the + at position + + + index of the gesture + + get property, the + at position + + + + + A helper factory of instance. + + + + + Initializes a new + with a instance + + + Target form + + + + Creates a for the + method and starts it. + + + The to execute + + + The started instance + + + + + Creates a instance + with a variable list of instances. + + + gestures to execute in sequence. + + + A instance + + + + Creates a that makes the + thread sleep a given number of milliseconds + + + Duration in milliseconds of the sleep + + + A instance + + + + + Creates a new with + the gesture and the repeat count + + + Target instance + + + Number of repetition + + + A instance + + + + + Creates a + that simulates a left click of the mouse + + + A instance + + + + + Creates a + that simulates a left click of the mouse + + + A instance + + + Control to click + + + + + Creates a + that simulates a left click of the mouse + + + A instance + + + Control to click + + + + + Creates a + that simulates a left click of the mouse + + + value representing the + involved in the gesture + + + A instance + + + + + Creates a new instance + that simulates a Mouse down event (left click) + + + A instance + + + + + Creates a new instance + that simulates a Mouse down event with the buttons + + + value representing the + involved in the gesture + + + A instance + + + + + Creates a new instance + that simulates a Mouse up event (left click) + + + A instance + + + + + Creates a new instance + that simulates a Mouse up event with the buttons + + + value representing the + involved in the gesture + + + A instance + + + + + Creates a + that simulates the movement of the mouse to the target + + + Target client coordinate + + + A instance + + + + + Creates a + that simulates the movement of the mouse to the target + and the buttons down + + + Target client coordinate + + + value representing the + involved in the gesture + + + A instance + + + + + Creates a + that simulates the movement of the mouse to the center + of the + + + Target instance + + + A instance + + + + + Creates a + that simulates the movement of the mouse to the center + of the with the buttons down + + + Target instance + + + value representing the + involved in the gesture + + + A instance + + + + + Creates a instance that simulates + a drag and drop between + and + + + Source client coordinate + + Target client coordinate + + + A instance that simulates the drag and drop + + + + + Creates a instance that simulates + a drag and drop between + and + + + Source client coordinate + + Target + + + A instance that simulates the drag and drop + + + + + Creates a instance that simulates + a drag and drop between + and + + + Source + + + Target client coordinate + + + A instance that simulates the drag and drop + + + + + Creates a instance that simulates + a drag and drop between + and + + + Source + + + Target + + + A instance that simulates the drag and drop + + + + + Creates a instance that simulates + a drag and drop between + and + + + Source + + + Target client coordinate + + + A instance that simulates the drag and drop + + + + + Gets the target instance + + + A instance that is targetted by the gestures + + + + + + The TestFu.Gestures namespace contains classes ( + instances) to simulate user mouse and keyboard interactions. + + + The user interaction are simulated by using native methods + mouse_event and keybd_event. + + + The can be used to rapidly generate + instances. + + + The gestures should not be executed in the main thread but in a worker thread. Otherwize, + you will miss message notifications. All gesture methods on + and are thread safe. + + + + + + A that executes a Repeat of + instances. + + + + + Initializes a new instance + + + + + Initialiazes a new instance + with a instance. + + + Target + + + The gesture to be repeated + + + The number of repetition + + + + Executes the contained in + in Repeat. + + + + + Gets the collection of to execute in Repeat + + + A instance + + + + + Gets or sets the number of gesture repetition + + + The repetition count + + + + + A that executes a sequence of + instances. + + + + + Initializes a new instance + + + + + Initialiazes a new instance + with a instance. + + + Target + + + + + Executes the contained in + in sequence. + + + + + Gets the collection of to execute in sequence + + + A instance + + + + + A that makes the + sleep. + + + + + Initialiazes a new instance. + + + + + Initialiazes a new instance + with a instance and a sleep duration + + + Target instance + + Sleep duration in milliseconds + + + + + Executes the sleep gestures + + + + + Gets or sets the sleep duration (in milliseconds) + + + Number of milliseconds of sleep + + + + + A static helper for artificially generationg mouse + and keyboard input. + + + + This class uses mouse_event and keybd_event native + methods (through interop) to simulate user mouse or keyboard input. + + + + + + Generates a mouse event + + + Combined flag describing the mouse event + + + + + Mouse event with additional data + + + Combined flag describing the mouse event + + + Relative horizontal movement of the cursor + + + Relative vertical movement of the cursor + + Additional data + + + + + Move mouse of units + + + horizontal movement + + vertical movement + + + + + Notfies that a mouse movement is starting + with the buttons settings + + + Combined flag describing the current button + state + + + + + Notfies that a mouse movement is finishing + with the buttons settings + + + Combined flag describing the current button + state + + + + + Mouse click using button state + + + Combined flag describing the current button + state + + + + + Mouse down event + + + + + + Mouse up event + + + + + + Mouse wheel event + + + Wheel movement + + + + Simulates a Key action (KeyDown, Key, KeyUp message sequence) + + character pressed + handle of control to receive the event + + + + Simulates a Backspace + + handle of control to receive the event + + + + Simulates a user typing text + + text to enter + handle of control to receive the event + + + + Mouse even type enumeration + + + + + No event + + + + + Mouse move where dx,dy are in absolute coordinate + + + + + Left button bown + + + + + Left button up + + + + + Middle button down + + + + + middle button up + + + + + Mouse moved + + + + + Right button down + + + + + Right button up + + + + + Mouse wheel movement + + + + + Additional button down + + + + + Additional button up + + + + + A that choose from a set of sub-. + + + + + Abstract rule containing other rules. + + + + + Abstract rule class + + + + + A production rule + + + + A instance is used to execute a production. + + + + + + Executes the production using the rule. + + + A production token authorizing production. + + + is a null reference (Nothing in Visual Basic) + + + + + Gets or sets a value indicating the rule importance + + + Value indicating the rule importance + + + set property, value is negative. + + + + + Semantic actions event. + + + + Semantic action are triggered upon each successful rule execution. + + + + + + Gets a value indicating if the rule is terminal + + + true if the rule is terminal; otherwise, false. + + + + + Gets or sets the rule name (for debugging purpose) + + + The rule name. + + + + + Creates an empty rule + + + true if the rule is terminal; otherwise, false. + + + + + Raises the event. + + + + + Executes the production using the rule (abstract class). + + + A production token authorizing production. + + + is a null reference (Nothing in Visual Basic) + + + + + Gets a value indicating if the rule is terminal + + + true if the rule is terminal; otherwise, false. + + + + + Gets or sets the rule name + + + The rule name + + + + + Gets or sets the rule weight + + + The rule weight + + + set property, weight is negative + + + + + Semantic action event. + + + + + Creates an empty instance. + + + + + Gets the list of rules stored in the rule. + + + containing the child rules. + + + + + Choose a and launch its production. + + + Authorizing token + + + + + Gets or sets the instance + + + instance. + + + + + If then else rule fashion. + + + + This rule uses the results of a + instance to select which to execute: + + if (predicate.Test(...)) + rule.Produce(...); + else + elseRule.Produce(...); + + + + + + + Creates a with a + instance and + instance. + + + instance used for testing + + + rule to execute. + + + or + is a null reference. + + + + + Creates a with a + instance and + instance. If the predicate returns + false, is executed. + + + instance used for testing + + + rule to execute. + + + rule to execute if predicate is false. + + + or + is a null reference. + + + + + Executes one of the rules depending on the predicate result. + + + A production token authorizing production. + + + is a null reference (Nothing in Visual Basic) + + + + + Gets or sets the predicate for the condition. + + + instance used for testing the condition. + + + set property, value is a null reference + + + + + Gets or sets the rule executed when the predicate is true + + + instance executed when + is true. + + + set property, value is a null reference + + + + + Gets or sets the rule executed when the predicate is false + + + instance executed when + is false. + + + + + Method that returns a bool. + + + Current instance. + + + + + A instance that executes + a . + + + + + Predicate that checks a given condition. + + + + + Checks a condition and returns result. + + + Predicate result + + + Current production token + + + + + Creates a new instance arounda + + + to attach. + + + is a null reference. + + + + + Invokes the instance + and returns the result. + + + + + + + A class that limits the number of + terminal execution. + + + + + A production done by a grammar and its set of rules. + + + + + Processes the request for a + done by a rule and returns the token or throws. + + + instance that requests the token. + + + A valid instance. + + + The request was defined using the internal production + logic. + + + + + Gets the seed that created the production + + + Seed used to create the production + + + + + Creates an instance that limits the number of terminal rule execution + to . + + + Maximum number of terminal execution. + + + + + Processes the request for a + done by a rule and returns the token or throws. + + + instance that requests the token. + + + A valid instance. + + + The maximum number of terminal rule execution was hitted. + + + + + Factory for instance. + + + + + A factory for instances. + + + + + Creates a new instance. + + + A valid instance. + + + + + Creates a factory of . + + + + + Creates new instances of + + + A instance + + + + + A that wraps a + call. + + + + + Creates an instance with a + attached. + + + Handler to attach + + + is a null reference + + + + + Invokes handler. + + + + + + A grammar containing a set of rules, a . + + + + + A grammar containing a set of rules, a . + + + + + Launches a production. + + + + + Gets or sets the starting rule. + + + The start . + + + + + Raised when production is finished. + + + + + Creates an empty grammar. + + + + + Launches a production. + + + + + + + + + Gets or sets the instance. + + + instance used for creating new + productions. + + + + + Gets or sets the starting rule. + + + The start . + + + + + A that guard an inner instance + execution from a specific exceptionType. + + + + + Creates an instance with the guarded rule and the expected + exception type. + + + Guarded instance + + + Expected type. + + + or + is a null reference. + + + + + Creates an instance with the guarded rule, the expected + exception type and the regular expression to match the message. + + + Guarded instance + + + Expected type. + + + Regular expression used to match the exception message + + + or + is a null reference. + + + + + Raises the event. + + + + + Executes the inner and guards for + a particular exception type. + + + Authorization token + + + + + Semantic actions event + + + + + Gets or sets the regular expression to match the message. + + + The instance used to mach the message. + + + + If this property is set to null, no message matching is performed. + + + + + + Gets or sets the rule name (for debugging purpose) + + + The rule name. + + + + + Gets or sets a value indicating the rule importance + + + Value indicating the rule importance + + + + + Gets a value indicating if the rule is terminal. + + + Always returns true. + + + + + An authorization to execute a production. + + + + + Gets a value indicating if the production is authorized + + + true if authorized, otherwise false. + + + + + Gets the that emited the token. + + + The instance that emited the token. + + + + + A class that creates random values. + + + + + Returns a nonnegative random number. + + + A 32-bit signed integer greater than or equal to zero and less than + . + + + + + Returns a nonnegative random number less than the specified maximum. + + + + A 32-bit signed integer greater than or equal to zero and less than + . + + + + + Returns a random number within a specified range. + + + The lower bound of the random number returned. + + + The upper bound of the random number returned. + maxValue must be greater than or equal to minValue. + + + A 32-bit signed integer greater than or equal to minValue and less + than maxValue; that is, the range of return values includes + minValue but not MaxValue. If minValue equals maxValue, minValue + is returned. + + + + + Returns a random number between 0.0 and 1.0. + + + A double-precision floating point number greater than or equal + to 0.0, and less than 1.0. + + + + + A collection of . + + + + + Gets an instance of the rules. + + + A valid instance. + + + + + An enumerator over instance. + + + + + Gets the current instance + + + Current instance. + + + + + A list of + + + + + Adds a to the list. + + + to add + + + + + Inserts a instance at position + + + position to insert the rule + + + to insert + + + + + Removes the first occurence of . + + + to remove + + + + + Gets a value indicating if is in the + list. + + + to test. + + + true if is in the list; otherwise, false. + + + + + Clears the list. + + + + + Gets or sets the at position . + + + index. + + + + + A object that select a rule between a collection of rules. + + + + + Select a from + + + array to select from + + + Select instance + + + is a null reference + + + is empty + + + + + Select a from + + + collection to select from + + + Select instance + + + is a null reference + + + is empty + + + + + A rule that executes a . + + + + + Creates a new instance around a + + + to attach. + + + is a null reference. + + + + + Invokes the instance. + + + Autorization token + + + + + The TestFu.Grammars namespace contains a framwork for + implementing + Production Grammars. + + + + + + Exception throwed when an exception is catched and is + not from the expected type. + + + + + Creates an instance with the expected exception type + and the actual exception. + + + Expected exception + + + Actual catch instance + + + + + Exception throwed when an exception message does not match + with the message regular expression + + + + + Creates an instance with the message regular expression and + the actual catched exception. + + + The instance used to match the message + + + The actual instance. + + + + + Gets the instance used to match the exception message + + + message matcher. + + + + + A static helper class for creating . + + + + + Creates a around + + + + condition to wrap + + A + + + + + Expection class used to stop production. + + + + + + + + + + + Gets the production that stopped. + + + + + Default implementation of + + + + + Creates a token from + + + production to wrap. + + + is a null reference (Nothing in + Visual Basic). + + + + + Gets the that emited the token. + + + The instance that emited the token. + + + + + Gets a value indicating if the production is authorized + + + true if authorized, otherwise false. + + + + + A rule that executes a . + + + + + Creates a new instance around a + + + to attach. + + + is a null reference. + + + + + Invokes the instance. + + + Autorization token + + + + + Summary description for ProductionTokenEventArgs. + + + + + System implementation of + + + + + Creates an instance initialized using .Now.Ticks. + + + + + Uniform random rule selector. + + + + + Select a from + + + array to select from + + + Select instance + + + is a null reference + + + is empty + + + + + Select a from + + + collection to select from + + + Select instance + + + is a null reference + + + is empty + + + + + Gets or sets the random generator + + + The instance used for random data generation + + + set property, value is a null reference + + + + + A that executes repeatidely an inner + + + + + Creates an instance that executes the rule between + and + times. + + + to repeat + + + Minimum number of occurence + + + Maximum number of occurence + + + + + Executes repeatidely the inner rule. + + + Authorization token + + + + + Converts rule to EBNF like representation + + + EBNF-like string representing the rule. + + + + + Gets or sets the random generator used for selection repetition + counts + + + The random generator. + + + set property, value is a null reference + + + + + Gets the inner instance + + + Repeated instance. + + + + + Gets the minimum of rule execution + + + Minimum of rule execution + + + + + Gets the maximum of rule execution + + + Maximum of rule execution + + + + + Round Robin rule selector. + + + + + Select a from + + + array to select from + + + Select instance + + + is a null reference + + + is empty + + + + + Select a from + + + collection to select from + + + Select instance + + + is a null reference + + + is empty + + + + + Gets or sets the current rule index. + + + Current rule index + + + + + A collection of elements of type IRule + + + + + Initializes a new empty instance of the RuleList class. + + + + + Adds an instance of type IRule to the end of this RuleList. + + + The IRule to be added to the end of this RuleList. + + + + + Determines whether a specfic IRule value is in this RuleList. + + + The IRule value to locate in this RuleList. + + + true if value is found in this RuleList; + false otherwise. + + + + + Inserts an element into the RuleList at the specified index + + + The index at which the IRule is to be inserted. + + + The IRule to insert. + + + + + Removes the first occurrence of a specific IRule from this RuleList. + + + The IRule value to remove from this RuleList. + + + + + Returns an enumerator that can iterate through the elements of this RuleList. + + + An object that implements System.Collections.IEnumerator. + + + + + Gets or sets the IRule at the given index in this RuleList. + + + + + Type-specific enumeration class, used by RuleList.GetEnumerator. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Static helper class for creating rules. + + + + + Creates an alternative of rules. + + + Set of rule to choose from alternatively. + + + + [EBNF] + rule := A | B | C + + [C#] + IRule rule = Rules.Alt(A,B,C); + + + + An instance implementing + the alternative rule choosing. + + + + + Creates a weighted alternative of rules. + + + Set of rule to choose from alternatively. + + + + The property of each rule is used to + weight the probability to choose the rule. + + + [EBNF] + rule := A | B | C where A is chosen with P(A)=A.Weight / ABC.Weight + and ABC.Weight = A.Weight + B.Weight + C.Weight + + [C#] + IRule rule = Rules.WeightedAlt(A,B,C); + + + + An instance implementing + the alternative rule choosing. + + + + + Creates a sequence of rules. + + + Set of rule to execute in sequence. + + + + [EBNF] + rule := A B C + + [C#] + IRule rule = Rules.Seq(A,B,C); + + + + An instance implementing + the sequence of rules. + + + + + Creates an optional rule. + + + Rule to execute optionaly. + + + + [EBNF] + rule := A? + + [C#] + IRule rule = Rules.Opt(A); + + + + An instance implementing + the ? operator. + + + + + Creates a rule to be execute one or more times. + + + Rule to be executed. + + + + [EBNF] + rule := A+ + + [C#] + IRule rule = Rules.Pos(A); + + + + An instance implementing + the + operator. + + + + + Creates a rule to be execute zero or more times. + + + Rule to be executed. + + + + [EBNF] + rule := A* + + [C#] + IRule rule = Rules.Kleene(A); + + + + An instance implementing + the * operator. + + + + + Creates a rule to be execute between + and times. + + + Rule to be executed. + + + + [EBNF] + rule := A{m,n} + + [C#] + IRule rule = Rules.Repetition(A,m,n); + + + + minimum number of execution of + + + maximum number of execution of + + + An instance implementing + the {m,n} operator. + + + + + Creates a that executes an . + + + to execute + + + instance that contains + + + + + Creates a that executes an . + + + to execute + + + instance that contains + + + + + + Creates a that executes an . + + + to execute + + + instance that contains + + + + + + Guards the execution of a from an expected + type. + + + instance to guard. + + + Expected throwed exception when is executed + + + A instance guarding + + + + + Creates a conditional rule with "if" rule. + + + Condition expression + + + to execute if condition is true. + + + A implementing condition rule execution. + + + + + Creates a conditional rule with "if" rule and "else" rule. + + + Condition expression + + + to execute if condition is true. + + + to execute if condition is false. + + + A implementing condition rule execution. + + + + + Creates a conditional rule with "if" rule. + + + Condition expression + + + to execute if condition is true. + + + to execute if condition is false. + + + A implementing condition rule execution. + + + + + Creates a conditional rule with "if" rule and "else" rule. + + + Condition expression + + + to execute if condition is true. + + + A implementing condition rule execution. + + + + + A sequence of rules. + + + + + Executes sub-rule production in sequence. + + + to authorize production. + + + + + Weighted random rule selector. + + + + + Select a from + + + array to select from + + + Select instance + + + is a null reference + + + is empty + + + + + Select a from + + + collection to select from + + + Select instance + + + is a null reference + + + is empty + + + + + + TestFu, the Art of Testing. + + + The TestFu assembly contains a bunch of framework to help + developper build automated tests using random generators, + models, grammars, etc... + + + + + + + The TestFu.Operations namespace contains classes for building + Combinatorial Test suites. + + + The algorithms for generating the covergate suites are extracted + from Efficient Algorithms for Generation of Combinatorial Covering Suites, + by Adrian Dumitrescu. + + + + + + A class to generate permutations. + + + + This class can generate any sequence of permutation of order . + The method returns the next permutation, while + can be used to iterates all the rest of the permutations. + + + The permutation can be applied to an array using , it can also + be inverted using . + + + This class was extracted from + + Using Permutations in .NET for Improved Systems Security by + Dr. James McCaffrey. + + + + + + + Creates a new idenity permutation + + + order of the new permutation + + + + + Creates the -th permutation of + order . + + + + + + + Checks that the permutation is correct + + + + + Converts the permutation to a string representation. + + + + + + Applis the permutation to the array + + + A array of Length equal + to . + + A new array containing the permutated element of + + + + + Creates the inverse of the permutation. + + + + + + Creates the next permutation in lexicographic order. + + + The next instance if there remain any; + otherwize a null reference. + + + + + Gets an enumerable collection of successors. + + + + + + Gets the order of the permutation + + + + + diff --git a/Tools/MbUnit/users.txt b/Tools/MbUnit/users.txt index b38f886b..6aad3954 100644 --- a/Tools/MbUnit/users.txt +++ b/Tools/MbUnit/users.txt @@ -1,6 +1,6 @@ -Id Name Email -1 ayende ayende@example.org -2 foo foo@example.org -3 bar bar@example.org -4 brak brak@example.org -5 snar snar@example.org +Id Name Email +1 ayende ayende@example.org +2 foo foo@example.org +3 bar bar@example.org +4 brak brak@example.org +5 snar snar@example.org diff --git a/acknowledgements.txt b/acknowledgements.txt index 834b0b01..01af4c1c 100644 --- a/acknowledgements.txt +++ b/acknowledgements.txt @@ -1,2 +1,2 @@ -Rhino Mocks is using Castle Dynamic Proxy (http://www.castleproject.org/dynamicproxy/index.html) to handle proxying the types it needs to mock. +Rhino Mocks is using Castle Dynamic Proxy (http://www.castleproject.org/dynamicproxy/index.html) to handle proxying the types it needs to mock. The Dynamic Proxy project has been invaluable resource and made creating Rhino Mocks possible. \ No newline at end of file diff --git a/default.ps1 b/default.ps1 index cc5add7c..f88a992f 100644 --- a/default.ps1 +++ b/default.ps1 @@ -1,118 +1,118 @@ -properties { - $base_dir = resolve-path . - $lib_dir = "$base_dir\SharedLibs" - $build_dir = "$base_dir\build" - $buildartifacts_dir = "$build_dir\" - $sln_file = "$base_dir\Rhino.Mocks.sln" - $version = "3.6.0.0" - $humanReadableversion = "3.6" - $tools_dir = "$base_dir\Tools" - $release_dir = "$base_dir\Release" - $uploadCategory = "Rhino-Mocks" - $uploadScript = "C:\Builds\Upload\PublishBuild.build" -} - -include .\psake_ext.ps1 - -task default -depends Release - -task Clean { - remove-item -force -recurse $buildartifacts_dir -ErrorAction SilentlyContinue - remove-item -force -recurse $release_dir -ErrorAction SilentlyContinue -} - -task Init -depends Clean { - - Generate-Assembly-Info ` - -file "$base_dir\Rhino.Mocks\Properties\AssemblyInfo.cs" ` - -title "Rhino Mocks $version" ` - -description "Mocking Framework for .NET" ` - -company "Hibernating Rhinos" ` - -product "Rhino Mocks $version" ` - -version $version ` - -copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" - - Generate-Assembly-Info ` - -file "$base_dir\Rhino.Mocks.Tests\Properties\AssemblyInfo.cs" ` - -title "Rhino Mocks Tests $version" ` - -description "Mocking Framework for .NET" ` - -company "Hibernating Rhinos" ` - -product "Rhino Mocks Tests $version" ` - -version $version ` - -clsCompliant "false" ` - -copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" - - Generate-Assembly-Info ` - -file "$base_dir\Rhino.Mocks.Tests.Model\Properties\AssemblyInfo.cs" ` - -title "Rhino Mocks Tests Model $version" ` - -description "Mocking Framework for .NET" ` - -company "Hibernating Rhinos" ` - -product "Rhino Mocks Tests Model $version" ` - -version $version ` - -clsCompliant "false" ` - -copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" - - new-item $release_dir -itemType directory - new-item $buildartifacts_dir -itemType directory - cp $tools_dir\MbUnit\*.* $build_dir -} - -task Compile -depends Init { - exec msbuild "/p:OutDir=""$buildartifacts_dir "" $sln_file" -} - -task Test -depends Compile { - $old = pwd - cd $build_dir - &.\MbUnit.Cons.exe "$build_dir\Rhino.Mocks.Tests.dll" /report-type:Html - if ($lastExitCode -ne 0) { - throw "Error: Failed to execute tests" - } - cd $old -} - -task Merge { - $old = pwd - cd $build_dir - - Remove-Item Rhino.Mocks.Partial.dll -ErrorAction SilentlyContinue - Rename-Item $build_dir\Rhino.Mocks.dll Rhino.Mocks.Partial.dll - - & $tools_dir\ILMerge.exe Rhino.Mocks.Partial.dll ` - Castle.DynamicProxy2.dll ` - Castle.Core.dll ` - /out:Rhino.Mocks.dll ` - /t:library ` - "/keyfile:$base_dir\ayende-open-source.snk" ` - "/internalize:$base_dir\ilmerge.exclude" - if ($lastExitCode -ne 0) { - throw "Error: Failed to merge assemblies!" - } - cd $old -} - -task Release -depends Test, Merge { - & $tools_dir\zip.exe -9 -A -j ` - $release_dir\Rhino.Mocks-$humanReadableversion-Build-$env:ccnetnumericlabel.zip ` - $build_dir\Rhino.Mocks.dll ` - $build_dir\Rhino.Mocks.xml ` - license.txt ` - acknowledgements.txt - if ($lastExitCode -ne 0) { - throw "Error: Failed to execute ZIP command" - } -} - -task Upload -depend Release { - if (Test-Path $uploadScript ) { - $log = git log -n 1 --oneline - msbuild $uploadScript /p:Category=$uploadCategory "/p:Comment=$log" "/p:File=$release_dir\Rhino.Mocks-$humanReadableversion-Build-$env:ccnetnumericlabel.zip" - - if ($lastExitCode -ne 0) { - throw "Error: Failed to publish build" - } - } - else { - Write-Host "could not find upload script $uploadScript, skipping upload" - } +properties { + $base_dir = resolve-path . + $lib_dir = "$base_dir\SharedLibs" + $build_dir = "$base_dir\build" + $buildartifacts_dir = "$build_dir\" + $sln_file = "$base_dir\Rhino.Mocks.sln" + $version = "3.6.0.0" + $humanReadableversion = "3.6" + $tools_dir = "$base_dir\Tools" + $release_dir = "$base_dir\Release" + $uploadCategory = "Rhino-Mocks" + $uploadScript = "C:\Builds\Upload\PublishBuild.build" +} + +include .\psake_ext.ps1 + +task default -depends Release + +task Clean { + remove-item -force -recurse $buildartifacts_dir -ErrorAction SilentlyContinue + remove-item -force -recurse $release_dir -ErrorAction SilentlyContinue +} + +task Init -depends Clean { + + Generate-Assembly-Info ` + -file "$base_dir\Rhino.Mocks\Properties\AssemblyInfo.cs" ` + -title "Rhino Mocks $version" ` + -description "Mocking Framework for .NET" ` + -company "Hibernating Rhinos" ` + -product "Rhino Mocks $version" ` + -version $version ` + -copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" + + Generate-Assembly-Info ` + -file "$base_dir\Rhino.Mocks.Tests\Properties\AssemblyInfo.cs" ` + -title "Rhino Mocks Tests $version" ` + -description "Mocking Framework for .NET" ` + -company "Hibernating Rhinos" ` + -product "Rhino Mocks Tests $version" ` + -version $version ` + -clsCompliant "false" ` + -copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" + + Generate-Assembly-Info ` + -file "$base_dir\Rhino.Mocks.Tests.Model\Properties\AssemblyInfo.cs" ` + -title "Rhino Mocks Tests Model $version" ` + -description "Mocking Framework for .NET" ` + -company "Hibernating Rhinos" ` + -product "Rhino Mocks Tests Model $version" ` + -version $version ` + -clsCompliant "false" ` + -copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" + + new-item $release_dir -itemType directory + new-item $buildartifacts_dir -itemType directory + cp $tools_dir\MbUnit\*.* $build_dir +} + +task Compile -depends Init { + exec msbuild "/p:OutDir=""$buildartifacts_dir "" $sln_file" +} + +task Test -depends Compile { + $old = pwd + cd $build_dir + &.\MbUnit.Cons.exe "$build_dir\Rhino.Mocks.Tests.dll" /report-type:Html + if ($lastExitCode -ne 0) { + throw "Error: Failed to execute tests" + } + cd $old +} + +task Merge { + $old = pwd + cd $build_dir + + Remove-Item Rhino.Mocks.Partial.dll -ErrorAction SilentlyContinue + Rename-Item $build_dir\Rhino.Mocks.dll Rhino.Mocks.Partial.dll + + & $tools_dir\ILMerge.exe Rhino.Mocks.Partial.dll ` + Castle.DynamicProxy2.dll ` + Castle.Core.dll ` + /out:Rhino.Mocks.dll ` + /t:library ` + "/keyfile:$base_dir\ayende-open-source.snk" ` + "/internalize:$base_dir\ilmerge.exclude" + if ($lastExitCode -ne 0) { + throw "Error: Failed to merge assemblies!" + } + cd $old +} + +task Release -depends Test, Merge { + & $tools_dir\zip.exe -9 -A -j ` + $release_dir\Rhino.Mocks-$humanReadableversion-Build-$env:ccnetnumericlabel.zip ` + $build_dir\Rhino.Mocks.dll ` + $build_dir\Rhino.Mocks.xml ` + license.txt ` + acknowledgements.txt + if ($lastExitCode -ne 0) { + throw "Error: Failed to execute ZIP command" + } +} + +task Upload -depend Release { + if (Test-Path $uploadScript ) { + $log = git log -n 1 --oneline + msbuild $uploadScript /p:Category=$uploadCategory "/p:Comment=$log" "/p:File=$release_dir\Rhino.Mocks-$humanReadableversion-Build-$env:ccnetnumericlabel.zip" + + if ($lastExitCode -ne 0) { + throw "Error: Failed to publish build" + } + } + else { + Write-Host "could not find upload script $uploadScript, skipping upload" + } } \ No newline at end of file diff --git a/docs/Rhino.Mocks.build b/docs/Rhino.Mocks.build index 7d1d603a..314ea2cd 100644 --- a/docs/Rhino.Mocks.build +++ b/docs/Rhino.Mocks.build @@ -1,124 +1,124 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Merging Assemblies - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Merging Assemblies + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ilmerge.exclude b/ilmerge.exclude index 339f151a..252600cd 100644 --- a/ilmerge.exclude +++ b/ilmerge.exclude @@ -1,5 +1,5 @@ -Castle.Core.Interceptor.IInvocation -Castle.Core.Interceptor.IInterceptor -Castle.Core.Interceptor.IProxyTargetAccessor -Castle.DynamicProxy.AbstractInvocation -Castle.DynamicProxy.Generators.AttributesToAvoidReplicating +Castle.Core.Interceptor.IInvocation +Castle.Core.Interceptor.IInterceptor +Castle.Core.Interceptor.IProxyTargetAccessor +Castle.DynamicProxy.AbstractInvocation +Castle.DynamicProxy.Generators.AttributesToAvoidReplicating diff --git a/license.txt b/license.txt index 93977366..011d4156 100644 --- a/license.txt +++ b/license.txt @@ -1,25 +1,25 @@ -Copyright (c) 2005 - 2009 Ayende Rahien (ayende@ayende.com) -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of Ayende Rahien nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +Copyright (c) 2005 - 2009 Ayende Rahien (ayende@ayende.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Ayende Rahien nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/psake.ps1 b/psake.ps1 index 325d30dc..1af6661b 100644 --- a/psake.ps1 +++ b/psake.ps1 @@ -1,312 +1,312 @@ -# psake v0.22 -# Copyright © 2009 James Kovacs -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -param( - [string]$buildFile = 'default.ps1', - [string[]]$taskList = @(), - [string]$framework = '3.5', - [switch]$debug = $false, - [switch]$help = $false, - [switch]$timing = $false, - [switch]$docs = $false, - $values -) - -if($help) { -@" -psake [buildFile] [tasks] [-framework ver] [-debug] [-timing] [-docs] - where buildFile is the name of the build file, (default: default.ps1) - tasks is a list of tasks to execute from the build file, - ver is the .NET Framework version to target - 1.0, 1.1, 2.0, 3.0, or 3.5 (default) - debug dumps information on the properties, includes, and tasks, as well as more detailed error information. - timing prints a report showing how long each task took to execute - docs prints a list of available tasks - -psake -help - Displays this message. -"@ - return -} - -$global:tasks = @{} -$global:properties = @() -$global:includes = New-Object System.Collections.Queue -$global:psake_version = "0.22" -$global:psake_buildScript = $buildFile -$global:psake_frameworkVersion = $framework - -$script:executedTasks = New-Object System.Collections.Stack -$script:callStack = New-Object System.Collections.Stack -$script:originalEnvPath = $env:path -$script:originalDirectory = Get-Location -$originalErrorActionPreference = $Global:ErrorActionPreference - -function task([string]$name=$null, [scriptblock]$action = $null, [scriptblock]$precondition = $null, [scriptblock]$postcondition = $null, [switch]$continueOnError = $false, [string[]]$depends = @(), [string]$description = $null) { - if (($name -eq $null) -or ($name.Trim() -eq "")) { - throw "Error: Task must have a name" - } - if($name.ToLower() -eq 'default' -and $action -ne $null) { - throw "Error: Default task cannot specify an action" - } - $newTask = @{ - Name = $name - DependsOn = $depends - Action = $action - Precondition = $precondition - Postcondition = $postcondition - ContinueOnError = $continueOnError - Description = $description - } - if($global:tasks.$name -ne $null) { throw "Error: Task, $name, has already been defined." } - $global:tasks.$name = $newTask -} - -function properties([scriptblock]$propertyBlock) { - $global:properties += $propertyBlock -} - -function include([string]$include){ - if (!(test-path $include)) { throw "Error: $include not found."} - $global:includes.Enqueue((Resolve-Path $include)); -} - -function AssertNotCircular([string]$name) { - if($script:callStack.Contains($name)) { - throw "Error: Circular reference found for task, $name" - } -} - -function ExecuteTask([string]$name) { - if($script:executedTasks.Contains($name)) { return } - AssertNotCircular $name - $script:callStack.Push($name) - - $task = $global:tasks.$name - foreach($childTask in $task.DependsOn) { - ExecuteTask $childTask - } - if($name -ne 'default') { - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - $precondition = $true - if($task.Precondition -ne $null) { - $precondition = (& $task.Precondition) - } - "Executing task, $name..." - if($task.Action -ne $null) { - if($precondition) { - trap { - if ($task.ContinueOnError) { - "-"*70 - "Error in Task [$name] $_" - "-"*70 - continue - } else { - throw $_ - } - } - & $task.Action - $postcondition = $true - if($task.Postcondition -ne $null) { - $postcondition = (& $task.Postcondition) - } - if (!$postcondition) { - throw "Error: Postcondition failed for $name" - } - } else { - "Precondition was false not executing $name" - } - } - $stopwatch.stop() - $task.Duration = $stopwatch.Elapsed - } - - $poppedTask = $script:callStack.Pop() - if($poppedTask -ne $name) { - throw "Error: CallStack was corrupt. Expected $name, but got $poppedTask." - } - $script:executedTasks.Push($name) -} - -function Dump-Tasks { - 'Dumping tasks:' - foreach($key in $global:tasks.Keys) { - $task = $global:tasks.$key; - $task.Name + " depends on " + $task.DependsOn.Length + " other tasks: " + $task.DependsOn; - } - "`n" -} - -function Dump-Properties { - 'Dumping properties:' - $global:properties -} - -function Dump-Includes { - 'Dumping includes:' - $global:includes -} - -function Configure-BuildEnvironment { - $version = $null - switch ($framework) { - '1.0' { $version = 'v1.0.3705' } - '1.1' { $version = 'v1.1.4322' } - '2.0' { $version = 'v2.0.50727' } - '3.0' { $version = 'v2.0.50727' } # .NET 3.0 uses the .NET 2.0 compilers - '3.5' { $version = 'v3.5' } - default { throw "Error: Unknown .NET Framework version, $framework" } - } - $frameworkDir = "$env:windir\Microsoft.NET\Framework\$version\" - if(!(test-path $frameworkDir)) { - throw "Error: No .NET Framework installation directory found at $frameworkDir" - } - $env:path = "$frameworkDir;$env:path" - $global:ErrorActionPreference = "Stop" -} - -function Cleanup-Environment { - $env:path = $script:originalEnvPath - Set-Location $script:originalDirectory - $global:ErrorActionPreference = $originalErrorActionPreference - remove-variable tasks -scope "global" - remove-variable properties -scope "global" - remove-variable includes -scope "global" - remove-variable psake_* -scope "global" -} - -#borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx -function Resolve-Error($ErrorRecord=$Error[0]) { - $ErrorRecord | Format-List * -Force - $ErrorRecord.InvocationInfo | Format-List * - $Exception = $ErrorRecord.Exception - for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException)) { - "$i" * 70 - $Exception | Format-List * -Force - } -} - -function Write-Documentation { - $list = New-Object System.Collections.ArrayList - foreach($key in $global:tasks.Keys) { - if($key -eq "default") { - continue; - } - $task = $global:tasks.$key; - $content = "" | Select-Object Name, Description - $content.Name = $task.Name - $content.Description = $task.Description - $index = $list.Add($content); - } - - $list | Sort 'Name' | Format-Table -Auto -} - -function exec([string]$command, [string]$parameters) { - & $command $parameters - if ($lastExitCode -ne 0) { - throw "Error: Failed to execute ""$command"" with parameters ""$parameters""" - } -} - -function Run-Psake { - trap { - Cleanup-Environment - Write-Host -foregroundcolor Red $_ - if($debug) { - "-" * 80 - "An Error Occurred. See Error Details Below:" - "-" * 80 - Resolve-Error - "-" * 80 - } - exit(1) - } - - $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() - - # Execute the build file to set up the tasks and defaults - if(test-path $buildFile) { - $buildFile = resolve-path $buildFile - set-location (split-path $buildFile) - & $buildFile - } else { - throw "Error: Could not find the build file, $buildFile." - } - - if($debug) { - Dump-Includes - Dump-Properties - Dump-Tasks - } - - Configure-BuildEnvironment - - # N.B. The initial dot (.) indicates that variables initialized/modified - # in the propertyBlock are available in the parent scope. - while ($global:includes.Count -gt 0) { - $includeBlock = $global:includes.Dequeue(); - . $includeBlock; - } - foreach($propertyBlock in $global:properties) { - . $propertyBlock - } - - if($docs) { - Write-Documentation - Cleanup-Environment - exit(0) - } - - # Execute the list of tasks or the default task - if($taskList.Length -ne 0) { - foreach($task in $taskList) { - ExecuteTask $task - } - } elseif ($global:tasks.default -ne $null) { - ExecuteTask default - } else { - throw 'Error: default task required' - } - - $stopwatch.Stop() - - if ($timing) { - "-"*70 - "Build Time Report" - "-"*70 - $list = @() - while ($script:executedTasks.Count -gt 0) { - $name = $script:executedTasks.Pop() - $task = $global:tasks.$name - if($name -eq "default") { - continue; - } - $list += "" | Select-Object @{Name="Name";Expression={$name}}, @{Name="Duration";Expression={$task.Duration}} - } - [Array]::Reverse($list) - $list += "" | Select-Object @{Name="Name";Expression={"Total:"}}, @{Name="Duration";Expression={$stopwatch.Elapsed}} - $list | Format-Table -Auto | Out-String -Stream | ? {$_} # using "Out-String -Stream" to filter out the blank line that Format-Table prepends - } - - # Clear out any global variables - Cleanup-Environment -} - +# psake v0.22 +# Copyright © 2009 James Kovacs +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +param( + [string]$buildFile = 'default.ps1', + [string[]]$taskList = @(), + [string]$framework = '3.5', + [switch]$debug = $false, + [switch]$help = $false, + [switch]$timing = $false, + [switch]$docs = $false, + $values +) + +if($help) { +@" +psake [buildFile] [tasks] [-framework ver] [-debug] [-timing] [-docs] + where buildFile is the name of the build file, (default: default.ps1) + tasks is a list of tasks to execute from the build file, + ver is the .NET Framework version to target - 1.0, 1.1, 2.0, 3.0, or 3.5 (default) + debug dumps information on the properties, includes, and tasks, as well as more detailed error information. + timing prints a report showing how long each task took to execute + docs prints a list of available tasks + +psake -help + Displays this message. +"@ + return +} + +$global:tasks = @{} +$global:properties = @() +$global:includes = New-Object System.Collections.Queue +$global:psake_version = "0.22" +$global:psake_buildScript = $buildFile +$global:psake_frameworkVersion = $framework + +$script:executedTasks = New-Object System.Collections.Stack +$script:callStack = New-Object System.Collections.Stack +$script:originalEnvPath = $env:path +$script:originalDirectory = Get-Location +$originalErrorActionPreference = $Global:ErrorActionPreference + +function task([string]$name=$null, [scriptblock]$action = $null, [scriptblock]$precondition = $null, [scriptblock]$postcondition = $null, [switch]$continueOnError = $false, [string[]]$depends = @(), [string]$description = $null) { + if (($name -eq $null) -or ($name.Trim() -eq "")) { + throw "Error: Task must have a name" + } + if($name.ToLower() -eq 'default' -and $action -ne $null) { + throw "Error: Default task cannot specify an action" + } + $newTask = @{ + Name = $name + DependsOn = $depends + Action = $action + Precondition = $precondition + Postcondition = $postcondition + ContinueOnError = $continueOnError + Description = $description + } + if($global:tasks.$name -ne $null) { throw "Error: Task, $name, has already been defined." } + $global:tasks.$name = $newTask +} + +function properties([scriptblock]$propertyBlock) { + $global:properties += $propertyBlock +} + +function include([string]$include){ + if (!(test-path $include)) { throw "Error: $include not found."} + $global:includes.Enqueue((Resolve-Path $include)); +} + +function AssertNotCircular([string]$name) { + if($script:callStack.Contains($name)) { + throw "Error: Circular reference found for task, $name" + } +} + +function ExecuteTask([string]$name) { + if($script:executedTasks.Contains($name)) { return } + AssertNotCircular $name + $script:callStack.Push($name) + + $task = $global:tasks.$name + foreach($childTask in $task.DependsOn) { + ExecuteTask $childTask + } + if($name -ne 'default') { + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + $precondition = $true + if($task.Precondition -ne $null) { + $precondition = (& $task.Precondition) + } + "Executing task, $name..." + if($task.Action -ne $null) { + if($precondition) { + trap { + if ($task.ContinueOnError) { + "-"*70 + "Error in Task [$name] $_" + "-"*70 + continue + } else { + throw $_ + } + } + & $task.Action + $postcondition = $true + if($task.Postcondition -ne $null) { + $postcondition = (& $task.Postcondition) + } + if (!$postcondition) { + throw "Error: Postcondition failed for $name" + } + } else { + "Precondition was false not executing $name" + } + } + $stopwatch.stop() + $task.Duration = $stopwatch.Elapsed + } + + $poppedTask = $script:callStack.Pop() + if($poppedTask -ne $name) { + throw "Error: CallStack was corrupt. Expected $name, but got $poppedTask." + } + $script:executedTasks.Push($name) +} + +function Dump-Tasks { + 'Dumping tasks:' + foreach($key in $global:tasks.Keys) { + $task = $global:tasks.$key; + $task.Name + " depends on " + $task.DependsOn.Length + " other tasks: " + $task.DependsOn; + } + "`n" +} + +function Dump-Properties { + 'Dumping properties:' + $global:properties +} + +function Dump-Includes { + 'Dumping includes:' + $global:includes +} + +function Configure-BuildEnvironment { + $version = $null + switch ($framework) { + '1.0' { $version = 'v1.0.3705' } + '1.1' { $version = 'v1.1.4322' } + '2.0' { $version = 'v2.0.50727' } + '3.0' { $version = 'v2.0.50727' } # .NET 3.0 uses the .NET 2.0 compilers + '3.5' { $version = 'v3.5' } + default { throw "Error: Unknown .NET Framework version, $framework" } + } + $frameworkDir = "$env:windir\Microsoft.NET\Framework\$version\" + if(!(test-path $frameworkDir)) { + throw "Error: No .NET Framework installation directory found at $frameworkDir" + } + $env:path = "$frameworkDir;$env:path" + $global:ErrorActionPreference = "Stop" +} + +function Cleanup-Environment { + $env:path = $script:originalEnvPath + Set-Location $script:originalDirectory + $global:ErrorActionPreference = $originalErrorActionPreference + remove-variable tasks -scope "global" + remove-variable properties -scope "global" + remove-variable includes -scope "global" + remove-variable psake_* -scope "global" +} + +#borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx +function Resolve-Error($ErrorRecord=$Error[0]) { + $ErrorRecord | Format-List * -Force + $ErrorRecord.InvocationInfo | Format-List * + $Exception = $ErrorRecord.Exception + for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException)) { + "$i" * 70 + $Exception | Format-List * -Force + } +} + +function Write-Documentation { + $list = New-Object System.Collections.ArrayList + foreach($key in $global:tasks.Keys) { + if($key -eq "default") { + continue; + } + $task = $global:tasks.$key; + $content = "" | Select-Object Name, Description + $content.Name = $task.Name + $content.Description = $task.Description + $index = $list.Add($content); + } + + $list | Sort 'Name' | Format-Table -Auto +} + +function exec([string]$command, [string]$parameters) { + & $command $parameters + if ($lastExitCode -ne 0) { + throw "Error: Failed to execute ""$command"" with parameters ""$parameters""" + } +} + +function Run-Psake { + trap { + Cleanup-Environment + Write-Host -foregroundcolor Red $_ + if($debug) { + "-" * 80 + "An Error Occurred. See Error Details Below:" + "-" * 80 + Resolve-Error + "-" * 80 + } + exit(1) + } + + $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + + # Execute the build file to set up the tasks and defaults + if(test-path $buildFile) { + $buildFile = resolve-path $buildFile + set-location (split-path $buildFile) + & $buildFile + } else { + throw "Error: Could not find the build file, $buildFile." + } + + if($debug) { + Dump-Includes + Dump-Properties + Dump-Tasks + } + + Configure-BuildEnvironment + + # N.B. The initial dot (.) indicates that variables initialized/modified + # in the propertyBlock are available in the parent scope. + while ($global:includes.Count -gt 0) { + $includeBlock = $global:includes.Dequeue(); + . $includeBlock; + } + foreach($propertyBlock in $global:properties) { + . $propertyBlock + } + + if($docs) { + Write-Documentation + Cleanup-Environment + exit(0) + } + + # Execute the list of tasks or the default task + if($taskList.Length -ne 0) { + foreach($task in $taskList) { + ExecuteTask $task + } + } elseif ($global:tasks.default -ne $null) { + ExecuteTask default + } else { + throw 'Error: default task required' + } + + $stopwatch.Stop() + + if ($timing) { + "-"*70 + "Build Time Report" + "-"*70 + $list = @() + while ($script:executedTasks.Count -gt 0) { + $name = $script:executedTasks.Pop() + $task = $global:tasks.$name + if($name -eq "default") { + continue; + } + $list += "" | Select-Object @{Name="Name";Expression={$name}}, @{Name="Duration";Expression={$task.Duration}} + } + [Array]::Reverse($list) + $list += "" | Select-Object @{Name="Name";Expression={"Total:"}}, @{Name="Duration";Expression={$stopwatch.Elapsed}} + $list | Format-Table -Auto | Out-String -Stream | ? {$_} # using "Out-String -Stream" to filter out the blank line that Format-Table prepends + } + + # Clear out any global variables + Cleanup-Environment +} + Run-Psake \ No newline at end of file diff --git a/psake_ext.ps1 b/psake_ext.ps1 index 109b4cdd..280c2fea 100644 --- a/psake_ext.ps1 +++ b/psake_ext.ps1 @@ -1,40 +1,40 @@ -function Generate-Assembly-Info -{ -param( - [string]$clsCompliant = "true", - [string]$title, - [string]$description, - [string]$company, - [string]$product, - [string]$copyright, - [string]$version, - [string]$file = $(throw "file is a required parameter.") -) - - $asmInfo = "using System; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -[assembly: CLSCompliantAttribute($clsCompliant )] -[assembly: ComVisibleAttribute(false)] -[assembly: AssemblyTitleAttribute(""$title"")] -[assembly: AssemblyDescriptionAttribute(""$description"")] -[assembly: AssemblyCompanyAttribute(""$company"")] -[assembly: AssemblyProductAttribute(""$product"")] -[assembly: AssemblyCopyrightAttribute(""$copyright"")] -[assembly: AssemblyVersionAttribute(""$version"")] -[assembly: AssemblyInformationalVersionAttribute(""$version"")] -[assembly: AssemblyFileVersionAttribute(""$version"")] -[assembly: AssemblyDelaySignAttribute(false)] -" - - $dir = [System.IO.Path]::GetDirectoryName($file) - if ([System.IO.Directory]::Exists($dir) -eq $false) - { - Write-Host "Creating directory $dir" - [System.IO.Directory]::CreateDirectory($dir) - } - Write-Host "Generating assembly info file: $file" - Write-Output $asmInfo > $file +function Generate-Assembly-Info +{ +param( + [string]$clsCompliant = "true", + [string]$title, + [string]$description, + [string]$company, + [string]$product, + [string]$copyright, + [string]$version, + [string]$file = $(throw "file is a required parameter.") +) + + $asmInfo = "using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: CLSCompliantAttribute($clsCompliant )] +[assembly: ComVisibleAttribute(false)] +[assembly: AssemblyTitleAttribute(""$title"")] +[assembly: AssemblyDescriptionAttribute(""$description"")] +[assembly: AssemblyCompanyAttribute(""$company"")] +[assembly: AssemblyProductAttribute(""$product"")] +[assembly: AssemblyCopyrightAttribute(""$copyright"")] +[assembly: AssemblyVersionAttribute(""$version"")] +[assembly: AssemblyInformationalVersionAttribute(""$version"")] +[assembly: AssemblyFileVersionAttribute(""$version"")] +[assembly: AssemblyDelaySignAttribute(false)] +" + + $dir = [System.IO.Path]::GetDirectoryName($file) + if ([System.IO.Directory]::Exists($dir) -eq $false) + { + Write-Host "Creating directory $dir" + [System.IO.Directory]::CreateDirectory($dir) + } + Write-Host "Generating assembly info file: $file" + Write-Output $asmInfo > $file } \ No newline at end of file