You can subscribe to this list here.
| 2002 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(31) |
Dec
(26) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2003 |
Jan
(8) |
Feb
(27) |
Mar
(15) |
Apr
|
May
(2) |
Jun
(13) |
Jul
(59) |
Aug
(48) |
Sep
(9) |
Oct
(4) |
Nov
(24) |
Dec
|
| 2004 |
Jan
(24) |
Feb
(2) |
Mar
(12) |
Apr
(9) |
May
(4) |
Jun
(26) |
Jul
(20) |
Aug
(23) |
Sep
(13) |
Oct
(31) |
Nov
(23) |
Dec
(11) |
| 2005 |
Jan
|
Feb
|
Mar
|
Apr
(19) |
May
(64) |
Jun
(7) |
Jul
(20) |
Aug
(1) |
Sep
(6) |
Oct
|
Nov
(3) |
Dec
|
| 2006 |
Jan
|
Feb
(69) |
Mar
(18) |
Apr
(1) |
May
(4) |
Jun
(3) |
Jul
(27) |
Aug
(19) |
Sep
(12) |
Oct
(3) |
Nov
(13) |
Dec
(6) |
| 2007 |
Jan
(20) |
Feb
(17) |
Mar
(1) |
Apr
(3) |
May
(4) |
Jun
(11) |
Jul
(10) |
Aug
(24) |
Sep
(19) |
Oct
(13) |
Nov
(8) |
Dec
(7) |
| 2008 |
Jan
(54) |
Feb
(24) |
Mar
(11) |
Apr
(35) |
May
(13) |
Jun
(10) |
Jul
(30) |
Aug
(18) |
Sep
(21) |
Oct
(18) |
Nov
(40) |
Dec
(76) |
| 2009 |
Jan
(64) |
Feb
(23) |
Mar
(15) |
Apr
(23) |
May
(46) |
Jun
(25) |
Jul
(31) |
Aug
(7) |
Sep
(7) |
Oct
(6) |
Nov
(15) |
Dec
(19) |
| 2010 |
Jan
(13) |
Feb
(8) |
Mar
(6) |
Apr
(4) |
May
(8) |
Jun
(7) |
Jul
(3) |
Aug
(9) |
Sep
(6) |
Oct
(15) |
Nov
(3) |
Dec
(5) |
| 2011 |
Jan
(1) |
Feb
|
Mar
(4) |
Apr
(5) |
May
(2) |
Jun
|
Jul
(2) |
Aug
(2) |
Sep
(2) |
Oct
(4) |
Nov
(2) |
Dec
(3) |
| 2012 |
Jan
(6) |
Feb
(2) |
Mar
(3) |
Apr
(3) |
May
(3) |
Jun
(1) |
Jul
|
Aug
|
Sep
(2) |
Oct
(2) |
Nov
|
Dec
(1) |
| 2013 |
Jan
(3) |
Feb
(1) |
Mar
|
Apr
|
May
(1) |
Jun
(1) |
Jul
|
Aug
(5) |
Sep
|
Oct
(1) |
Nov
(2) |
Dec
|
| 2014 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
(1) |
Jul
(1) |
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
(1) |
| 2015 |
Jan
|
Feb
(19) |
Mar
(115) |
Apr
(23) |
May
(41) |
Jun
(48) |
Jul
(59) |
Aug
(29) |
Sep
(40) |
Oct
(78) |
Nov
(58) |
Dec
(47) |
| 2016 |
Jan
(25) |
Feb
(30) |
Mar
(29) |
Apr
(10) |
May
(17) |
Jun
(1) |
Jul
(1) |
Aug
(6) |
Sep
(2) |
Oct
(1) |
Nov
(3) |
Dec
(2) |
| 2017 |
Jan
(5) |
Feb
(2) |
Mar
(7) |
Apr
(1) |
May
(7) |
Jun
(2) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2018 |
Jan
|
Feb
|
Mar
(5) |
Apr
|
May
(1) |
Jun
|
Jul
(3) |
Aug
|
Sep
|
Oct
|
Nov
(2) |
Dec
|
| 2019 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
(3) |
| 2020 |
Jan
|
Feb
|
Mar
|
Apr
(6) |
May
|
Jun
|
Jul
(29) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2021 |
Jan
|
Feb
|
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(5) |
Dec
(3) |
| 2022 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(5) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2023 |
Jan
|
Feb
|
Mar
|
Apr
(3) |
May
|
Jun
(7) |
Jul
(1) |
Aug
|
Sep
(6) |
Oct
(4) |
Nov
(1) |
Dec
(4) |
| 2024 |
Jan
(2) |
Feb
(5) |
Mar
|
Apr
|
May
(8) |
Jun
(159) |
Jul
(90) |
Aug
(22) |
Sep
|
Oct
(6) |
Nov
(8) |
Dec
(1) |
| 2025 |
Jan
(20) |
Feb
(6) |
Mar
(2) |
Apr
(4) |
May
(29) |
Jun
(63) |
Jul
(62) |
Aug
(70) |
Sep
(120) |
Oct
(46) |
Nov
(33) |
Dec
(25) |
| 2026 |
Jan
(37) |
Feb
(56) |
Mar
(62) |
Apr
(35) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: <thi...@gm...> - 2005-06-07 12:33:36
|
Hi nmock 1.1 binaries are not strong named if I'm not mistaken. I can't get access to the source from where I am so I can't check myself, could someone tell me if strong naming is currently activated in nmock build scripts ? kind regards Thibaut |
|
From: <sco...@rk...> - 2005-06-07 12:17:50
|
Hello,
I just ran into this problem today. John, can you please post your patch =
and/or check it in. Thibaut, I am also interested to see what your work =
around is. Can you please post it?
Thanks,
-Scott
----Original Message-----
Hi Thibaut,
=20
This is actually the same problem I ran into that I mentioned in a =
recent list post (the
issue is "NMO-44" on the jira.truemesh tracker, but doesn"t seem to be =
in the sourceforge
tracker). I"ve got a fix for it that seems to work well, but it hasn"t =
been incorporated
into the official source yet.
=20
If you"re interested, I can send you the patch and you can compile your =
own version for the
time being.
=20
John.
=20
-----Original Message-----
From: nmock-general-admin@li...
[mailto:nmock-general-admin@li...] On Behalf Of Thibaut Barr=E8re
Sent: Tuesday, May 10, 2005 11:29 AM
To: <nmock-general@li...>
Subject: [Nmock-general] Inherited properties and DynamicMock (known =
bug?)
=20
Hi,
=20
I"m getting a NullReferenceException while calling SetupResult for an
inherited property (full testcase below) :
- is it a know issue ?
- which tracker should I use to open an issue for that, if not know =
already ?
=20
I found a quick workaround which is to create a custom class
inheriting from DynamicMock, and override Invoke().
=20
=20
regards
=20
Thibaut
=20
=20
=20
Repro:
=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D
public enum MyEnum
{
MyValue
}
=20
public interface IMyInterface
{
MyEnum Enum { get; }
}
=20
public interface IMyChildInterface : IMyInterface
{
}
=20
[Test]
public void SetupResultWithInheritedProperty()
{
DynamicMock mock =3D new DynamicMock(typeof(IMyChildInterface));
mock.SetupResult("Enum",MyEnum.MyValue);
IMyChildInterface instance =3D (IMyChildInterface)mock.MockInstance;
}
=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D
=20
Exception I get :
=20
System.NullReferenceException : Object reference not set to an
instance of an object.
at NMock.DynamicMock.checkReturnTypeIsValid(String methodName, Object
returnVal, MethodSignature signature)
at NMock.DynamicMock.SetupResult(String methodName, Object returnVal,
Type[] argTypes)
=20
=20
-------------------------------------------------------
This SF.Net email is sponsored by Oracle Space Sweepstakes
Want to be the first software developer in space?
Enter now for the Oracle Space Sweepstakes!
http://ads.osdn.com/?ad_ids93&alloc_id=16281&op=3Dick
_______________________________________________
Nmock-general mailing list
Nmock-general@li...
https://lists.sourceforge.net/lists/listinfo/nmock-general
=20
From: <thibaut@gm...>
Re: Inherited properties and DynamicMock (known bug?) =20
2005-05-11 14:02
Hi John,
=20
thanks for pointing this out; I"ve missed the message.
=20
I can wait until it"s incorporated into the main tree, it"s just fine =
for me.
=20
Who are the committers ?
=20
=20
cheers
=20
Thibaut
=20
2005/5/11, John Price <John.Price@de...>:
> Hi Thibaut,
>=20
> This is actually the same problem I ran into that I mentioned in a =
recent list post (the
issue is "NMO-44" on the jira.truemesh tracker, but doesn"t seem to be =
in the sourceforge
tracker). I"ve got a fix for it that seems to work well, but it hasn"t =
been incorporated
into the official source yet.
>=20
> If you"re interested, I can send you the patch and you can compile =
your own version for
the time being.
>=20
> John.
>=20
> -----Original Message-----
> From: nmock-general-admin@li...
[mailto:nmock-general-admin@li...] On Behalf Of Thibaut Barr=E8re
> Sent: Tuesday, May 10, 2005 11:29 AM
> To: <nmock-general@li...>
> Subject: [Nmock-general] Inherited properties and DynamicMock (known =
bug?)
>=20
> Hi,
>=20
> I"m getting a NullReferenceException while calling SetupResult for an
> inherited property (full testcase below) :
> - is it a know issue ?
> - which tracker should I use to open an issue for that, if not know =
already ?
>=20
> I found a quick workaround which is to create a custom class
> inheriting from DynamicMock, and override Invoke().
>=20
> regards
>=20
> Thibaut
>=20
> Repro:
> =
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D
> public enum MyEnum
> {
> MyValue
> }
>=20
> public interface IMyInterface
> {
> MyEnum Enum { get; }
> }
>=20
> public interface IMyChildInterface : IMyInterface
> {
> }
>=20
> [Test]
> public void SetupResultWithInheritedProperty()
> {
> DynamicMock mock =3D new =
DynamicMock(typeof(IMyChildInterface));
> mock.SetupResult("Enum",MyEnum.MyValue);
> IMyChildInterface instance =3D =
(IMyChildInterface)mock.MockInstance;
> }
> =
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D
>=20
> Exception I get :
>=20
> System.NullReferenceException : Object reference not set to an
> instance of an object.
> at NMock.DynamicMock.checkReturnTypeIsValid(String methodName, =
Object
> returnVal, MethodSignature signature)
> at NMock.DynamicMock.SetupResult(String methodName, Object =
returnVal,
> Type[] argTypes)
>=20
> -------------------------------------------------------
> This SF.Net email is sponsored by Oracle Space Sweepstakes
> Want to be the first software developer in space?
> Enter now for the Oracle Space Sweepstakes!
> http://ads.osdn.com/?ad_ids93&alloc_id=16281&op=3Dick
> _______________________________________________
> Nmock-general mailing list
> Nmock-general@li...
> https://lists.sourceforge.net/lists/listinfo/nmock-general
>=20
> -------------------------------------------------------
> This SF.Net email is sponsored by Oracle Space Sweepstakes
> Want to be the first software developer in space?
> Enter now for the Oracle Space Sweepstakes!
> http://ads.osdn.com/?ad_ids93&alloc_id=16281&opclick
> _______________________________________________
> Nmock-general mailing list
> Nmock-general@li...
> https://lists.sourceforge.net/lists/listinfo/nmock-general
>
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Matchers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2/Matchers Added Files: AlwaysMatcher.cs BinaryOperator.cs NullMatcher.cs OrMatcher.cs NotMatcher.cs PropertyMatcher.cs ComparisonMatcher.cs DescriptionOverride.cs MethodNameMatcher.cs EqualMatcher.cs ToStringMatcher.cs StringContainsMatcher.cs SameMatcher.cs AndMatcher.cs ArgumentsMatcher.cs IndexSetterArgumentsMatcher.cs IndexGetterArgumentsMatcher.cs Log Message: first upload of nmock2 --- NEW FILE: DescriptionOverride.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: SameMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class SameMatcher : Matcher { private object expected; public SameMatcher(object expected) { this.expected = expected; } public override bool Matches(object o) { return expected == o; } public override void DescribeTo(TextWriter writer) { writer.Write("same as "); writer.Write(expected); } } } --- NEW FILE: ComparisonMatcher.cs --- using System; using System.IO; namespace NMock2.Matchers { public class ComparisonMatcher : Matcher { private readonly IComparable value; private readonly int minComparisonResult; private readonly int maxComparisonResult; public ComparisonMatcher(IComparable value, int comparisonResult1, int comparisonResult2) { this.value = value; this.minComparisonResult = Math.Min(comparisonResult1, comparisonResult2) ; this.maxComparisonResult = Math.Max(comparisonResult1, comparisonResult2) ; if (minComparisonResult == -1 && maxComparisonResult == 1) { throw new ArgumentException("comparison result range too large", "comparisonResult1, comparisonResult2"); } } public override bool Matches(object o) { if (o.GetType() == value.GetType()) { int comparisonResult = -(value.CompareTo(o)); return comparisonResult >= minComparisonResult && comparisonResult <= maxComparisonResult; } else { return false; } } public override void DescribeTo(TextWriter writer) { writer.Write("? "); if (minComparisonResult == -1) writer.Write("<"); if (maxComparisonResult == 1) writer.Write(">"); if (minComparisonResult == 0 || maxComparisonResult == 0) writer.Write("="); writer.Write(" "); writer.Write(value); } } } --- NEW FILE: ToStringMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class ToStringMatcher : Matcher { private readonly Matcher stringMatcher; public ToStringMatcher(Matcher stringMatcher) { this.stringMatcher = stringMatcher; } public override bool Matches(object o) { return stringMatcher.Matches(o.ToString()); } public override void DescribeTo(TextWriter writer) { writer.Write("an object with a string representation that is "); stringMatcher.DescribeTo(writer); } } } --- NEW FILE: ArgumentsMatcher.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: StringContainsMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class StringContainsMatcher : Matcher { private readonly string substring; public StringContainsMatcher(string substring) { this.substring = substring; } public override bool Matches(object o) { return o != null && o is string && ((string)o).IndexOf(substring) >= 0; } public override void DescribeTo(TextWriter writer) { writer.Write("containing "); writer.Write((object)substring); } } } --- NEW FILE: IndexSetterArgumentsMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class IndexSetterArgumentsMatcher : ArgumentsMatcher { public IndexSetterArgumentsMatcher(params Matcher[] valueMatchers) : base(valueMatchers) { } public override void DescribeTo(TextWriter writer) { writer.Write("["); WriteListOfMatchers(MatcherCount()-1, writer); writer.Write("] = ("); LastMatcher().DescribeTo(writer); writer.Write(")"); } } } --- NEW FILE: NotMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class NotMatcher : Matcher { private readonly Matcher negated; public NotMatcher(Matcher negated) { this.negated = negated; } public override bool Matches(object o) { return !negated.Matches(o); } public override void DescribeTo(TextWriter writer) { writer.Write("not "); negated.DescribeTo(writer); } } } --- NEW FILE: AlwaysMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class AlwaysMatcher : Matcher { private bool matches; private string description; public AlwaysMatcher(bool matches, string description) { this.matches = matches; this.description = description; } public override bool Matches(object o) { return matches; } public override void DescribeTo(TextWriter writer) { writer.Write(description); } } } --- NEW FILE: MethodNameMatcher.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: PropertyMatcher.cs --- using System; using System.IO; using System.Reflection; namespace NMock2.Matchers { public class PropertyMatcher : Matcher { private readonly string propertyName; private readonly Matcher valueMatcher; public PropertyMatcher(string propertyName, Matcher valueMatcher) { this.propertyName = propertyName; this.valueMatcher = valueMatcher; } public override bool Matches(object o) { Type type = o.GetType(); PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Public|BindingFlags.Instance); if (property == null) return false; if (!property.CanRead) return false; object value = property.GetValue(o, null); return valueMatcher.Matches(value); } public override void DescribeTo(TextWriter writer) { throw new NotImplementedException(); } } } --- NEW FILE: AndMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class AndMatcher : BinaryOperator { public AndMatcher(Matcher left, Matcher right) : base(left,right) { } public override bool Matches(object o) { return left.Matches(o) && right.Matches(o); } public override void DescribeTo(TextWriter writer) { writer.Write("`"); left.DescribeTo(writer); writer.Write("' and `"); right.DescribeTo(writer); writer.Write("'"); } } } --- NEW FILE: EqualMatcher.cs --- using System; using System.IO; namespace NMock2.Matchers { public class EqualMatcher : Matcher { private readonly object expected; public EqualMatcher(object expected) { this.expected = expected; } public override bool Matches(object actual) { return AreEqual(this.expected, actual); } private bool AreEqual(object o1, object o2) { if (o1 is Array) { return o2 is Array && ArraysEqual( (Array)o1, (Array)o2 ); } else { return Object.Equals(o1,o2); } } private bool ArraysEqual(Array a1, Array a2) { return a1.Rank == a2.Rank && ArrayLengthsEqual(a1,a2) && ArrayElementsEqual(a1,a2); } private bool ArrayLengthsEqual(Array a1, Array a2) { if (a1.Rank != a2.Rank) return false; for (int dimension = 0; dimension < a1.Rank; dimension++) { if (a1.GetLength(dimension) != a2.GetLength(dimension)) return false; } return true; } private bool ArrayElementsEqual(Array a1, Array a2) { for (int i = 0; i < a1.Length; i++) { if (!AreEqual(a1.GetValue(i), a2.GetValue(i))) return false; } return true; } public override void DescribeTo(TextWriter writer) { writer.Write("equal to "); writer.Write(expected); } } } --- NEW FILE: IndexGetterArgumentsMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class IndexGetterArgumentsMatcher : ArgumentsMatcher { public IndexGetterArgumentsMatcher(params Matcher[] valueMatchers) : base(valueMatchers) { } public override void DescribeTo(TextWriter writer) { writer.Write("["); WriteListOfMatchers(MatcherCount(), writer); writer.Write("]"); } } } --- NEW FILE: BinaryOperator.cs --- namespace NMock2.Matchers { public abstract class BinaryOperator : Matcher { protected readonly Matcher right; protected readonly Matcher left; protected BinaryOperator(Matcher left, Matcher right) { this.left = left; this.right = right; } } } --- NEW FILE: OrMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class OrMatcher : BinaryOperator { public OrMatcher(Matcher left, Matcher right) : base(left,right) { } public override bool Matches(object o) { return left.Matches(o) || right.Matches(o); } public override void DescribeTo(TextWriter writer) { writer.Write("`"); left.DescribeTo(writer); writer.Write("' or `"); right.DescribeTo(writer); writer.Write("'"); } } } --- NEW FILE: NullMatcher.cs --- using System.IO; namespace NMock2.Matchers { public class NullMatcher : Matcher { public override bool Matches(object o) { return o == null; } public override void DescribeTo(TextWriter writer) { writer.Write("null"); } } } |
Update of /cvsroot/nmock/nmock2/src/NMock2.Test In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2.Test Added Files: NMock2.Test.csproj NamedObject.cs AssertDescription.cs VerifyTest.cs .cvsignore AssemblyInfo.cs MockeryTest.cs Log Message: first upload of nmock2 --- NEW FILE: VerifyTest.cs --- using NMock2.Internal; using NUnit.Framework; namespace NMock2.Test { [TestFixture] public class VerifyTest { [Test] public void VerifyThatPassesIfMatcherMatchesValue() { object value = new NamedObject("value"); Verify.That(value, Is.Same(value)); } [Test] public void VerifyThatFailsIfMatcherDoesNotMatchValue() { object expected = new NamedObject("expected"); object actual = new NamedObject("actual"); Matcher matcher = Is.Same(expected); try { Verify.That(actual, matcher); } catch (ExpectationException e) { Assert.AreEqual( System.Environment.NewLine + "Expected: "+matcher.ToString()+System.Environment.NewLine + "Actual: <"+actual.ToString()+">", e.Message); return; } Assert.Fail("Verify.That should have failed"); } [Test] public void CanPrependCustomMessageToDescriptionOfFailure() { object expected = new NamedObject("expected"); object actual = new NamedObject("actual"); Matcher matcher = Is.Same(expected); try { Verify.That(actual, matcher, "message {0} {1}", "0", 1); } catch (ExpectationException e) { Assert.AreEqual( "message 0 1" + System.Environment.NewLine + "Expected: "+matcher.ToString()+ System.Environment.NewLine + "Actual: <"+actual.ToString()+">", e.Message); return; } Assert.Fail("Verify.That should have failed"); } } } --- NEW FILE: NamedObject.cs --- using System; namespace NMock2.Test { public class NamedObject : ICloneable { private readonly string id; private readonly int cloneId; public NamedObject(string id) : this(id, 0) { } public NamedObject(string id, int cloneId) { this.id = id; this.cloneId = cloneId; } public override string ToString() { return id + (cloneId > 0 ? " (clone " + cloneId + ")" : ""); } public object Clone() { return new NamedObject(id, cloneId+1); } } } --- NEW FILE: AssertDescription.cs --- using System; using System.IO; using NUnit.Framework; using NMock2.Internal; namespace NMock2.Test { public abstract class AssertDescription { public static void IsEqual(ISelfDescribing selfDescribing, string expectedDescription) { Assert.AreEqual(expectedDescription, DescriptionOf(selfDescribing), "description"); } private static string DescriptionOf(ISelfDescribing selfDescribing) { TextWriter writer = new DescriptionWriter(); selfDescribing.DescribeTo(writer); return writer.ToString(); } public static void IsComposed(ISelfDescribing selfDescribing, string format, params ISelfDescribing[] components) { string[] componentDescriptions = new string[components.Length]; for (int i = 0; i < components.Length; i++) { componentDescriptions[i] = DescriptionOf(components[i]); } AssertDescription.IsEqual(selfDescribing, String.Format(format, componentDescriptions)); } } } --- NEW FILE: MockeryTest.cs --- using System; using System.IO; using System.Reflection; using NUnit.Framework; using NMock2.Internal; using NMock2.Monitoring; namespace NMock2.Test { [TestFixture] public class MockeryTest { public interface IMockedType { void DoStuff(); } public interface InterfaceWithoutIPrefix { } public interface ARSEIInterfaceWithAdditionalPrefixBeforeI { } public interface INTERFACE_WITH_UPPER_CLASS_NAME { } private Mockery mockery; [SetUp] public void SetUp() { mockery = new Mockery(); } [Test] public void CreatesMocksThatCanBeCastToMockedType() { object mock = mockery.NewMock(typeof (IMockedType)); Assert.IsTrue(mock is IMockedType, "should be instance of mocked type"); } [Test] public void CreatesMocksThatCanBeCastToIMockObject() { object mock = mockery.NewMock(typeof (IMockedType)); Assert.IsTrue(mock is IMockObject, "should be instance of IMock"); } [Test] public void MockReturnsNameFromToString() { object mock = mockery.NewMock(typeof (IMockedType), "mock"); Assert.AreEqual("mock", mock.ToString()); } [Test] public void GivesMocksDefaultNameIfNoNameSpecified() { Assert.AreEqual("mockedType", mockery.NewMock(typeof (IMockedType)).ToString()); Assert.AreEqual("interfaceWithoutIPrefix", mockery.NewMock(typeof (InterfaceWithoutIPrefix)).ToString()); Assert.AreEqual("interfaceWithAdditionalPrefixBeforeI", mockery.NewMock(typeof (ARSEIInterfaceWithAdditionalPrefixBeforeI)).ToString()); Assert.AreEqual("interface_with_upper_class_name", mockery.NewMock(typeof (INTERFACE_WITH_UPPER_CLASS_NAME)).ToString()); } [Test] public void CreatedMockComparesReferenceIdentityWithEqualsMethod() { object mock1 = mockery.NewMock(typeof (IMockedType), "mock1"); object mock2 = mockery.NewMock(typeof (IMockedType), "mock2"); Assert.IsTrue(mock1.Equals(mock1), "same object should be equal"); Assert.IsFalse(mock1.Equals(mock2), "different objects should not be equal"); } [Test] public void CreatedMockReturnsNameFromToString() { object mock1 = mockery.NewMock(typeof (IMockedType), "mock1"); object mock2 = mockery.NewMock(typeof (IMockedType), "mock2"); Assert.AreEqual("mock1", mock1.ToString(), "mock1.ToString()"); Assert.AreEqual("mock2", mock2.ToString(), "mock2.ToString()"); } [Test] public void DispatchesInvocationBySearchingForMatchingExpectationInOrderOfAddition() { IMockedType mock = (IMockedType)mockery.NewMock(typeof(IMockedType),"mock"); IMockObject mockObjectControl = (IMockObject) mock; MockExpectation e1 = new MockExpectation(); MockExpectation e2 = new MockExpectation(); mockObjectControl.AddExpectation(e1); mockObjectControl.AddExpectation(e2); e2.Previous = e1; e1.ExpectedInvokedObject = e2.ExpectedInvokedObject = mock; e1.ExpectedInvokedMethod = e2.ExpectedInvokedMethod = typeof(IMockedType).GetMethod("DoStuff", new Type[0]); e1.Matches_Result = false; e2.Matches_Result = true; mock.DoStuff(); Assert.IsTrue(e1.Matches_HasBeenCalled, "should have tried to match e1"); Assert.IsFalse(e1.Perform_HasBeenCalled, "should not have performed e1"); Assert.IsTrue(e2.Matches_HasBeenCalled, "should have tried to match e2"); Assert.IsTrue(e2.Perform_HasBeenCalled, "should have performed e2"); } [Test] public void StopsSearchingForMatchingExpectationAsSoonAsOneMatches() { IMockedType mock = (IMockedType)mockery.NewMock(typeof(IMockedType),"mock"); IMockObject mockObjectControl = (IMockObject) mock; MockExpectation e1 = new MockExpectation(); MockExpectation e2 = new MockExpectation(); mockObjectControl.AddExpectation(e1); mockObjectControl.AddExpectation(e2); e2.Previous = e1; e1.ExpectedInvokedObject = e2.ExpectedInvokedObject = mock; e1.ExpectedInvokedMethod = e2.ExpectedInvokedMethod = typeof(IMockedType).GetMethod("DoStuff", new Type[0]); e1.Matches_Result = true; mock.DoStuff(); Assert.IsTrue(e1.Matches_HasBeenCalled, "should have tried to match e1"); Assert.IsTrue(e1.Perform_HasBeenCalled, "should have performed e1"); Assert.IsFalse(e2.Matches_HasBeenCalled, "should not have tried to match e2"); Assert.IsFalse(e2.Perform_HasBeenCalled, "should not have performed e2"); } [Test] public void FailsTestIfNoExpectationsMatch() { IMockedType mock = (IMockedType)mockery.NewMock(typeof(IMockedType),"mock"); IMockObject mockObjectControl = (IMockObject) mock; MockExpectation e1 = new MockExpectation(); MockExpectation e2 = new MockExpectation(); mockObjectControl.AddExpectation(e1); mockObjectControl.AddExpectation(e2); e1.Matches_Result = false; e2.Matches_Result = false; try { mock.DoStuff(); } catch(ExpectationException) { return; } Assert.Fail("expected ExpectationException"); } [Test] public void VerifiesThatAllExpectationsHaveBeenMet() { bool assertionFailed; IMockedType mock = (IMockedType)mockery.NewMock(typeof(IMockedType),"mock"); IMockObject mockObjectControl = (IMockObject) mock; MockExpectation e1 = new MockExpectation(); MockExpectation e2 = new MockExpectation(); mockObjectControl.AddExpectation(e1); mockObjectControl.AddExpectation(e2); e1.HasBeenMet = true; e2.HasBeenMet = true; mockery.VerifyAllExpectationsHaveBeenMet(); e1.HasBeenMet = true; e2.HasBeenMet = false; try { assertionFailed = false; mockery.VerifyAllExpectationsHaveBeenMet(); } catch (ExpectationException) { assertionFailed = true; } Assert.IsTrue(assertionFailed, "should have failed when e2 was not met"); e1.HasBeenMet = false; e2.HasBeenMet = true; try { assertionFailed = false; mockery.VerifyAllExpectationsHaveBeenMet(); } catch (ExpectationException) { assertionFailed = true; } Assert.IsTrue(assertionFailed, "should have failed when e1 was not met"); } [Test] public void AssertionExceptionThrownWhenSomeExpectationsHaveNotBeenMetContainsDescriptionOfUnMetExpectations() { IMockedType mock = (IMockedType)mockery.NewMock(typeof(IMockedType),"mock"); IMockObject mockObjectControl = (IMockObject) mock; MockExpectation e1 = new MockExpectation(); MockExpectation e2 = new MockExpectation(); MockExpectation e3 = new MockExpectation(); e1.Description = "e1"; e1.HasBeenMet = false; e1.IsActive = true; e2.Description = "e2"; e2.HasBeenMet = true; e2.IsActive = true; e3.Description = "e3"; e3.HasBeenMet = false; e3.IsActive = true; mockObjectControl.AddExpectation(e1); mockObjectControl.AddExpectation(e2); mockObjectControl.AddExpectation(e3); try { mockery.VerifyAllExpectationsHaveBeenMet(); } catch (ExpectationException e) { string newLine = System.Environment.NewLine; Assert.AreEqual( "not all expected invocations were performed" + newLine + "Expected:" + newLine + " e1" + newLine + " e3" + newLine, e.Message); } } [Test] public void AssertionExceptionThrownWhenNoExpectationsMatchContainsDescriptionOfActiveExpectations() { IMockedType mock = (IMockedType)mockery.NewMock(typeof(IMockedType),"mock"); IMockObject mockObjectControl = (IMockObject) mock; MockExpectation e1 = new MockExpectation(); MockExpectation e2 = new MockExpectation(); MockExpectation e3 = new MockExpectation(); e1.Description = "e1"; e1.IsActive = true; e1.Matches_Result = false; e2.IsActive = false; e2.Matches_Result = false; e3.Description = "e3"; e3.IsActive = true; e3.Matches_Result = false; mockObjectControl.AddExpectation(e1); mockObjectControl.AddExpectation(e2); mockObjectControl.AddExpectation(e3); try { mock.DoStuff(); } catch (ExpectationException e) { string newLine = System.Environment.NewLine; Assert.AreEqual( "unexpected invocation of mock.DoStuff()" + newLine + "Expected:" + newLine + " e1" + newLine + " e3" + newLine, e.Message); } } } class MockExpectation : IExpectation { public object ExpectedInvokedObject = null; public MethodInfo ExpectedInvokedMethod = null; public MockExpectation Previous; public bool Matches_Result = false; public bool Matches_HasBeenCalled = false; public bool Matches(Invocation invocation) { CheckInvocation(invocation); Assert.IsTrue(Previous == null || Previous.Matches_HasBeenCalled, "called out of order"); Matches_HasBeenCalled = true; return Matches_Result; } public bool Perform_HasBeenCalled = false; public void Perform(Invocation invocation) { CheckInvocation(invocation); Assert.IsTrue(Matches_HasBeenCalled, "Matches should have been called"); Perform_HasBeenCalled = true; } public string Description = ""; public void DescribeActiveExpectationsTo(TextWriter writer) { writer.Write(Description); } public void DescribeUnmetExpectationsTo(TextWriter writer) { writer.Write(Description); } private bool isActive_Value = false; public bool IsActive { get { return isActive_Value; } set { isActive_Value = value; } } private bool hasBeenMet_Value = false; public bool HasBeenMet { get { return hasBeenMet_Value; } set { hasBeenMet_Value = value; } } private void CheckInvocation(Invocation invocation) { Assert.IsTrue(ExpectedInvokedObject == null || ExpectedInvokedObject == invocation.Receiver, "should have received invocation on expected object"); Assert.IsTrue(ExpectedInvokedMethod == null || ExpectedInvokedMethod == invocation.Method, "should have received invocation of expected method"); } } } --- NEW FILE: NMock2.Test.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{CC6D39F7-1387-401D-9303-088D39459F36}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "NMock2.Test" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "NMock2.Test" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "..\..\build\NMock2.Test\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "..\..\build\NMock2.Test\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "NMock2" Project = "{CEE959FE-C3AF-4B51-8F1A-CCB32BAA1E98}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssertDescription.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MockeryTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NamedObject.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "VerifyTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ResultSynthesizerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ReturnActionTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ReturnCloneActionTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\SetIndexedParameterActionTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\SetNamedParameterActionTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ThrowActionTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\BuildableExpectationTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\DescriptionWriterTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\AlwaysMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\AndMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\ArgumentsMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\ComparisonMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\DescriptionOverrideTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\EqualMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\MatcherWithDescription.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\MethodNameMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\MockMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\NotMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\NullMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\OrMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\PropertyMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\SameMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\StringContainsMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\ToStringMatcherTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\InvocationSemanticsTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\InvocationTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\InvokerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\MethodInfoStub.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\MockInvokable.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\MultiInterfaceFactoryTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ParameterInfoStub.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ParameterListTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ProxiedObjectIdentityTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ProxyInvokableAdapterTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: .cvsignore --- obj NMock2.Test.csproj.user --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:58
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Monitoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2.Test/Monitoring Added Files: ProxyInvokableAdapterTest.cs InvocationTest.cs ProxiedObjectIdentityTest.cs MockInvokable.cs ParameterListTest.cs InvokerTest.cs ParameterInfoStub.cs InvocationSemanticsTest.cs MultiInterfaceFactoryTest.cs MethodInfoStub.cs Log Message: first upload of nmock2 --- NEW FILE: MethodInfoStub.cs --- using System; using System.Globalization; using System.Reflection; namespace NMock2.Test.Monitoring { public class MethodInfoStub : MethodInfo { private readonly string name; private ParameterInfo[] parameters; public MethodInfoStub( string name, params ParameterInfo[] parameters ) { this.name = name; this.parameters = parameters; } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override string Name { get { return name; } } public override Type DeclaringType { get { throw new NotImplementedException(); } } public override ParameterInfo[] GetParameters() { return parameters; } public override MethodImplAttributes GetMethodImplementationFlags() { throw new NotImplementedException(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotImplementedException(); } public override RuntimeMethodHandle MethodHandle { get { throw new NotImplementedException(); } } public override MethodInfo GetBaseDefinition() { throw new NotImplementedException(); } public Type StubReturnType = typeof(object); public override Type ReturnType { get { return StubReturnType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotImplementedException(); } } public override MethodAttributes Attributes { get { throw new NotImplementedException(); } } public override Type ReflectedType { get { throw new NotImplementedException(); } } } } --- NEW FILE: InvocationTest.cs --- using System; using System.Reflection; using NUnit.Framework; using NMock2.Monitoring; namespace NMock2.Test.Monitoring { [TestFixture] public class InvocationTest { object receiver; MethodInfoStub method; Invocation invocation; object result; Exception exception; [SetUp] public void SetUp() { receiver = "receiver"; result = "result"; method = new MethodInfoStub("method"); invocation = new Invocation(receiver,method,new object[0]); exception = new Exception(); } [Test] public void StoresResultToReturn() { invocation.Result = result; Assert.AreSame(result, invocation.Result, "should store result"); Assert.IsFalse(invocation.IsThrowing, "should not be throwing"); Assert.IsNull(invocation.Exception, "should not store an exception"); } [Test] public void StoresExceptionToThrow() { invocation.Exception = exception; Assert.AreSame(exception, invocation.Exception, "should store exception"); Assert.IsTrue(invocation.IsThrowing, "should be throwing"); Assert.IsNull(invocation.Result, "should not store a result"); } [Test] public void SettingResultClearsException() { invocation.Exception = exception; invocation.Result = result; Assert.AreSame(result, invocation.Result, "should store result"); Assert.IsFalse(invocation.IsThrowing, "should not be throwing"); Assert.IsNull(invocation.Exception, "should not store an exception"); } [Test] public void SettingExceptionClearsResult() { invocation.Result = result; invocation.Exception = exception; Assert.AreSame(exception, invocation.Exception, "should store exception"); Assert.IsTrue(invocation.IsThrowing, "should be throwing"); Assert.IsNull(invocation.Result, "should not store a result"); } [Test, ExpectedException(typeof(ArgumentNullException))] public void DoesNotAllowNullException() { invocation.Exception = null; } [Test, ExpectedException(typeof(ArgumentException))] public void DoesNotAllowSettingNonNullResultOfVoidMethod() { method.StubReturnType = typeof(void); invocation.Result = "some value"; } [Test] public void AllowsSettingNullResultOfVoidMethod() { method.StubReturnType = typeof(void); invocation.Result = null; } [Test, ExpectedException(typeof(ArgumentException))] public void DoesNotAllowNullResultForMethodThatReturnsAValueType() { method.StubReturnType = typeof(int); invocation.Result = null; } public class A {} public class B: A {} public class C {} [Test] public void DoesNotAllowSettingIncompatibleResultType() { method.StubReturnType = typeof(A); invocation.Result = new B(); try { invocation.Result = new C(); Assert.Fail("expected ArgumentException"); } catch(ArgumentException) { //expected } } public interface IFoo { string Foo(string input, out string output); } public static readonly MethodInfo FOO_METHOD = typeof(IFoo).GetMethod("Foo"); public class MockFoo : IFoo { public bool FooWasInvoked = false; public string Foo_ExpectedInput; public string Foo_Output = "output"; public string Foo_Result; public Exception Foo_Exception = null; public string Foo(string input, out string output) { FooWasInvoked = true; Assert.AreEqual(Foo_ExpectedInput, input, "input"); if (Foo_Exception != null) { throw Foo_Exception; } else { output = Foo_Output; return Foo_Result; } } } [Test] public void CanBeInvokedOnAnotherObject() { string input = "INPUT"; string output = "OUTPUT"; string result = "RESULT"; invocation = new Invocation(receiver, FOO_METHOD, new object[]{input, null}); MockFoo mockFoo = new MockFoo(); mockFoo.Foo_ExpectedInput = input; mockFoo.Foo_Output = output; mockFoo.Foo_Result = result; invocation.InvokeOn(mockFoo); Assert.IsTrue(mockFoo.FooWasInvoked, "Foo should have been invoked"); Assert.AreEqual(invocation.Result, result, "result"); Assert.AreEqual(invocation.Parameters[1], output, "output"); } [Test] public void TrapsExceptionsWhenInvokedOnAnotherObject() { Exception exception = new Exception("thrown from Foo"); invocation = new Invocation(receiver, FOO_METHOD, new object[]{"input",null}); MockFoo mockFoo = new MockFoo(); mockFoo.Foo_ExpectedInput = "input"; mockFoo.Foo_Exception = exception; invocation.InvokeOn(mockFoo); Assert.IsTrue(mockFoo.FooWasInvoked, "Foo should have been invoked"); Assert.AreSame(exception, invocation.Exception, "exception"); } public interface SugarMethods { int Property { get; set; } int this[string s, int i] { get; set; } event EventHandler Event; } private void HandleEvent(object sender, EventArgs args) { } [Test] public void DescriptionOfInvocationOfPropertyGetterDoesNotShowSugaredMethod() { MethodInfo getter = typeof(SugarMethods).GetMethod("get_Property", new Type[0]); invocation = new Invocation(receiver, getter, new object[0]); AssertDescription.IsEqual(invocation, "receiver.Property"); } [Test] public void DescriptionOfInvocationOfPropertySetterDoesNotShowSugaredMethod() { MethodInfo setter = typeof(SugarMethods).GetMethod("set_Property", new Type[] { typeof(int) }); invocation = new Invocation(receiver, setter, new object[] { 10 }); AssertDescription.IsEqual(invocation, "receiver.Property = <10>"); } [Test] public void DescriptionOfInvocationOfIndexerGetterDoesNotShowSugaredMethod() { MethodInfo getter = typeof(SugarMethods).GetMethod( "get_Item", new Type[]{typeof(string), typeof(int)}); invocation = new Invocation(receiver, getter, new object[]{"hello", 10}); AssertDescription.IsEqual(invocation, "receiver[\"hello\", <10>]"); } [Test] public void DescriptionOfInvocationOfIndexerSetterDoesNotShowSugaredMethod() { MethodInfo getter = typeof(SugarMethods).GetMethod( "set_Item", new Type[]{typeof(string), typeof(int), typeof(int)}); invocation = new Invocation(receiver, getter, new object[]{"hello", 10, 11}); AssertDescription.IsEqual(invocation, "receiver[\"hello\", <10>] = <11>"); } [Test] public void DescriptionOfEventAdderDoesNotShowSugaredMethod() { MethodInfo adder = typeof(SugarMethods).GetMethod( "add_Event", new Type[]{typeof(EventHandler)} ); Delegate handler = new EventHandler(HandleEvent); invocation = new Invocation(receiver, adder, new object[]{handler}); AssertDescription.IsEqual(invocation, "receiver += <System.EventHandler>"); } [Test] public void DescriptionOfEventRemoverDoesNotShowSugaredMethod() { MethodInfo adder = typeof(SugarMethods).GetMethod( "remove_Event", new Type[]{typeof(EventHandler)} ); Delegate handler = new EventHandler(HandleEvent); invocation = new Invocation(receiver, adder, new object[]{handler}); AssertDescription.IsEqual(invocation, "receiver -= <System.EventHandler>"); } } } --- NEW FILE: ParameterInfoStub.cs --- using System.Reflection; namespace NMock2.Test.Monitoring { public class ParameterInfoStub : ParameterInfo { public ParameterInfoStub( string name, ParameterAttributes attributes ) { this.NameImpl = name; this.AttrsImpl = attributes; } } } --- NEW FILE: ProxyInvokableAdapterTest.cs --- using System; using System.Reflection; using NUnit.Framework; using NMock2.Monitoring; namespace NMock2.Test.Monitoring { public interface ProxiedInterface { string Return(); void Throw(); void InOut( string inArg, ref string refArg, out string outArg ); } [TestFixture] public class ProxyInvokableAdapterTest { static readonly MethodInfo RETURN_METHOD = typeof(ProxiedInterface).GetMethod("Return"); static readonly MethodInfo INOUT_METHOD = typeof(ProxiedInterface).GetMethod("InOut"); MockInvokable invokable; ProxyInvokableAdapter adapter; ProxiedInterface transparentProxy; [SetUp] public void SetUp() { invokable = new MockInvokable(); adapter = new ProxyInvokableAdapter( typeof(ProxiedInterface), invokable ); transparentProxy = (ProxiedInterface)adapter.GetTransparentProxy(); } [Test] public void CapturesInvocationsOnTransparentProxyAndForwardsToInvokableObject() { invokable.Expected = new Invocation( transparentProxy, RETURN_METHOD, new object[0] ); transparentProxy.Return(); Assert.IsNotNull(invokable.Actual, "received invocation"); } [Test] public void ReturnsResultFromInvocationToCallerOfProxy() { invokable.ResultSetOnInvocation = "result"; Assert.AreEqual( invokable.ResultSetOnInvocation, transparentProxy.Return() ); } class TestException : Exception {} [Test, ExpectedException(typeof(TestException))] public void ThrowsExceptionFromInvocationToCallerOfProxy() { invokable.ExceptionSetOnInvocation = new TestException(); transparentProxy.Throw(); } [Test] public void ReturnsOutAndRefParametersFromInvocationToCallerOfProxy() { invokable.Expected = new Invocation(transparentProxy,INOUT_METHOD,new object[]{"inArg","refArg",null}); invokable.Outputs = new object[]{null, "returnedRefArg", "returnedOutArg"}; string refArg = "refArg"; string outArg; transparentProxy.InOut("inArg", ref refArg, out outArg); Assert.AreEqual("returnedRefArg", refArg); Assert.AreEqual("returnedOutArg", outArg); } [Test, ExpectedException(typeof(TestException))] public void PassesExceptionThrownByInvokableToCallerOfProxy() { invokable.ThrownException = new TestException(); transparentProxy.Throw(); } } } --- NEW FILE: MockInvokable.cs --- using System; using NUnit.Framework; using NMock2.Monitoring; namespace NMock2.Test.Monitoring { public class MockInvokable : IInvokable { public Invocation Expected; public Invocation Actual; public object[] Outputs; public object ResultSetOnInvocation = null; public Exception ExceptionSetOnInvocation = null; public Exception ThrownException = null; public bool expectNotCalled = false; public void ExpectNotCalled() { this.expectNotCalled = true; } public void Invoke(Invocation invocation) { Assert.IsFalse(expectNotCalled, "MockInvokable should not have been invoked"); Actual = invocation; if (Expected != null) Assert.AreEqual( Expected.Method, Actual.Method, "method"); if (Outputs != null) { for (int i = 0; i < Actual.Parameters.Count; i++) { if (!Actual.Method.GetParameters()[i].IsIn) { Actual.Parameters[i] = Outputs[i]; } } } if (ThrownException != null) throw ThrownException; if (ExceptionSetOnInvocation != null) { invocation.Exception = ExceptionSetOnInvocation; } else if(invocation.Method.ReturnType != typeof(void)) { invocation.Result = ResultSetOnInvocation; } } } } --- NEW FILE: InvokerTest.cs --- using System.Reflection; using NUnit.Framework; using NMock2.Monitoring; using NMock2.Test.Monitoring; namespace NMock2.Test.Monitoring { [TestFixture] public class InvokerTest { public interface IFoo { void Foo(); } public interface IOther { void Other(); } public class MockFoo : IFoo { public bool FooWasInvoked = false; public void Foo() { FooWasInvoked = true; } } public static readonly MethodInfo FOO_METHOD = typeof(IFoo).GetMethod("Foo"); public static readonly MethodInfo OTHER_METHOD = typeof(IOther).GetMethod("Other"); private object receiver; private MockFoo target; private MockInvokable next; private Invoker invoker; [SetUp] public void SetUp() { receiver = new object(); target = new MockFoo(); next = new MockInvokable(); invoker = new Invoker(typeof(IFoo), this.target, this.next); } [Test] public void InvokesMethodOnObjectIfMethodIsDeclaredInSpecifiedType() { Invocation invocation = new Invocation(receiver, FOO_METHOD, new object[0]); invoker.Invoke(invocation); Assert.IsTrue(target.FooWasInvoked, "Foo should have been invoked on target"); } [Test] public void ForwardsInvocationsToNextIfMethodIsNotDeclaredInSpecifiedType() { Invocation invocation = new Invocation(receiver, OTHER_METHOD, new object[0]); next.Expected = invocation; invoker.Invoke(invocation); Assert.IsFalse(target.FooWasInvoked, "should not have invoked method on target"); Assert.AreSame(invocation, next.Actual, "should have passed invocation to next in chain"); } } } --- NEW FILE: ParameterListTest.cs --- using System; using System.Reflection; using NUnit.Framework; using NMock2.Monitoring; namespace NMock2.Test.Monitoring { [TestFixture] public class ParameterListTest { static readonly object inValue = "inValue"; static readonly object refValue = "refValue"; const int IN_PARAMETER_INDEX = 0; const int REF_PARAMETER_INDEX = 1; const int OUT_PARAMETER_INDEX = 2; MethodInfo method; object[] parameterValues; ParameterList list; [SetUp] public void SetUp() { ParameterInfo inParam = new ParameterInfoStub("inParam", ParameterAttributes.In); ParameterInfo refParam = new ParameterInfoStub("refParam", ParameterAttributes.None); ParameterInfo outParam = new ParameterInfoStub("outParam", ParameterAttributes.Out); method = new MethodInfoStub("method", inParam, refParam, outParam); parameterValues = new object[]{inValue, refValue, null}; list = new ParameterList(method, parameterValues); } [Test] public void ReturnsNumberOfParameters() { Assert.AreEqual( parameterValues.Length, list.Count, "size" ); } [Test] public void ReturnsValuesOfInParameters() { Assert.IsTrue(list.IsValueSet(IN_PARAMETER_INDEX), "in parameter should be set"); Assert.AreSame(inValue, list[IN_PARAMETER_INDEX], "in value"); Assert.IsTrue(list.IsValueSet(REF_PARAMETER_INDEX), "ref parameter should be set"); Assert.AreSame(refValue, list[REF_PARAMETER_INDEX], "ref value"); } [Test, ExpectedException(typeof(InvalidOperationException))] public void DoesNotAllowAccessToValuesOfUnsetOutParameters() { Assert.IsFalse(list.IsValueSet(OUT_PARAMETER_INDEX), "out parameter is not set"); Ignore( list[OUT_PARAMETER_INDEX] ); } [Test] public void CanSetValuesOfOutAndRefParameters() { object newRefValue = "newRefValue"; object outValue = "outValue"; list[REF_PARAMETER_INDEX] = newRefValue; list[OUT_PARAMETER_INDEX] = outValue; Assert.AreSame(newRefValue, list[REF_PARAMETER_INDEX], "new ref value"); Assert.IsTrue(list.IsValueSet(OUT_PARAMETER_INDEX), "out parameter is set"); Assert.AreSame(outValue, list[OUT_PARAMETER_INDEX], "out value"); } [Test, ExpectedException(typeof(InvalidOperationException))] public void DoesNotAllowValuesOfInputParametersToBeChanged() { object newValue = "newValue"; list[IN_PARAMETER_INDEX] = newValue; } private void Ignore(object o) { // The things you have to do to ignore compiler warnings! object o2 = o; o = o2; } } } --- NEW FILE: ProxiedObjectIdentityTest.cs --- using System; using System.Reflection; using NUnit.Framework; using NMock2.Monitoring; using NMock2.Test.Monitoring; namespace NMock2.Test.Monitoring { [TestFixture] public class ProxiedObjectIdentityTest { private static readonly MethodInfo EQUALS_METHOD = typeof(object).GetMethod("Equals",new Type[]{typeof(object)}); private static readonly MethodInfo TOSRING_METHOD = typeof(object).GetMethod("ToString",new Type[0]); private static readonly MethodInfo GETHASHCODE_METHOD = typeof(object).GetMethod("GetHashCode",new Type[0]); private object receiver; private object identityProvider; private MockInvokable next; private IInvokable id; [SetUp] public void SetUp() { receiver = new NamedObject("receiver"); identityProvider = new NamedObject("identityProvider"); next = new MockInvokable(); id = new ProxiedObjectIdentity(identityProvider, next); } [Test] public void ImplementsEqualsByComparingInvocationReceiversForIdentity() { next.ExpectNotCalled(); Invocation equalInvocation = new Invocation(receiver, EQUALS_METHOD, new object[]{receiver}); id.Invoke(equalInvocation); Assert.IsTrue((bool)equalInvocation.Result, "should have returned true"); object other = new NamedObject("other"); Invocation notEqualInvocation = new Invocation(receiver, EQUALS_METHOD, new object[]{other}); id.Invoke(notEqualInvocation); Assert.IsFalse((bool)notEqualInvocation.Result, "should not have returned true"); } [Test] public void ForwardsToStringToIdentityProvider() { Invocation toStringInvocation = new Invocation(receiver, TOSRING_METHOD, new object[0]); id.Invoke(toStringInvocation); Assert.AreEqual(identityProvider.ToString(), toStringInvocation.Result, "ToString()"); } [Test] public void ForwardsGetHashCodeToIdentityProvider() { Invocation getHashCodeInvocation = new Invocation(receiver, GETHASHCODE_METHOD, new object[0]); id.Invoke(getHashCodeInvocation); Assert.AreEqual(identityProvider.GetHashCode(), getHashCodeInvocation.Result, "GetHashCode()"); } [Test] public void ForwardsInvocationsOfOtherMethodsToNextInChain() { Invocation invocation = new Invocation(receiver, typeof(ICloneable).GetMethod("Clone"), new object[0]); id.Invoke(invocation); Assert.AreSame(invocation, next.Actual, "should have forwarded invocation to next in chain"); } } } --- NEW FILE: InvocationSemanticsTest.cs --- using System; using NUnit.Framework; namespace NMock2.Test.Monitoring { [TestFixture] public class InvocationSemanticsTest { const int REF_PARAM_VALUE = 1; const int OUT_PARAM_VALUE = 2; [Test] public void OutParametersAreSetAfterExceptionThrown() { int refParam = 0; int outParam = 0; try { SetAndThrow(ref refParam, out outParam); } catch( TestException ) { } Assert.AreEqual( REF_PARAM_VALUE, refParam ); Assert.AreEqual( OUT_PARAM_VALUE, outParam ); } public void SetAndThrow( ref int refParam, out int outParam ) { refParam = REF_PARAM_VALUE; outParam = OUT_PARAM_VALUE; throw new TestException(); } } internal class TestException : ApplicationException { } } --- NEW FILE: MultiInterfaceFactoryTest.cs --- using System; using NUnit.Framework; using NMock2.Monitoring; namespace NMock2.Test.Monitoring { public interface A {} public interface B {} public interface C {} public interface A_B {} [TestFixture] public class MultiInterfaceFactoryTest { MultiInterfaceFactory factory; [SetUp] public void SetUp() { factory = new MultiInterfaceFactory("TestedMultiInterfaceFactory"); } [Test] public void CreatesTypeInfoObjectsThatRepresentAnInterfaceThatExtendsAllParameterInterfaces() { Type newType = factory.GetType(typeof(A),typeof(B),typeof(C)); Assert.IsTrue( typeof(A).IsAssignableFrom(newType), "new type is an A"); Assert.IsTrue( typeof(B).IsAssignableFrom(newType), "new type is an B"); Assert.IsTrue( typeof(C).IsAssignableFrom(newType), "new type is an C"); } [Test] public void ReturnsTheSameTypeWhenPassedTheSameArguments() { Type type = factory.GetType(typeof(A),typeof(B)); Type sameType = factory.GetType(typeof(A),typeof(B)); Type otherType = factory.GetType(typeof(A),typeof(C)); Assert.IsTrue( type == sameType, "should be same type"); Assert.IsTrue( type != otherType, "should be different type"); } [Test] public void ReturnsTheSameTypeWhenPassedTheSameArgumentsInDifferentOrder() { Type type = factory.GetType(typeof(A),typeof(B)); Type sameType = factory.GetType(typeof(B),typeof(A)); Assert.IsTrue( type == sameType, "should be same type"); } [Test] public void AvoidsNameClash() { Type type = factory.GetType(typeof(A), typeof(B), typeof(C)); Type otherType = factory.GetType(typeof(A_B), typeof(C)); Assert.IsTrue(type != otherType, "types should be different"); } } } |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:58
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Actions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2.Test/Actions Added Files: SetNamedParameterActionTest.cs ReturnCloneActionTest.cs SetIndexedParameterActionTest.cs ResultSynthesizerTest.cs ThrowActionTest.cs ReturnActionTest.cs Log Message: first upload of nmock2 --- NEW FILE: SetNamedParameterActionTest.cs --- using System.Reflection; using NUnit.Framework; using NMock2.Actions; using NMock2.Monitoring; using NMock2.Test.Monitoring; namespace NMock2.Test.Actions { [TestFixture] public class SetNamedParameterActionTest { [Test] public void SetsNamedParameterOnInvocation() { object receiver = new object(); MethodInfoStub methodInfo = new MethodInfoStub("method", new ParameterInfoStub("p1",ParameterAttributes.In), new ParameterInfoStub("p2",ParameterAttributes.Out)); string name = "p2"; object value = new object(); Invocation invocation = new Invocation(receiver, methodInfo, new object[]{null,null}); SetNamedParameterAction action = new SetNamedParameterAction(name,value); action.Invoke(invocation); Assert.AreSame( value, invocation.Parameters[1], "set value" ); } [Test] public void HasReadableDescription() { string name = "param"; object value = new NamedObject("value"); SetNamedParameterAction action = new SetNamedParameterAction(name,value); AssertDescription.IsEqual(action, "set param=<value>"); } } } --- NEW FILE: ResultSynthesizerTest.cs --- using System; using System.Collections; using System.IO; using System.Reflection; using NMock2.Actions; using NMock2.Monitoring; using NMock2.Test.Monitoring; using NUnit.Framework; namespace NMock2.Test.Actions { [TestFixture] public class ResultSynthesizerTest { [Test] public void CreatesDefaultValuesForBasicTypes() { ResultSynthesizer synth = new ResultSynthesizer(); AssertReturnsValue(synth, typeof(bool), false); AssertReturnsValue(synth, typeof(byte), (byte)0); AssertReturnsValue(synth, typeof(sbyte), (sbyte)0); AssertReturnsValue(synth, typeof(short), (short)0); AssertReturnsValue(synth, typeof(ushort), (ushort)0U); AssertReturnsValue(synth, typeof(int), 0); AssertReturnsValue(synth, typeof(uint), 0U); AssertReturnsValue(synth, typeof(long), 0L); AssertReturnsValue(synth, typeof(ulong), 0UL); AssertReturnsValue(synth, typeof(char), '\0'); AssertReturnsValue(synth, typeof(string), ""); } [Test] public void DoesNotTryToSetResultForVoidReturnType() { ResultSynthesizer synth = new ResultSynthesizer(); AssertReturnsValue(synth, typeof(void), Is.Null); } [Test] public void CanOverrideDefaultResultForType() { ResultSynthesizer synth = new ResultSynthesizer(); string newResult = "new result"; synth.SetResult(typeof(string), newResult); AssertReturnsValue(synth, typeof(string), newResult); } [Test] public void ReturnsZeroLengthArrays() { ResultSynthesizer synth = new ResultSynthesizer(); AssertReturnsValue(synth, typeof(int[]), new int[0]); AssertReturnsValue(synth, typeof(string[]), new string[0]); AssertReturnsValue(synth, typeof(object[]), new object[0]); } [Test] public void ReturnsEmptyCollections() { ResultSynthesizer synth = new ResultSynthesizer(); AssertReturnsValue(synth, typeof(ArrayList), IsAnEmpty(typeof(ArrayList))); AssertReturnsValue(synth, typeof(SortedList), IsAnEmpty(typeof(SortedList))); AssertReturnsValue(synth, typeof(Hashtable), IsAnEmpty(typeof(Hashtable))); AssertReturnsValue(synth, typeof(Stack), IsAnEmpty(typeof(Stack))); AssertReturnsValue(synth, typeof(Queue), IsAnEmpty(typeof(Queue))); } [Test] public void ReturnsADifferentCollectionOnEachInvocation() { ResultSynthesizer synth = new ResultSynthesizer(); ArrayList list = (ArrayList) ValueReturnedForType(synth, typeof(ArrayList)); list.Add("a new element"); AssertReturnsValue(synth, typeof(ArrayList), IsAnEmpty(typeof(ArrayList))); } [Test] public void CanSpecifyResultForOtherType() { ResultSynthesizer synth = new ResultSynthesizer(); NamedObject value = new NamedObject("value"); synth.SetResult( typeof(NamedObject), value); AssertReturnsValue(synth, typeof(NamedObject), value); } public struct AValueType { public int value1, value2; } [Test] public void ReturnsDefaultValueOfValueTypes() { ResultSynthesizer synth = new ResultSynthesizer(); AssertReturnsValue(synth, typeof(DateTime), new DateTime()); AssertReturnsValue(synth, typeof(AValueType), new AValueType()); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ThrowsExceptionIfTriesToReturnValueForUnsupportedResultType() { ResultSynthesizer synth = new ResultSynthesizer(); AssertReturnsValue(synth, typeof(NamedObject), Is.Nothing); } private Matcher IsAnEmpty(Type type) { return new IsEmptyCollectionMatcher(type); } private class IsEmptyCollectionMatcher : Matcher { private Type collectionType; public IsEmptyCollectionMatcher(Type collectionType) { if (!typeof(ICollection).IsAssignableFrom(collectionType)) { throw new ArgumentException(collectionType.FullName + " is not derived from ICollection"); } this.collectionType = collectionType; } public override bool Matches(object o) { return collectionType.IsInstanceOfType(o) && ((ICollection)o).Count == 0; } public override void DescribeTo(TextWriter writer) { writer.Write("an empty " + collectionType.Name); } } static readonly object RECEIVER = new NamedObject("receiver"); private void AssertReturnsValue(IAction action, Type returnType, object expectedResult) { AssertReturnsValue(action, returnType, Is.EqualTo(expectedResult)); } private void AssertReturnsValue(IAction action, Type returnType, Matcher resultMatcher) { Verify.That( ValueReturnedForType(action, returnType), resultMatcher, "result for type "+returnType ); } private static object ValueReturnedForType(IAction action, Type returnType) { MethodInfoStub method = new MethodInfoStub("method", new ParameterInfo[0]); method.StubReturnType = returnType; Invocation invocation = new Invocation(RECEIVER, method, new object[0]); action.Invoke(invocation); return invocation.Result; } } } --- NEW FILE: ReturnActionTest.cs --- using NUnit.Framework; using NMock2.Actions; using NMock2.Monitoring; using NMock2.Test.Monitoring; namespace NMock2.Test.Actions { [TestFixture] public class ReturnActionTest { [Test] public void SetsReturnValueOfInvocation() { object result = new NamedObject("result"); ReturnAction action = new ReturnAction(result); Assert.AreSame( result, ResultOfAction(action), "result" ); } [Test] public void HasAReadableDescription() { object result = new NamedObject("result"); ReturnAction action = new ReturnAction(result); AssertDescription.IsEqual(action, "return <result>"); } public static object ResultOfAction(IAction action) { object receiver = new NamedObject("receiver"); MethodInfoStub methodInfo = new MethodInfoStub("method"); Invocation invocation = new Invocation(receiver, methodInfo, new object[0]); action.Invoke(invocation); return invocation.Result; } } } --- NEW FILE: ThrowActionTest.cs --- using System; using NUnit.Framework; using NMock2.Actions; using NMock2.Monitoring; using NMock2.Test.Monitoring; namespace NMock2.Test.Actions { [TestFixture] public class ThrowActionTest { [Test] public void SetsExceptionOfInvocation() { Exception exception = new Exception(); ThrowAction action = new ThrowAction(exception); object receiver = new object(); MethodInfoStub methodInfo = new MethodInfoStub("method"); Invocation invocation = new Invocation(receiver, methodInfo, new object[0]); action.Invoke(invocation); Assert.AreSame( exception, invocation.Exception, "exception" ); } [Test] public void HasReadableDescription() { Exception exception = new Exception(); ThrowAction action = new ThrowAction(exception); AssertDescription.IsEqual(action, "throw <"+exception.ToString()+">"); } } } --- NEW FILE: SetIndexedParameterActionTest.cs --- using System.Reflection; using NMock2.Actions; using NMock2.Monitoring; using NMock2.Test.Monitoring; using NUnit.Framework; namespace NMock2.Test.Actions { [TestFixture] public class SetIndexedParameterActionTest { [Test] public void SetsIndexedParameterOnInvocation() { object receiver = new object(); MethodInfoStub methodInfo = new MethodInfoStub("method", new ParameterInfoStub("p1",ParameterAttributes.In), new ParameterInfoStub("p2",ParameterAttributes.Out)); int index = 1; object value = new object(); Invocation invocation = new Invocation(receiver, methodInfo, new object[]{null,null}); SetIndexedParameterAction action = new SetIndexedParameterAction(index,value); action.Invoke(invocation); Assert.AreSame( value, invocation.Parameters[index], "set value" ); } [Test] public void HasReadableDescription() { int index = 1; object value = new NamedObject("value"); SetIndexedParameterAction action = new SetIndexedParameterAction(index,value); AssertDescription.IsEqual(action, "set arg 1=<value>"); } } } --- NEW FILE: ReturnCloneActionTest.cs --- using System; using NMock2.Actions; using NUnit.Framework; namespace NMock2.Test.Actions { [TestFixture] public class ReturnCloneActionTest { [Test] public void ReturnsCloneOfPrototypeObject() { ICloneable prototype = ACloneableObject(); IAction action = new ReturnCloneAction(prototype); object result = ReturnActionTest.ResultOfAction(action); Verify.That(result, !Is.Same(prototype)); } [Test] public void HasAReadableDescription() { ICloneable prototype = ACloneableObject(); AssertDescription.IsEqual(new ReturnCloneAction(prototype), "a clone of <"+prototype+">"); } #region Unimportant test definitions private ICloneable ACloneableObject() { return new NamedObject("a cloneable object"); } #endregion } } |
Update of /cvsroot/nmock/nmock2/src/NMock2.AcceptanceTests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2.AcceptanceTests Added Files: .cvsignore PropertiesAcceptanceTest.cs IHelloWorld.cs ErrorCheckingAcceptanceTest.cs EventsAcceptanceTest.cs OrderedCallsAcceptanceTest.cs StubAcceptanceTest.cs AssemblyInfo.cs ExpectationsAcceptanceTest.cs IndexersAcceptanceTest.cs UsingBlockAcceptanceTest.cs Example.cs NMock2.AcceptanceTests.csproj ErrorMessageDemo.cs Log Message: first upload of nmock2 --- NEW FILE: .cvsignore --- obj NMock2.AcceptanceTests.csproj.user --- NEW FILE: Example.cs --- using NUnit.Framework; namespace NMock2.AcceptanceTests { public delegate void WhoIsThereResponse(); public delegate void WhoResponse(string firstName); public interface IKnockKnock { void KnockKnock(IJoker joker); void TellFirstName(IJoker joker, string firstName); void TellPunchline(IJoker joker, string punchline); } public interface IJoker { void Respond(string response); void Ha(); void Hee(); void Ho(); } public class Audience : IKnockKnock { public void KnockKnock(IJoker joker) { joker.Respond("Who's there?"); } public void TellFirstName(IJoker joker, string firstName) { joker.Respond(firstName + ", who?"); } public void TellPunchline(IJoker joker, string punchLine) { joker.Ha(); joker.Ha(); joker.Hee(); joker.Ho(); joker.Ho(); joker.Hee(); joker.Hee(); } } [TestFixture] public class Example { [Test] public void KnockKnockJoke() { Mockery mocks = new Mockery(); const string firstName = "Doctor"; const string punchline = "How did you know?"; IJoker joker = (IJoker)mocks.NewMock(typeof(IJoker), "joker"); Audience audience = new Audience(); using (mocks.Ordered) { Expect.Once.On(joker).Method("Respond").With(Is.EqualTo("Who's there?")); Expect.Once.On(joker).Method("Respond").With(Is.StringContaining(firstName) & Is.StringContaining("who?")); using (mocks.Unordered) { Expect.AtLeastOnce.On(joker).Method("Ha"); Expect.AtLeastOnce.On(joker).Method("Ho"); Expect.AtLeastOnce.On(joker).Method("Hee"); } } audience.KnockKnock(joker); audience.TellFirstName(joker, firstName); audience.TellPunchline(joker, punchline); mocks.VerifyAllExpectationsHaveBeenMet(); } } } --- NEW FILE: NMock2.AcceptanceTests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{B4EED566-0F75-443F-9990-FBD7E489B9BD}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "NMock2.AcceptanceTests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "NMock2.AcceptanceTests" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "..\..\build\NMock2.AcceptanceTests\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "..\..\build\NMock2.AcceptanceTests\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "NMock2" Project = "{CEE959FE-C3AF-4B51-8F1A-CCB32BAA1E98}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ErrorCheckingAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ErrorMessageDemo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "EventsAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Example.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ExpectationsAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IHelloWorld.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IndexersAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "OrderedCallsAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "PropertiesAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "StubAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "UsingBlockAcceptanceTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: ExpectationsAcceptanceTest.cs --- using NMock2.Internal; using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class ExpectationsAcceptanceTest { [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodExpectedOnceButNotCalled() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Once.On(helloWorld).Method("Hello").WithNoArguments(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void PassesTestIfMethodExpectedOnceAndCalled() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Once.On(helloWorld).Method("Hello").WithNoArguments(); helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodExpectedOnceButCalledTwice() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Once.On(helloWorld).Method("Hello").WithNoArguments(); helloWorld.Hello(); helloWorld.Hello(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodExpectedAtLeastNTimesButCalledLessThanNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.AtLeast(N).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N-1; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void PassesTestIfMethodExpectedAtLeastNTimesAndCalledNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.AtLeast(N).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void PassesTestIfMethodExpectedAtLeastNTimesAndCalledMoreThanNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.AtLeast(N).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N+1; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void PassesTestIfMethodExpectedAtMostNTimesButCalledMoreThanNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.AtMost(N).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N-1; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void PassesTestIfMethodExpectedAtMostNTimesAndCalledNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.AtMost(N).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodExpectedAtMostNTimesAndCalledMoreThanNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.AtMost(N).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N+1; i++) helloWorld.Hello(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodExpectedBetweenNAndMTimesButCalledLessThanNTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Between(N,M).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < N-1; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodExpectedBetweenNAndMTimesAndCalledMoreThanMTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Between(N,M).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < M; i++) helloWorld.Hello(); helloWorld.Hello(); } [Test] public void PassesTestIfMethodExpectedBetweenNAndMTimesAndCalledBetweenNAndMTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Between(N,M).On(helloWorld).Method("Hello").WithNoArguments(); for (int i = 0; i < (N+M)/2; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodNeverExpectedIsCalled() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Never.On(helloWorld).Method("Hello").WithNoArguments(); helloWorld.Hello(); } [Test] public void PassesTestIfMethodNeverExpectedIsNeverCalled() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Never.On(helloWorld).Method("Hello").WithNoArguments(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void FailsTestIfMethodNeverExpectedIsActuallyCalled() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Never.On(helloWorld).Method("Hello").WithNoArguments(); helloWorld.Hello(); } #region Really boring stuff #region It really is boring stuff const int N = 2; const int M = 4; #endregion #endregion } } --- NEW FILE: IndexersAcceptanceTest.cs --- using System; using NMock2.Internal; using NUnit.Framework; namespace NMock2.AcceptanceTests { interface Indexed { string this[string s, string t] { get; set; } } [TestFixture] public class IndexersAcceptanceTest { [Test] public void CanExpectIndexedGetter() { Mockery mocks = new Mockery(); Indexed indexed = (Indexed) mocks.NewMock(typeof(Indexed)); Stub.On(indexed).Get["Bill","Gates"].Will(Return.Value("Microsoft")); Stub.On(indexed).Get["Steve","Jobs"].Will(Return.Value("Apple")); Assert.AreEqual("Microsoft", indexed["Bill","Gates"], "Bill, Gates"); Assert.AreEqual("Apple", indexed["Steve","Jobs"], "Steve, Jobs"); } [Test] public void CanExpectIndexedSetter() { Mockery mocks = new Mockery(); Indexed indexed = (Indexed)mocks.NewMock(typeof(Indexed)); Expect.Once.On(indexed).Set["Bill","Gates"].To("Microsoft"); indexed["Bill","Gates"] = "Microsoft"; mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void ErrorMessagesContainNameOfIndexedGetterNotHiddenMethod() { Mockery mocks = new Mockery(); Indexed indexed = (Indexed) mocks.NewMock(typeof(Indexed)); Stub.On(indexed).Get["Bill","Gates"].Will(Return.Value("Microsoft")); try { String.Intern(indexed["Steve","Jobs"]); } catch (ExpectationException e) { Assert.IsTrue(e.Message.IndexOf("get_Item") < 0, "message should not contain get_Item" ); Assert.IsTrue(e.Message.IndexOf("indexed[equal to \"Bill\", equal to \"Gates\"]") >= 0, "message should contain indexed[equal to \"Bill\", equal to \"Gates\"]\nWas: " + e.Message ); Assert.IsTrue(e.Message.IndexOf("indexed[\"Steve\", \"Jobs\"]") >= 0, "message should contain indexed[\"Steve\", \"Jobs\"]\nWas: " + e.Message ); } } [Test] public void ErrorMessagesContainNameOfPropertySetterNotHiddenMethod() { Mockery mocks = new Mockery(); Indexed indexed = (Indexed) mocks.NewMock(typeof(Indexed)); Expect.Once.On(indexed).Set["Bill","Gates"].To("Microsoft"); try { indexed["Steve","Jobs"] = "Apple"; } catch (ExpectationException e) { Assert.IsTrue(e.Message.IndexOf("set_Item") < 0, "message should not contain set_Item" ); Assert.IsTrue(e.Message.IndexOf("indexed[equal to \"Bill\", equal to \"Gates\"] = (equal to \"Microsoft\")") >= 0, "message should contain indexed[equal to \"Bill\", equal to \"Gates\"] = \"Microsoft\"\nWas: " + e.Message ); Assert.IsTrue(e.Message.IndexOf("indexed[\"Steve\", \"Jobs\"] = \"Apple\"") >= 0, "message should contain indexed[\"Steve\", \"Jobs\"] = \"Apple\"\nWas: " + e.Message ); } } } } --- NEW FILE: IHelloWorld.cs --- namespace NMock2.AcceptanceTests { public interface IHelloWorld { void Hello(); void Umm(); void Err(); void Ahh(); void Goodbye(); string Ask(string question); } } --- NEW FILE: OrderedCallsAcceptanceTest.cs --- using NMock2.Internal; using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class OrderedCallsAcceptanceTest { private Mockery mocks; private IHelloWorld helloWorld; [SetUp] public void SetUp() { mocks = new Mockery(); helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); } [Test] public void DoesNotEnforceTheOrderOfCallsByDefault() { Expect.Once.On(helloWorld).Method("Hello"); Expect.Once.On(helloWorld).Method("Goodbye"); helloWorld.Goodbye(); helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void UnorderedExpectationsMatchInOrderOfSpecification() { Expect.Once.On(helloWorld).Method("Ask").With(Is.Anything).Will(Return.Value("1")); Expect.Once.On(helloWorld).Method("Ask").With(Is.Anything).Will(Return.Value("2")); Assert.AreEqual("1", helloWorld.Ask("ignored"), "first call"); Assert.AreEqual("2", helloWorld.Ask("ignored"), "second call"); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void EnforcesTheOrderOfCallsWithinAnInOrderBlock() { using (mocks.Ordered) { Expect.Once.On(helloWorld).Method("Hello"); Expect.Once.On(helloWorld).Method("Goodbye"); } helloWorld.Goodbye(); helloWorld.Hello(); } [Test] public void AllowsCallsIfCalledInSameOrderAsExpectedWithinAnInOrderBlock() { using (mocks.Ordered) { Expect.Once.On(helloWorld).Method("Hello"); Expect.Once.On(helloWorld).Method("Goodbye"); } helloWorld.Hello(); helloWorld.Goodbye(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void CanExpectUnorderedCallsWithinAnOrderedSequence() { using (mocks.Ordered) { Expect.Once.On(helloWorld).Method("Hello"); using (mocks.Unordered) { Expect.Once.On(helloWorld).Method("Umm"); Expect.Once.On(helloWorld).Method("Err"); } Expect.Once.On(helloWorld).Method("Goodbye"); } helloWorld.Hello(); helloWorld.Err(); helloWorld.Umm(); helloWorld.Goodbye(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, ExpectedException(typeof(ExpectationException))] public void UnorderedCallsWithinAnInOrderedBlockCannotBeCalledBeforeTheStartOfTheUnorderedExpectations() { using (mocks.Ordered) { Expect.Once.On(helloWorld).Method("Hello"); using (mocks.Unordered) { Expect.Once.On(helloWorld).Method("Umm"); Expect.Once.On(helloWorld).Method("Err"); } Expect.Once.On(helloWorld).Method("Goodbye"); } helloWorld.Err(); helloWorld.Hello(); helloWorld.Umm(); helloWorld.Goodbye(); } [Test, ExpectedException(typeof(ExpectationException))] public void UnorderedCallsWithinAnInOrderedBlockCannotBeCalledAfterTheEndOfTheUnorderedExpectations() { using (mocks.Ordered) { Expect.Once.On(helloWorld).Method("Hello"); using (mocks.Unordered) { Expect.Once.On(helloWorld).Method("Umm"); Expect.Once.On(helloWorld).Method("Err"); } Expect.Once.On(helloWorld).Method("Goodbye"); } helloWorld.Hello(); helloWorld.Err(); helloWorld.Goodbye(); helloWorld.Umm(); } [Test] public void CallsWithinAnInOrderedBlockCanBeExpectedMoreThanOnce() { using (mocks.Ordered) { Expect.Once.On(helloWorld).Method("Hello"); Expect.AtLeastOnce.On(helloWorld).Method("Err"); Expect.Once.On(helloWorld).Method("Goodbye"); } helloWorld.Hello(); helloWorld.Err(); helloWorld.Err(); helloWorld.Goodbye(); } } } --- NEW FILE: ErrorMessageDemo.cs --- using System; using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class ErrorMessageDemo { public delegate void Action(); public interface ISyntacticSugar { string Property { get; set; } string this[string s] { get; set; } int this[int i,string s] { get; set; } event Action Actions; } [Test, Explicit] public void VerifyFailure() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Once.On(helloWorld).Method("Hello").WithNoArguments(); Expect.Between(2,4).On(helloWorld).Method("Ask").With("What color is the fish?") .Will(Return.Value("purple")); Expect.AtLeast(1).On(helloWorld).Method("Ask").With("How big is the fish?") .Will(Throw.Exception(new InvalidOperationException("stop asking about the fish!"))); helloWorld.Hello(); helloWorld.Ask("What color is the fish?"); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, Explicit] public void UnexpectedInvocation() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Once.On(helloWorld).Method("Hello").WithNoArguments(); Expect.Between(2,4).On(helloWorld).Method("Ask").With("What color is the fish?") .Will(Return.Value("purple")); Expect.AtLeast(1).On(helloWorld).Method("Ask").With("How big is the fish?") .Will(Throw.Exception(new InvalidOperationException("stop asking about the fish!"))); helloWorld.Hello(); helloWorld.Ask("What color is the fish?"); helloWorld.Ask("What color is the hippo?"); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test, Explicit] public void IndexerSet() { Mockery mocks = new Mockery(); ISyntacticSugar sugar = (ISyntacticSugar) mocks.NewMock(typeof(ISyntacticSugar), "sugar"); Expect.Once.On(sugar).Set[10,"goodbye"].To(12); sugar[10,"hello"] = 11; } [Test, Explicit] public void EventAdd() { Mockery mocks = new Mockery(); ISyntacticSugar sugar = (ISyntacticSugar) mocks.NewMock(typeof(ISyntacticSugar), "sugar"); Expect.Once.On(sugar).EventRemove("Actions",Is.Anything); sugar.Actions += new Action(DoAction); } private void DoAction() { throw new NotSupportedException(); } } } --- NEW FILE: StubAcceptanceTest.cs --- using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class StubAcceptanceTest { [Test] public void StubsDoNotHaveToBeCalled() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Stub.On(helloWorld).Method("Hello").WithAnyArguments(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void StubsCanBeCalledAnyNumberOfTimes() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Stub.On(helloWorld).Method("Hello").WithAnyArguments(); for (int i = 0; i < ANY_NUMBER; i++) helloWorld.Hello(); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void StubsMatchArgumentsAndPerformActionsJustLikeAnExpectation() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Stub.On(helloWorld).Method("Ask").With("Name").Will(Return.Value("Bob")); Stub.On(helloWorld).Method("Ask").With("Age").Will(Return.Value("30")); for (int i = 0; i < ANY_NUMBER; i++) { Verify.That(helloWorld.Ask("Name"), Is.EqualTo("Bob"), "Name"); Verify.That(helloWorld.Ask("Age"), Is.EqualTo("30"), "Age"); } } #region Don't look in here... #region I told you not to look in here! const int ANY_NUMBER = 10; #endregion #endregion } } --- NEW FILE: ErrorCheckingAcceptanceTest.cs --- using System; using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class ErrorCheckingAcceptanceTest { [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectAMethodOnAnRealObject() { object realObject = new object(); Expect.Once.On(realObject).Method(Is.Anything); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectAMethodThatDoesNotExistInTheMockedType() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).Method("NonexistentMethod"); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectAMethodWithAnInvalidName() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).Method("Invalid Name!"); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectGetOfAnInvalidProperty() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).GetProperty("NonexistentProperty"); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectSetOfAnInvalidProperty() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).SetProperty("NonexistentProperty").To("something"); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectGetOfIndexerIfNoIndexerInMockedType() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).Get["arg"].Will(Return.Value("something")); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectSetOfIndexerIfNoIndexerInMockedType() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).Set["arg"].To("something"); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectAddToNonexistentEvent() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).EventAdd("NonexistentEvent", Is.Anything); } [Test, ExpectedException(typeof(ArgumentException))] public void CannotExpectRemoveFromNonexistentEvent() { Mockery mocks = new Mockery(); IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof (IHelloWorld)); Expect.Once.On(helloWorld).EventRemove("NonexistentEvent", Is.Anything); } } } --- NEW FILE: UsingBlockAcceptanceTest.cs --- using NMock2.Internal; using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class UsingBlockAcceptanceTest { [Test, ExpectedException(typeof(ExpectationException))] public void AssertsExpectationsAreMetAtEndOfUsingBlock() { using(Mockery mocks = new Mockery()) { IHelloWorld helloWorld = (IHelloWorld) mocks.NewMock(typeof(IHelloWorld)); Expect.Once.On(helloWorld).Method("Hello").WithNoArguments(); } } } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: PropertiesAcceptanceTest.cs --- using System; using NMock2.Internal; using NUnit.Framework; namespace NMock2.AcceptanceTests { interface PersonRecord { string FirstName { get; set; } string LastName { get; set; } } [TestFixture] public class PropertiesAcceptanceTest { [Test] public void CanExpectPropertyGetter() { Mockery mocks = new Mockery(); PersonRecord p = (PersonRecord) mocks.NewMock(typeof(PersonRecord),"p"); Stub.On(p).GetProperty("FirstName").Will(Return.Value("Fred")); Stub.On(p).GetProperty("LastName").Will(Return.Value("Bloggs")); Verify.That(p.FirstName, Is.EqualTo("Fred"), "first name"); Verify.That(p.LastName, Is.EqualTo("Bloggs"), "last name"); } [Test] public void CanExpectPropertySetter() { Mockery mocks = new Mockery(); PersonRecord p = (PersonRecord)mocks.NewMock(typeof(PersonRecord), "p"); Expect.Once.On(p).SetProperty("FirstName").To("Fred"); p.FirstName = "Fred"; mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void ErrorMessagesContainNameOfPropertyGetterNotHiddenMethod() { Mockery mocks = new Mockery(); PersonRecord p = (PersonRecord) mocks.NewMock(typeof(PersonRecord),"p"); Stub.On(p).GetProperty("FirstName").Will(Return.Value("Fred")); try { String.Intern(p.LastName); } catch (ExpectationException e) { Assert.IsTrue(e.Message.IndexOf("get_FirstName()") < 0, "message should not contain get_FirstName()\nWas: " + e.Message); Assert.IsTrue(e.Message.IndexOf("p.FirstName") >= 0, "message should contain p.FirstName\nWas: " + e.Message); Assert.IsTrue(e.Message.IndexOf("get_LastName()") < 0, "message should not contain get_LastName()\nWas: " + e.Message); Assert.IsTrue(e.Message.IndexOf("p.LastName") >= 0, "message should contain p.LastName\nWas: " + e.Message); } } [Test] public void ErrorMessagesContainNameOfPropertySetterNotHiddenMethod() { Mockery mocks = new Mockery(); PersonRecord p = (PersonRecord) mocks.NewMock(typeof(PersonRecord),"p"); Expect.Once.On(p).SetProperty("FirstName").To("Fred"); try { p.LastName = "Bloggs"; } catch (ExpectationException e) { Assert.IsTrue(e.Message.IndexOf("set_FirstName(\"Fred\")") < 0, "message should not contain set_FirstName(\"Fred\")\nWas: " + e.Message ); Assert.IsTrue(e.Message.IndexOf("p.FirstName = (equal to \"Fred\")") >= 0, "message should contain p.FirstName = \"Fred\"\nWas: " + e.Message ); Assert.IsTrue(e.Message.IndexOf("set_LastName(\"Bloggs\")") < 0, "message should not contain set_LastName(\"Bloggs\")\nWas :" + e.Message ); Assert.IsTrue(e.Message.IndexOf("p.LastName = \"Bloggs\"") >= 0, "message should contain p.LastName = \"Bloggs\"\nWas: " + e.Message ); } } } } --- NEW FILE: EventsAcceptanceTest.cs --- using NUnit.Framework; namespace NMock2.AcceptanceTests { [TestFixture] public class EventsAcceptanceTest { public delegate void Listener(string message); public interface Announcer { event Listener Listeners; } public void DummyListener(string message) { } [Test] public void CanExpectEventAdd() { Mockery mocks = new Mockery(); Announcer announcer = (Announcer) mocks.NewMock(typeof(Announcer)); Expect.Once.On(announcer).EventAdd("Listeners", new Listener(DummyListener)); announcer.Listeners += new Listener(DummyListener); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void CanExpectEventRemove() { Mockery mocks = new Mockery(); Announcer announcer = (Announcer) mocks.NewMock(typeof(Announcer)); Expect.Once.On(announcer).EventRemove("Listeners", new Listener(DummyListener)); announcer.Listeners -= new Listener(DummyListener); mocks.VerifyAllExpectationsHaveBeenMet(); } [Test] public void DelegatesCanBeComparedToEquality() { Listener l1 = new Listener(DummyListener); Listener l2 = new Listener(DummyListener); Assert.AreEqual(l1, l2); } } } |
Update of /cvsroot/nmock/nmock2/src/NMock2/Actions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2/Actions Added Files: SetIndexedParameterAction.cs ResultSynthesizer.cs SetNamedParameterAction.cs ReturnAction.cs ReturnCloneAction.cs ThrowAction.cs Log Message: first upload of nmock2 --- NEW FILE: ReturnAction.cs --- using System.IO; using NMock2.Monitoring; namespace NMock2.Actions { public class ReturnAction : IAction { private readonly object result; public ReturnAction(object result) { this.result = result; } public void Invoke(Invocation invocation) { invocation.Result = result; } public void DescribeTo(TextWriter writer) { writer.Write("return "); writer.Write(result); } } } --- NEW FILE: SetNamedParameterAction.cs --- using System; using System.IO; using System.Reflection; using NMock2.Monitoring; namespace NMock2.Actions { public class SetNamedParameterAction : IAction { private readonly string name; private readonly object value; public SetNamedParameterAction(string name, object value) { this.name = name; this.value = value; } public void Invoke(Invocation invocation) { ParameterInfo[] paramsInfo = invocation.Method.GetParameters(); for (int i = 0; i < paramsInfo.Length; i++) { if (paramsInfo[i].Name == name) { invocation.Parameters[i] = value; return; } } throw new ArgumentException("no such parameter", name); } public void DescribeTo(TextWriter writer) { writer.Write("set "); writer.Write(name); writer.Write("="); writer.Write(value); } } } --- NEW FILE: ResultSynthesizer.cs --- using System; using System.Collections; using System.IO; using NMock2.Monitoring; namespace NMock2.Actions { public class ResultSynthesizer : IAction { private static Hashtable DEFAULT_RESULTS = new Hashtable(); static ResultSynthesizer() { DEFAULT_RESULTS[typeof (string)] = new ReturnAction(""); DEFAULT_RESULTS[typeof (ArrayList)] = new ReturnCloneAction(new ArrayList()); DEFAULT_RESULTS[typeof (SortedList)] = new ReturnCloneAction(new SortedList()); DEFAULT_RESULTS[typeof (Hashtable)] = new ReturnCloneAction(new Hashtable()); DEFAULT_RESULTS[typeof (Queue)] = new ReturnCloneAction(new Queue()); DEFAULT_RESULTS[typeof (Stack)] = new ReturnCloneAction(new Stack()); } private Hashtable results = new Hashtable(); public void Invoke(Invocation invocation) { Type returnType = invocation.Method.ReturnType; if (returnType == typeof(void)) return; // sanity check if (results.ContainsKey(returnType)) { IAction action = GetAction(returnType, results); action.Invoke(invocation); } else if (returnType.IsArray) { invocation.Result = NewEmptyArray(returnType); } else if (returnType.IsValueType) { invocation.Result = Activator.CreateInstance(returnType); } else if(DEFAULT_RESULTS.ContainsKey(returnType)) { IAction action = GetAction(returnType, DEFAULT_RESULTS); action.Invoke(invocation); } else { throw new InvalidOperationException("No action registered for return type "+returnType); } } private IAction GetAction(Type returnType, Hashtable results) { return ((IAction)results[returnType]); } public void SetResult(Type type, object result) { SetAction(type, Return.Value(result)); } private object SetAction(Type type, IAction action) { return results[type] = action; } public void DescribeTo(TextWriter writer) { throw new NotImplementedException(); } private static object NewEmptyArray(Type arrayType) { int rank = arrayType.GetArrayRank(); int[] dimensions = new int[rank]; return Array.CreateInstance(arrayType.GetElementType(), dimensions); } } } --- NEW FILE: ThrowAction.cs --- using System; using System.IO; using NMock2.Monitoring; namespace NMock2.Actions { public class ThrowAction : IAction { private readonly Exception exception; public ThrowAction(Exception exception) { this.exception = exception; } public void Invoke(Invocation invocation) { invocation.Exception = exception; } public void DescribeTo(TextWriter writer) { writer.Write("throw "); writer.Write(exception); } } } --- NEW FILE: SetIndexedParameterAction.cs --- using System.IO; using NMock2.Monitoring; namespace NMock2.Actions { public class SetIndexedParameterAction : IAction { private readonly int index; private readonly object value; public SetIndexedParameterAction(int index, object value) { this.index = index; this.value = value; } public void Invoke(Invocation invocation) { invocation.Parameters[index] = value; } public void DescribeTo(TextWriter writer) { writer.Write("set arg "); writer.Write(index); writer.Write("="); writer.Write(value); } } } --- NEW FILE: ReturnCloneAction.cs --- using System; using System.IO; using NMock2.Monitoring; namespace NMock2.Actions { public class ReturnCloneAction : IAction { private readonly ICloneable prototype; public ReturnCloneAction(ICloneable prototype) { this.prototype = prototype; } public void Invoke(Invocation invocation) { invocation.Result = prototype.Clone(); } public void DescribeTo(TextWriter writer) { writer.Write("a clone of "); writer.Write(prototype); } } } |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:58
|
Update of /cvsroot/nmock/nmock2/src/NMock2 In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2 Added Files: Mockery.cs .cvsignore Return.cs Stub.cs Expect.cs ISelfDescribing.cs AssemblyInfo.cs Is.cs Matcher.cs IAction.cs NMock2.csproj Has.cs IExpectation.cs Verify.cs Throw.cs Log Message: first upload of nmock2 --- NEW FILE: IExpectation.cs --- using System.IO; using NMock2.Monitoring; namespace NMock2 { public interface IExpectation { bool IsActive { get; } bool HasBeenMet { get; } bool Matches(Invocation invocation); void Perform(Invocation invocation); void DescribeActiveExpectationsTo(TextWriter writer); void DescribeUnmetExpectationsTo(TextWriter writer); } } --- NEW FILE: .cvsignore --- obj NMock2.csproj.user --- NEW FILE: Mockery.cs --- using System; using System.Reflection; using NMock2.Internal; using NMock2.Monitoring; namespace NMock2 { // Name inspired by Ivan Moore. public class Mockery : IDisposable { private readonly MultiInterfaceFactory facadeFactory = new MultiInterfaceFactory("Mocks"); private int depth; private IExpectationOrdering expectations; private IExpectationOrdering topOrdering; public Mockery() { depth = 1; expectations = new UnorderedExpectations(); topOrdering = expectations; } public object NewMock(Type mockedType) { return NewMock(mockedType, DefaultNameFor(mockedType)); } public object NewMock(Type mockedType, string name) { Type facadeType = facadeFactory.GetType(typeof(IMockObject), mockedType); MockObject mockObject = new MockObject(this, mockedType, name); ProxyInvokableAdapter adapter = new ProxyInvokableAdapter(facadeType, new ProxiedObjectIdentity(mockObject, new Invoker(typeof(IMockObject), mockObject, mockObject))); return adapter.GetTransparentProxy(); } public void AddExpectation(IExpectation expectation) { topOrdering.AddExpectation(expectation); } private void Dispatch(Invocation invocation) { if (expectations.Matches(invocation)) { expectations.Perform(invocation); } else { FailUnexpectedInvocation(invocation); } } private bool TypeHasMethodMatching(Type type, Matcher matcher) { foreach (MethodInfo method in type.GetMethods()) { if (matcher.Matches(method)) return true; } return false; } public IDisposable Ordered { get { return Push(new OrderedExpectations(depth)); } } public IDisposable Unordered { get { return Push(new UnorderedExpectations(depth)); } } private Popper Push(IExpectationOrdering newOrdering) { topOrdering.AddExpectation(newOrdering); IExpectationOrdering oldOrdering = topOrdering; topOrdering = newOrdering; depth++; return new Popper(this, oldOrdering); } private void Pop(IExpectationOrdering oldOrdering) { topOrdering = oldOrdering; depth--; } public void VerifyAllExpectationsHaveBeenMet() { if (!expectations.HasBeenMet) { FailUnmetExpectations(); } } private void FailUnmetExpectations() { DescriptionWriter writer = new DescriptionWriter(); writer.WriteLine("not all expected invocations were performed"); expectations.DescribeUnmetExpectationsTo(writer); throw new ExpectationException(writer.ToString()); } private void FailUnexpectedInvocation(Invocation invocation) { DescriptionWriter writer = new DescriptionWriter(); writer.Write("unexpected invocation of "); invocation.DescribeTo(writer); writer.WriteLine(); expectations.DescribeActiveExpectationsTo(writer); throw new ExpectationException(writer.ToString()); } public void Dispose() { VerifyAllExpectationsHaveBeenMet(); } protected virtual string DefaultNameFor(Type type) { string name = type.Name; int firstLower = FirstLowerCaseChar(name); if (firstLower == name.Length) { return name.ToLower(); } else { return name.Substring(firstLower-1,1).ToLower() + name.Substring(firstLower); } } private int FirstLowerCaseChar(string s) { int i = 0; while (i < s.Length && !Char.IsLower(s[i])) i++; return i; } private class MockObject : IInvokable, IMockObject { private readonly Mockery mockery; private readonly Type mockedType; private readonly string name; public MockObject(Mockery mockery, Type mockedType, string name) { this.mockery = mockery; this.mockedType = mockedType; this.name = name; } public override string ToString() { return name; } public void Invoke(Invocation invocation) { mockery.Dispatch(invocation); } public bool HasMethodMatching(Matcher methodMatcher) { return mockery.TypeHasMethodMatching(mockedType, methodMatcher); } public void AddExpectation(IExpectation expectation) { mockery.AddExpectation(expectation); } } private class Popper : IDisposable { private readonly Mockery mockery; private readonly IExpectationOrdering previous; public Popper( Mockery mockery, IExpectationOrdering previous ) { this.previous = previous; this.mockery = mockery; } public void Dispose() { mockery.Pop(previous); } } } } --- NEW FILE: Return.cs --- using System; using NMock2.Actions; namespace NMock2 { public class Return { public static IAction Value(object result) { return new ReturnAction(result); } public static IAction CloneOf(ICloneable prototype) { return new ReturnCloneAction(prototype); } } } --- NEW FILE: Verify.cs --- using NMock2.Internal; namespace NMock2 { public class Verify { public static void That( object actualValue, Matcher matcher, string message, params object[] formatArgs ) { if (!matcher.Matches(actualValue)) { DescriptionWriter writer = new DescriptionWriter(); writer.Write(message, formatArgs); WriteDescriptionOfFailedMatch(writer, actualValue, matcher); throw new ExpectationException(writer.ToString()); } } public static void That( object actualValue, Matcher matcher ) { if (!matcher.Matches(actualValue)) { DescriptionWriter writer = new DescriptionWriter(); WriteDescriptionOfFailedMatch(writer, actualValue, matcher); throw new ExpectationException(writer.ToString()); } } private static void WriteDescriptionOfFailedMatch(DescriptionWriter writer, object actualValue, Matcher matcher) { writer.WriteLine(); writer.Write("Expected: "); matcher.DescribeTo(writer); writer.WriteLine(); writer.Write("Actual: "); writer.Write(actualValue); } } } --- NEW FILE: Has.cs --- using NMock2.Matchers; namespace NMock2 { public class Has { public static Matcher ToString(Matcher stringMatcher) { return new ToStringMatcher(stringMatcher); } public static Matcher Property(string propertyName, Matcher valueMatcher) { return new PropertyMatcher(propertyName, valueMatcher); } } } --- NEW FILE: Stub.cs --- using NMock2.Internal; using NMock2.Syntax; namespace NMock2 { public class Stub { public static IMethodSyntax On(object mock) { ExpectationBuilder builder = new ExpectationBuilder("Stub", Is.Anything, Is.Anything); return builder.On(mock); } } } --- NEW FILE: Throw.cs --- using NMock2.Actions; namespace NMock2 { public class Throw { public static IAction Exception(System.Exception exception) { return new ThrowAction(exception); } } } --- NEW FILE: IAction.cs --- using NMock2.Monitoring; namespace NMock2 { public interface IAction : IInvokable, ISelfDescribing { } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("SharpMock")] [assembly: AssemblyDescription("Funky Mock Objects for C# and .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: Expect.cs --- using NMock2.Internal; using NMock2.Syntax; namespace NMock2 { public class Expect { public static IReceiverSyntax Never { get { return new ExpectationBuilder("never", Is.EqualTo(0), Is.EqualTo(0)); } } public static IReceiverSyntax Once { get { return Exactly(1); } } public static IReceiverSyntax AtLeastOnce { get { return AtLeast(1); } } public static IReceiverSyntax Exactly(int count) { return new ExpectationBuilder(Times(count), Is.EqualTo(count), Is.EqualTo(count)); } public static IReceiverSyntax AtLeast(int count) { return new ExpectationBuilder("at least "+Times(count), Is.AtLeast(count), Is.Anything); } public static IReceiverSyntax AtMost(int count) { return new ExpectationBuilder("at most "+Times(count) , Is.Anything, Is.AtMost(count)); } public static IReceiverSyntax Between(int minCount, int maxCount) { return new ExpectationBuilder(minCount+" to "+maxCount+" times", Is.AtLeast(minCount), Is.AtMost(maxCount)); } private static string Times(int n) { return n + ((n == 1) ? " time" : " times"); } } } --- NEW FILE: Matcher.cs --- using System.IO; using NMock2.Internal; using NMock2.Matchers; namespace NMock2 { public abstract class Matcher : ISelfDescribing { public abstract bool Matches(object o); public abstract void DescribeTo(TextWriter writer); public override string ToString() { DescriptionWriter writer = new DescriptionWriter(); DescribeTo(writer); return writer.ToString(); } public static Matcher operator& (Matcher m1, Matcher m2) { return new AndMatcher(m1,m2); } public static Matcher operator| (Matcher m1, Matcher m2) { return new OrMatcher(m1,m2); } public static Matcher operator! (Matcher m) { return new NotMatcher(m); } } } --- NEW FILE: Is.cs --- using System; using NMock2.Matchers; namespace NMock2 { public class Is { public static readonly Matcher Anything = new AlwaysMatcher(true, "anything"); public static readonly Matcher Nothing = new AlwaysMatcher(false, "nothing"); public static readonly Matcher Null = new NullMatcher(); public static readonly Matcher NotNull = new NotMatcher(Null); public static readonly Matcher Out = new ArgumentsMatcher.OutMatcher(); public static Matcher EqualTo(object expected) { return new EqualMatcher(expected); } public static Matcher Same(object expected) { return new SameMatcher(expected); } public static Matcher StringContaining(string substring) { return new StringContainsMatcher(substring); } public static Matcher GreaterThan(IComparable value) { return new ComparisonMatcher(value, 1, 1); } public static Matcher AtLeast(IComparable value) { return new ComparisonMatcher(value, 0, 1); } public static Matcher LessThan(IComparable value) { return new ComparisonMatcher(value, -1, -1); } public static Matcher AtMost(IComparable value) { return new ComparisonMatcher(value, -1, 0); } } } --- NEW FILE: ISelfDescribing.cs --- using System.IO; namespace NMock2 { public interface ISelfDescribing { void DescribeTo(TextWriter writer); } } --- NEW FILE: NMock2.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{CEE959FE-C3AF-4B51-8F1A-CCB32BAA1E98}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "NMock2" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "NMock2" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "..\..\build\NMock2\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "..\..\build\NMock2\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINNT\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Expect.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Has.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IAction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IExpectation.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Is.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ISelfDescribing.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Mockery.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Return.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Stub.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Throw.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Verify.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ResultSynthesizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ReturnAction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ReturnCloneAction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\SetIndexedParameterAction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\SetNamedParameterAction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Actions\ThrowAction.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\BuildableExpectation.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\DescriptionWriter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\ExpectationBuilder.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\ExpectationException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\IExpectationOrdering.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\IMockObject.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\OrderedExpectations.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Internal\UnorderedExpectations.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\AlwaysMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\AndMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\ArgumentsMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\BinaryOperator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\ComparisonMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\DescriptionOverride.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\EqualMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\IndexGetterArgumentsMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\IndexSetterArgumentsMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\MethodNameMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\NotMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\NullMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\OrMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\PropertyMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\SameMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\StringContainsMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Matchers\ToStringMatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\IInvokable.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\Invocation.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\Invoker.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\MultiInterfaceFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ParameterList.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ProxiedObjectIdentity.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Monitoring\ProxyInvokableAdapter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IActionSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IArgumentSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IGetIndexerSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IMatchSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IMethodSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IReceiverSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\ISetIndexerSyntax.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Syntax\IValueSyntax.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:57
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2/Internal Added Files: UnorderedExpectations.cs IMockObject.cs BuildableExpectation.cs IExpectationOrdering.cs OrderedExpectations.cs ExpectationException.cs DescriptionWriter.cs ExpectationBuilder.cs Log Message: first upload of nmock2 --- NEW FILE: IMockObject.cs --- namespace NMock2.Internal { public interface IMockObject { bool HasMethodMatching(Matcher methodMatcher); void AddExpectation(IExpectation expectation); } } --- NEW FILE: IExpectationOrdering.cs --- namespace NMock2.Internal { public interface IExpectationOrdering : IExpectation { void AddExpectation(IExpectation expectation); } } --- NEW FILE: OrderedExpectations.cs --- using System; using System.Collections; using System.IO; using NMock2.Monitoring; namespace NMock2.Internal { public class OrderedExpectations : IExpectationOrdering { private ArrayList expectations = new ArrayList(); private int current = 0; private int depth; public OrderedExpectations(int depth) { this.depth = depth; } public bool IsActive { get { return CurrentExpectation.IsActive; } } public bool HasBeenMet { get { return CurrentExpectation.HasBeenMet; } } public bool Matches(Invocation invocation) { return CurrentExpectation.Matches(invocation) || (CurrentExpectation.HasBeenMet && NextExpectationMatches(invocation)); } private bool NextExpectationMatches(Invocation invocation) { return HasNextExpectation && NextExpectation.Matches(invocation); } public void AddExpectation(IExpectation expectation) { expectations.Add(expectation); } public void Perform(Invocation invocation) { // If the current expectation doesn't match, it must have been met, by the contract // for the IExpectation interface and due to the implementation of this.Matches if (!CurrentExpectation.Matches(invocation)) current++; CurrentExpectation.Perform(invocation); } public void DescribeActiveExpectationsTo(TextWriter writer) { writer.WriteLine("Ordered:"); for (int i = 0; i < expectations.Count; i++) { IExpectation expectation = (IExpectation)expectations[i]; if (expectation.IsActive) { Indent(writer, depth+1); expectation.DescribeActiveExpectationsTo(writer); writer.WriteLine(); } } } public void DescribeUnmetExpectationsTo(TextWriter writer) { writer.WriteLine("Ordered:"); for (int i = 0; i < expectations.Count; i++) { IExpectation expectation = (IExpectation)expectations[i]; if (!expectation.HasBeenMet) { Indent(writer, depth+1); expectation.DescribeUnmetExpectationsTo(writer); writer.WriteLine(); } } } private IExpectation CurrentExpectation { get { return (IExpectation)expectations[current]; } } private bool HasNextExpectation { get { return current < expectations.Count-1; } } private IExpectation NextExpectation { get { return (IExpectation)expectations[current+1]; } } private void Indent(TextWriter writer, int n) { for (int i = 0; i < n; i++) writer.Write(" "); } } } --- NEW FILE: DescriptionWriter.cs --- using System.IO; namespace NMock2.Internal { public class DescriptionWriter : StringWriter { public DescriptionWriter() { } public override void Write(object value) { Write(FormatValue(value)); } private string FormatValue(object value) { if (value == null) { return "null"; } else if (value is string) { return FormatString( (string)value ); } else { return "<" + value.ToString() + ">"; } } private string FormatString(string s) { const string quote = "\""; const string escapedQuote = "\\\""; return quote + s.Replace(quote,escapedQuote) + quote; } } } --- NEW FILE: ExpectationBuilder.cs --- using System; using System.Reflection; using NMock2.Matchers; using NMock2.Syntax; namespace NMock2.Internal { public class ExpectationBuilder : IReceiverSyntax, IMethodSyntax, IArgumentSyntax, IMatchSyntax, IActionSyntax { BuildableExpectation expectation; IMockObject mockObject = null; public ExpectationBuilder(string description, Matcher requiredCountMatcher, Matcher acceptedCountMatcher) { expectation = new BuildableExpectation(description, requiredCountMatcher, acceptedCountMatcher); } public IMethodSyntax On(object receiver) { if (receiver is IMockObject) { mockObject = (IMockObject) receiver; expectation.ReceiverMatcher = new DescriptionOverride(receiver.ToString(), Is.Same(receiver)); mockObject.AddExpectation(expectation); } else { throw new ArgumentException("not a mock object", "receiver"); } return this; } public IArgumentSyntax Method(string methodName) { return Method(new MethodNameMatcher(methodName)); } public IArgumentSyntax Method(MethodInfo method) { return Method(new DescriptionOverride(method.Name, Is.Same(method))); } public IArgumentSyntax Method(Matcher methodMatcher) { if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have a method matching " + methodMatcher); } expectation.MethodMatcher = methodMatcher; return this; } public IMatchSyntax GetProperty(string propertyName) { Matcher methodMatcher = NewMethodNameMatcher(propertyName, "get_"+propertyName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have a getter for property " + propertyName); } expectation.MethodMatcher = methodMatcher; expectation.ArgumentsMatcher = new DescriptionOverride("", new ArgumentsMatcher()); return this; } public IValueSyntax SetProperty(string propertyName) { Matcher methodMatcher = NewMethodNameMatcher(propertyName+" = ", "set_"+propertyName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have a setter for property " + propertyName); } expectation.MethodMatcher = methodMatcher; return new PropertyValueBuilder(this); } private class PropertyValueBuilder : IValueSyntax { private readonly ExpectationBuilder builder; public PropertyValueBuilder(ExpectationBuilder builder) { this.builder = builder; } public IMatchSyntax To(Matcher valueMatcher) { return builder.With(valueMatcher); } public IMatchSyntax To(object equalValue) { return To(Is.EqualTo(equalValue)); } } public IGetIndexerSyntax Get { get { Matcher methodMatcher = NewMethodNameMatcher("", "get_Item"); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an indexed setter"); } expectation.DescribeAsIndexer(); expectation.MethodMatcher = methodMatcher; return new IndexGetterBuilder(expectation, this); } } private class IndexGetterBuilder : IGetIndexerSyntax { private readonly BuildableExpectation expectation; private readonly ExpectationBuilder builder; public IndexGetterBuilder(BuildableExpectation expectation, ExpectationBuilder builder) { this.expectation = expectation; this.builder = builder; } public IMatchSyntax this[params Matcher[] matchers] { get { expectation.ArgumentsMatcher = new IndexGetterArgumentsMatcher(matchers); return builder; } } public IMatchSyntax this[params object[] equalValues] { get { return this[IsEqualMatchersFor(equalValues)]; } } } public ISetIndexerSyntax Set { get { Matcher methodMatcher = NewMethodNameMatcher("", "set_Item"); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an indexed setter"); } expectation.DescribeAsIndexer(); expectation.MethodMatcher = methodMatcher; return new IndexSetterBuilder(expectation, this); } } private class IndexSetterBuilder : ISetIndexerSyntax, IValueSyntax { private readonly BuildableExpectation expectation; private readonly ExpectationBuilder builder; private Matcher[] matchers; public IndexSetterBuilder(BuildableExpectation expectation, ExpectationBuilder builder) { this.expectation = expectation; this.builder = builder; } public IValueSyntax this[params Matcher[] indexMatchers] { get { matchers = new Matcher[indexMatchers.Length + 1]; Array.Copy(indexMatchers, matchers, indexMatchers.Length); SetValueMatcher(Is.Anything); return this; } } public IValueSyntax this[params object[] equalValues] { get { return this[IsEqualMatchersFor(equalValues)]; } } public IMatchSyntax To(Matcher matcher) { SetValueMatcher(matcher); return builder; } public IMatchSyntax To(object equalValue) { return To(Is.EqualTo(equalValue)); } private void SetValueMatcher(Matcher matcher) { matchers[matchers.Length - 1] = matcher; expectation.ArgumentsMatcher = new IndexSetterArgumentsMatcher(matchers); } } public IMatchSyntax EventAdd(string eventName, Matcher listenerMatcher) { Matcher methodMatcher = NewMethodNameMatcher(eventName + " += ", "add_"+eventName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an event named " + eventName); } expectation.MethodMatcher = methodMatcher; expectation.ArgumentsMatcher = new ArgumentsMatcher(listenerMatcher); return this; } public IMatchSyntax EventAdd(string eventName, Delegate equalListener) { return EventAdd(eventName, Is.EqualTo(equalListener)); } public IMatchSyntax EventRemove(string eventName, Matcher listenerMatcher) { Matcher methodMatcher = NewMethodNameMatcher(eventName + " -= ", "remove_"+eventName); if (!mockObject.HasMethodMatching(methodMatcher)) { throw new ArgumentException("mock object " + mockObject + " does not have an event named " + eventName); } expectation.MethodMatcher = methodMatcher; expectation.ArgumentsMatcher = new ArgumentsMatcher(listenerMatcher); return this; } public IMatchSyntax EventRemove(string eventName, Delegate equalListener) { return EventRemove(eventName, Is.EqualTo(equalListener)); } public IMatchSyntax With(params Matcher[] argumentMatchers) { expectation.ArgumentsMatcher = new ArgumentsMatcher(argumentMatchers); return this; } public IMatchSyntax With(params object[] equalArgumentValues) { return With(IsEqualMatchersFor(equalArgumentValues)); } private static Matcher[] IsEqualMatchersFor(object[] equalArgumentValues) { Matcher[] matchers = new Matcher[equalArgumentValues.Length]; for (int i = 0; i < matchers.Length; i++) { matchers[i] = new EqualMatcher(equalArgumentValues[i]); } return matchers; } public IMatchSyntax WithNoArguments() { return With(new Matcher[0]); } public IMatchSyntax WithAnyArguments() { expectation.ArgumentsMatcher = new AlwaysMatcher(true, "(any arguments)"); return this; } public IActionSyntax Matching(Matcher matcher) { expectation.AddInvocationMatcher(matcher); return this; } public void Will(params IAction[] actions) { foreach (IAction action in actions) { expectation.AddAction(action); } } private static Matcher NewMethodNameMatcher(string description, string methodName) { return new DescriptionOverride(description, new MethodNameMatcher(methodName)); } } } --- NEW FILE: BuildableExpectation.cs --- using System.Collections; using System.IO; using NMock2.Matchers; using NMock2.Monitoring; namespace NMock2.Internal { public class BuildableExpectation : IExpectation { private int callCount = 0; private string expectationDescription; private Matcher requiredCountMatcher, matchingCountMatcher; private Matcher receiverMatcher = new AlwaysMatcher(true, "<any object>"); private string methodSeparator = "."; private Matcher methodMatcher = new AlwaysMatcher(true, "<any method>"); private Matcher argumentsMatcher = new AlwaysMatcher(true, "(any arguments)"); private ArrayList extraMatchers = new ArrayList(); private ArrayList actions = new ArrayList(); public BuildableExpectation(string expectationDescription, Matcher requiredCountMatcher, Matcher matchingCountMatcher) { this.expectationDescription = expectationDescription; this.requiredCountMatcher = requiredCountMatcher; this.matchingCountMatcher = matchingCountMatcher; } public Matcher ReceiverMatcher { get { return receiverMatcher; } set { receiverMatcher = value; } } public Matcher MethodMatcher { get { return methodMatcher; } set { methodMatcher = value; } } public Matcher ArgumentsMatcher { get { return argumentsMatcher; } set { argumentsMatcher = value; } } public void AddInvocationMatcher(Matcher matcher ) { extraMatchers.Add(matcher); } public void AddAction(IAction action) { actions.Add(action); } public bool Matches(Invocation invocation) { return IsActive && receiverMatcher.Matches(invocation.Receiver) && methodMatcher.Matches(invocation.Method) && argumentsMatcher.Matches(invocation) && ExtraMatchersMatch(invocation); } private bool ExtraMatchersMatch(Invocation invocation) { foreach (Matcher matcher in extraMatchers) { if (!matcher.Matches(invocation)) return false; } return true; } public void Perform(Invocation invocation) { callCount++; foreach (IAction action in actions) { action.Invoke(invocation); } } public bool IsActive { get { return matchingCountMatcher.Matches(callCount+1); } } public bool HasBeenMet { get { return requiredCountMatcher.Matches(callCount); } } public void DescribeActiveExpectationsTo(TextWriter writer) { if (IsActive) DescribeTo(writer); } public void DescribeUnmetExpectationsTo(TextWriter writer) { if (!HasBeenMet) DescribeTo(writer); } private void DescribeTo(TextWriter writer) { writer.Write(expectationDescription); writer.Write(": "); receiverMatcher.DescribeTo(writer); writer.Write(methodSeparator); methodMatcher.DescribeTo(writer); argumentsMatcher.DescribeTo(writer); foreach (Matcher extraMatcher in extraMatchers) { writer.Write(", "); extraMatcher.DescribeTo(writer); } if (actions.Count > 0) { writer.Write(", will "); ((IAction)actions[0]).DescribeTo(writer); for (int i = 1; i < actions.Count; i++) { writer.Write(", "); ((IAction)actions[i]).DescribeTo(writer); } } writer.Write(" [called "); writer.Write(callCount); writer.Write(" time"); if (callCount != 1) writer.Write("s"); writer.Write("]"); } public void DescribeAsIndexer() { methodSeparator = ""; } } } --- NEW FILE: UnorderedExpectations.cs --- using System; using System.Collections; using System.IO; using NMock2.Monitoring; namespace NMock2.Internal { public class UnorderedExpectations : IExpectationOrdering { private ArrayList expectations = new ArrayList(); private int depth; private string prompt; public UnorderedExpectations() { this.depth = 0; this.prompt = "Expected:"; } public UnorderedExpectations(int depth) { this.depth = depth; this.prompt = "Unordered:"; } public bool IsActive { get { foreach (IExpectation e in expectations) { if (e.IsActive) return true; } return false; } } public bool HasBeenMet { get { foreach (IExpectation e in expectations) { if (!e.HasBeenMet) return false; } return true; } } public bool Matches(Invocation invocation) { foreach (IExpectation e in expectations) { if (e.Matches(invocation)) return true; } return false; } public void Perform(Invocation invocation) { foreach (IExpectation e in expectations) { if (e.Matches(invocation)) { e.Perform(invocation); return; } } throw new InvalidOperationException("No matching expectation"); } public void DescribeActiveExpectationsTo(TextWriter writer) { writer.WriteLine(prompt); foreach (IExpectation expectation in expectations) { if (expectation.IsActive) { Indent(writer, depth+1); expectation.DescribeActiveExpectationsTo(writer); writer.WriteLine(); } } } public void DescribeUnmetExpectationsTo(TextWriter writer) { writer.WriteLine(prompt); foreach (IExpectation expectation in expectations) { if (!expectation.HasBeenMet) { Indent(writer, depth+1); expectation.DescribeUnmetExpectationsTo(writer); writer.WriteLine(); } } } private void Indent(TextWriter writer, int n) { for (int i = 0; i < n; i++) writer.Write(" "); } public void AddExpectation(IExpectation expectation) { expectations.Add(expectation); } } } --- NEW FILE: ExpectationException.cs --- using System; using System.Runtime.Serialization; namespace NMock2.Internal { public class ExpectationException : Exception { public ExpectationException() { } public ExpectationException(string message) : base(message) { } public ExpectationException(string message, Exception innerException) : base(message, innerException) { } public ExpectationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } |
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Matchers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2.Test/Matchers Added Files: DescriptionOverrideTest.cs ToStringMatcherTest.cs MethodNameMatcherTest.cs MockMatcher.cs MatcherWithDescription.cs ComparisonMatcherTest.cs AndMatcherTest.cs EqualMatcherTest.cs SameMatcherTest.cs ArgumentsMatcherTest.cs NotMatcherTest.cs PropertyMatcherTest.cs StringContainsMatcherTest.cs AlwaysMatcherTest.cs OrMatcherTest.cs NullMatcherTest.cs Log Message: first upload of nmock2 --- NEW FILE: PropertyMatcherTest.cs --- using NMock2.Matchers; using NUnit.Framework; namespace NMock2.Test.Matchers { [TestFixture] public class PropertyMatcherTest { [Test] public void MatchesObjectWithNamedPropertyAndMatchingPropertyValue() { ObjectWithProperties o = new ObjectWithProperties(); object aValue = new NamedObject("aValue"); o.A = aValue; Matcher m = new PropertyMatcher("A", Is.Same(aValue) ); Assert.IsTrue(m.Matches(o), "should match o"); } [Test] public void DoesNotMatchObjectIfPropertyMatcherDoesNotMatch() { ObjectWithProperties o = new ObjectWithProperties(); object aValue = new NamedObject("aValue"); object otherValue = new NamedObject("otherValue"); o.A = aValue; Matcher m = new PropertyMatcher("A", new SameMatcher(otherValue) ); Assert.IsFalse(m.Matches(o), "should match o"); } [Test] public void DoesNotMatchObjectIfItDoesNotHaveNamedProperty() { ObjectWithProperties o = new ObjectWithProperties(); Matcher m = new PropertyMatcher("OtherProperty", new AlwaysMatcher(true,"anything")); Assert.IsFalse(m.Matches(o), "should not match o"); } [Test] public void DoesNotMatchWriteOnlyProperty() { ObjectWithProperties o = new ObjectWithProperties(); Matcher m = new PropertyMatcher("WriteOnlyProperty", new AlwaysMatcher(true,"anything")); Assert.IsFalse(m.Matches(o), "should not match o"); } [Test] public void DoesNotMatchPrivateProperty() { ObjectWithProperties o = new ObjectWithProperties(); Matcher m = new PropertyMatcher("PrivateProperty", new AlwaysMatcher(true,"anything")); Assert.IsFalse(m.Matches(o), "should not match o"); } public class ObjectWithProperties { private object a; public object A { get { return a; } set { a = value; } } public object WriteOnlyProperty { set {} } private object PrivateProperty { get { return "value"; } set {} } public void AMethodToGetAroundCompilerWarnings() { this.PrivateProperty = "something"; } } } } --- NEW FILE: ComparisonMatcherTest.cs --- using System; using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class ComparisonMatcherTest { [Test] public void MatchesAComparisonOfAComparableValue() { Matcher matcher; matcher = new ComparisonMatcher(10, -1, 0); Assert.IsTrue(matcher.Matches(9), "less"); Assert.IsTrue(matcher.Matches(10), "equal"); Assert.IsFalse(matcher.Matches(11), "greater"); matcher = new ComparisonMatcher(10, -1, -1 ); Assert.IsTrue(matcher.Matches(9), "less"); Assert.IsFalse(matcher.Matches(10), "equal"); Assert.IsFalse(matcher.Matches(11), "greater"); matcher = new ComparisonMatcher(10, 0, 1 ); Assert.IsFalse(matcher.Matches(9), "less"); Assert.IsTrue(matcher.Matches(10), "equal"); Assert.IsTrue(matcher.Matches(11), "greater"); } [Test] public void DoesNotMatchObjectOfDifferentType() { Assert.IsFalse((new ComparisonMatcher(10,0,0)).Matches("a string")); } [Test,ExpectedException(typeof(ArgumentException))] public void CannotCreateComparisonThatMatchesAnything() { new ComparisonMatcher(10, -1, 1); } [Test] public void CanSpecifyMinAndMaxComparisonResultInAnyOrder() { Matcher matcher = new ComparisonMatcher(10, 0, -1); Assert.IsTrue(matcher.Matches(9), "less"); Assert.IsTrue(matcher.Matches(10), "equal"); Assert.IsFalse(matcher.Matches(11), "greater"); } [Test] public void HasReadableDescription() { AssertDescription.IsEqual(new ComparisonMatcher(10, -1, -1), "? < <10>"); AssertDescription.IsEqual(new ComparisonMatcher(10, -1, 0), "? <= <10>"); AssertDescription.IsEqual(new ComparisonMatcher(10, 0, 0), "? = <10>"); AssertDescription.IsEqual(new ComparisonMatcher(10, 0, 1), "? >= <10>"); AssertDescription.IsEqual(new ComparisonMatcher(10, 1, 1), "? > <10>"); } } } --- NEW FILE: StringContainsMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class StringContainsMatcherTest { [Test] public void MatchesIfStringArgumentContainsGivenSubstring() { string substring = "SUBSTRING"; Matcher matcher = new StringContainsMatcher(substring); Assert.IsTrue(matcher.Matches(substring), "arg is substring"); Assert.IsTrue(matcher.Matches(substring + "X"), "arg starts with substring"); Assert.IsTrue(matcher.Matches("X" + substring), "arg ends with substring"); Assert.IsTrue(matcher.Matches("X" + substring + "X"), "arg contains substring"); Assert.IsFalse(matcher.Matches("XX"), "arg does not contain substring"); Assert.IsFalse(matcher.Matches(null), "arg is null"); Assert.IsFalse(matcher.Matches(new object()), "arg is not a string"); } [Test] public void HasAReadableDescription() { string substring = "substring"; AssertDescription.IsEqual(new StringContainsMatcher(substring), "containing \"" + substring + "\""); } } } --- NEW FILE: MatcherWithDescription.cs --- using System; using System.IO; namespace NMock2.Test.Matchers { public class MatcherWithDescription : Matcher { private readonly string description; public MatcherWithDescription(string description) { this.description = description; } public override bool Matches(object o) { throw new NotImplementedException(); } public override void DescribeTo(TextWriter writer) { writer.Write(description); } } } --- NEW FILE: AndMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class AndMatcherTest { static readonly object ignored = new object(); static readonly Matcher TRUE = new AlwaysMatcher(true,"TRUE"); static readonly Matcher FALSE = new AlwaysMatcher(false, "FALSE"); static readonly object[,] truthTable = { {FALSE, FALSE, false}, {FALSE, TRUE, false}, {TRUE, FALSE, false}, {TRUE, TRUE, true} }; [Test] public void CalculatesLogicalConjunctionOfTwoMatchers() { for (int i = 0; i < truthTable.GetLength(0); i++) { Matcher matcher = new AndMatcher((Matcher)truthTable[i,0], (Matcher)truthTable[i,1]); Assert.AreEqual( truthTable[i,2], matcher.Matches(ignored) ); } } [Test] public void CanUseOperatorOverloadingAsSyntacticSugar() { for (int i = 0; i < truthTable.GetLength(0); i++) { Matcher arg1 = (Matcher)truthTable[i,0]; Matcher arg2 = (Matcher)truthTable[i,1]; Matcher matcher = arg1 & arg2; Assert.AreEqual( truthTable[i,2], matcher.Matches(ignored) ); } } [Test] public void HasAReadableDescription() { Matcher left = new MatcherWithDescription("<left>"); Matcher right = new MatcherWithDescription("<right>"); AssertDescription.IsComposed( new AndMatcher(left,right), "`{0}' and `{1}'", left, right); } } } --- NEW FILE: DescriptionOverrideTest.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: MockMatcher.cs --- using System.IO; using NUnit.Framework; namespace NMock2.Test.Matchers { class MockMatcher : Matcher { public object ExpectedMatchesArg = null; public bool MatchesResult = false; public int MatchesCallCount = 0; public override bool Matches(object o) { MatchesCallCount++; Assert.AreEqual(ExpectedMatchesArg, o, "Matches arg"); return MatchesResult; } public void AssertMatchesCalled(string messageFormat, params object[] formatArgs) { AssertMatchesCalled(1, messageFormat, formatArgs); } public void AssertMatchesCalled(int times, string messageFormat, params object[] formatArgs) { Assert.AreEqual(times, MatchesCallCount, messageFormat, formatArgs); } public TextWriter ExpectedDescribeToWriter = null; public string DescribeToOutput = ""; public int DescribeToCallCount = 0; public override void DescribeTo(TextWriter writer) { DescribeToCallCount++; if (ExpectedDescribeToWriter != null) { Assert.AreSame(ExpectedDescribeToWriter, writer, "DescribeTo writer"); } writer.Write(DescribeToOutput); } } } --- NEW FILE: AlwaysMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class AlwaysMatcherTest { [Test] public void AlwaysReturnsFixedBooleanValueFromMatchesMethod() { Matcher matcher = new AlwaysMatcher(true, ""); Assert.IsTrue(matcher.Matches("something")); Assert.IsTrue(matcher.Matches("something else")); Assert.IsTrue(matcher.Matches(null)); Assert.IsTrue(matcher.Matches(1)); Assert.IsTrue(matcher.Matches(1.0)); Assert.IsTrue(matcher.Matches(new object())); matcher = new AlwaysMatcher(false, ""); Assert.IsFalse(matcher.Matches("something")); Assert.IsFalse(matcher.Matches("something else")); Assert.IsFalse(matcher.Matches(null)); Assert.IsFalse(matcher.Matches(1)); Assert.IsFalse(matcher.Matches(1.0)); Assert.IsFalse(matcher.Matches(new object())); } [Test] public void IsGivenADescription() { string description = "DESCRIPTION"; bool irrelevantFlag = false; AssertDescription.IsEqual(new AlwaysMatcher(irrelevantFlag, description), description); } } } --- NEW FILE: SameMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class SameMatcherTest { [Test] public void MatchesSameObject() { object same = new object(); object other = new object(); Matcher matcher = new SameMatcher(same); Assert.IsTrue(matcher.Matches(same), "same"); Assert.IsFalse(matcher.Matches(other), "other"); } [Test] public void IsNullSafe() { Assert.IsTrue( new SameMatcher(null).Matches(null), "null matches null" ); Assert.IsFalse( new SameMatcher("not null").Matches(null), "not null does not match null" ); Assert.IsFalse( new SameMatcher(null).Matches("not null"), "null does not match not null" ); } [Test] public void HasAReadableDescription() { object same = new object(); AssertDescription.IsEqual(new SameMatcher(same), "same as <"+same+">"); } } } --- NEW FILE: ToStringMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class ToStringMatcherTest { NamedObject arg; MockMatcher stringMatcher; Matcher matcher; [SetUp] public void SetUp() { arg = new NamedObject("arg"); stringMatcher = new MockMatcher(); matcher = new ToStringMatcher(this.stringMatcher); } [Test] public void PassesResultOfToStringToOtherMatcher() { stringMatcher.ExpectedMatchesArg = arg.ToString(); stringMatcher.MatchesResult = true; Assert.AreEqual(stringMatcher.MatchesResult, matcher.Matches(arg), "result"); stringMatcher.AssertMatchesCalled("should have passed string representation to stringMatcher"); } [Test] public void ReturnsAReadableDescription() { stringMatcher.DescribeToOutput = "<stringMatcher description>"; AssertDescription.IsComposed(matcher, "an object with a string representation that is {0}", stringMatcher); } } } --- NEW FILE: EqualMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class EqualMatcherTest { const string EXPECTED = "expected"; [Test] public void ComparesArgumentForEqualityToExpectedObject() { Matcher matcher = new EqualMatcher(EXPECTED); Assert.IsTrue( matcher.Matches(EXPECTED), "same object" ); Assert.IsTrue( matcher.Matches(EXPECTED.Clone()), "equal object" ); Assert.IsFalse( matcher.Matches("not expected"), "unequal object" ); } [Test] public void IsNullSafe() { Assert.IsTrue( new EqualMatcher(null).Matches(null), "null matches null" ); Assert.IsFalse( new EqualMatcher("not null").Matches(null), "not null does not match null" ); Assert.IsFalse( new EqualMatcher(null).Matches("not null"), "null does not match not null" ); } [Test] public void ComparesArraysForEqualityByContents() { int[] expected = {1,2}; int[] equal = {1,2}; int[] inequal = {2,3}; int[] longer = {1,2,3}; int[] shorter = {1}; int[] empty = {}; int[,] otherRank = {{1,2},{3,4}}; Matcher matcher = new EqualMatcher(expected); Assert.IsTrue(matcher.Matches(expected), "same array"); Assert.IsTrue(matcher.Matches(equal), "same contents"); Assert.IsFalse(matcher.Matches(inequal), "different contents"); Assert.IsFalse(matcher.Matches(longer), "longer"); Assert.IsFalse(matcher.Matches(shorter), "shorter"); Assert.IsFalse(matcher.Matches(empty), "empty"); Assert.IsFalse(matcher.Matches(otherRank), "other rank"); } [Test] public void RecursivelyComparesArrayContentsOfNestedArrays() { int[][] expected = new int[][] {new int[]{1,2},new int[]{3,4}}; int[][] equal = new int[][] {new int[]{1,2},new int[]{3,4}}; int[][] inequal = new int[][] {new int[]{2,3},new int[]{4,5}}; Matcher matcher = new EqualMatcher(expected); Assert.IsTrue(matcher.Matches(expected), "same array"); Assert.IsTrue(matcher.Matches(equal), "same contents"); Assert.IsFalse(matcher.Matches(inequal), "different contents"); } [Test] public void CanCompareAutoboxedValues() { Matcher matcher = new EqualMatcher(1); Assert.IsTrue(matcher.Matches(1), "equal value"); Assert.IsFalse(matcher.Matches(2), "other value"); } [Test] public void HasAReadableDescription() { NamedObject value = new NamedObject("value"); AssertDescription.IsEqual(new EqualMatcher(value), "equal to <"+value+">"); } } } --- NEW FILE: OrMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class OrMatcherTest { static readonly object ignored = new object(); static readonly Matcher TRUE = new AlwaysMatcher(true,"TRUE"); static readonly Matcher FALSE = new AlwaysMatcher(false, "FALSE"); static readonly object[,] truthTable = { {FALSE, FALSE, false}, {FALSE, TRUE, true}, {TRUE, FALSE, true}, {TRUE, TRUE, true} }; [Test] public void CalculatesLogicalDisjunctionOfTwoMatchers() { for (int i = 0; i < truthTable.GetLength(0); i++) { Matcher arg1 = (Matcher)truthTable[i,0]; Matcher arg2 = (Matcher)truthTable[i,1]; Matcher matcher = new OrMatcher(arg1, arg2); Assert.AreEqual( truthTable[i,2], matcher.Matches(ignored) ); } } [Test] public void CanUseOperatorOverloadingAsSyntacticSugar() { for (int i = 0; i < truthTable.GetLength(0); i++) { Matcher arg1 = (Matcher)truthTable[i,0]; Matcher arg2 = (Matcher)truthTable[i,1]; Matcher matcher = arg1 | arg2; Assert.AreEqual( truthTable[i,2], matcher.Matches(ignored) ); } } [Test] public void HasAReadableDescription() { Matcher left = new MatcherWithDescription("<left>"); Matcher right = new MatcherWithDescription("<right>"); AssertDescription.IsComposed( new OrMatcher(left,right), "`{0}' or `{1}'", left, right); } } } --- NEW FILE: MethodNameMatcherTest.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: NullMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class NullMatcherTest { [Test] public void MatchesNullReferences() { Matcher matcher = new NullMatcher(); Assert.IsTrue( matcher.Matches(null), "null"); Assert.IsFalse( matcher.Matches(new object()), "not null"); } [Test] public void ProvidesAReadableDescription() { AssertDescription.IsEqual(new NullMatcher(), "null"); } } } --- NEW FILE: NotMatcherTest.cs --- using NUnit.Framework; using NMock2.Matchers; namespace NMock2.Test.Matchers { [TestFixture] public class NotMatcherTest { static readonly object ignored = new object(); static readonly Matcher TRUE = new AlwaysMatcher(true,"TRUE"); static readonly Matcher FALSE = new AlwaysMatcher(false, "FALSE"); [Test] public void CalculatesTheLogicalNegationOfAMatcher() { Assert.IsTrue( new NotMatcher(FALSE).Matches(ignored), "not false" ); Assert.IsFalse( new NotMatcher(TRUE).Matches(ignored), "not true" ); } [Test] public void CanUseOperatorOverloadingAsSyntacticSugar() { Assert.IsTrue( (!FALSE).Matches(ignored), "not false" ); Assert.IsFalse( (!TRUE).Matches(ignored), "not true" ); } [Test] public void HasAReadableDescription() { Matcher negated = new MatcherWithDescription("<negated>"); NotMatcher notMatcher = new NotMatcher(negated); AssertDescription.IsComposed(notMatcher, "not {0}", negated ); } } } --- NEW FILE: ArgumentsMatcherTest.cs --- (This appears to be a binary file; contents omitted.) |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:54
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2.Test/Internal Added Files: BuildableExpectationTest.cs DescriptionWriterTest.cs Log Message: first upload of nmock2 --- NEW FILE: DescriptionWriterTest.cs --- using NUnit.Framework; using NMock2.Internal; namespace NMock2.Internal.Test { [TestFixture] public class DescriptionWriterTest { DescriptionWriter writer; [SetUp] public void InitialiseWriter() { writer = new DescriptionWriter(); } [Test] public void FormatsStringsInCSharpSyntaxWhenWrittenAsObject() { object aString = "hello \"world\""; writer.Write(aString); Assert.AreEqual("\"hello \\\"world\\\"\"", writer.ToString()); } [Test] public void FormatsNullAsNull() { writer.Write((object)null); Assert.AreEqual("null", writer.ToString()); } [Test] public void HighlightsOtherValuesWhenWrittenAsObject() { object anInt = 1; writer.Write(anInt); Assert.AreEqual("<1>", writer.ToString()); } } } --- NEW FILE: BuildableExpectationTest.cs --- using System.IO; using NMock2.Matchers; using NMock2.Monitoring; using NMock2.Test.Monitoring; using NUnit.Framework; namespace NMock2.Internal.Test { [TestFixture] public class BuildableExpectationTest { private Invocation invocation; [SetUp] public void SetUp() { invocation = new Invocation("receiver", new MethodInfoStub("method"), new object[] { "arg" }); } [Test] public void MatchesIfAllMatchersMatch() { BuildableExpectation e = BuildExpectation(true, true, true, true, true, true, true); Assert.IsTrue( e.Matches(this.invocation), "should match"); } [Test] public void DoesNotMatchIfAnyMatcherDoesNotMatch() { const bool ignoreRequiredCallCount = true; for (int i = 1; i < 64; i++) { BuildableExpectation e = BuildExpectation( ignoreRequiredCallCount, (i & 1) == 0, (i & 2) == 0, (i & 4) == 0, (i & 8) == 0, (i & 16) == 0, (i & 32) == 0); Assert.IsFalse(e.Matches(this.invocation), "should not match (iteration "+i+")"); } } [Test] public void InvokesAListOfActionsToPerformAnInvocation() { BuildableExpectation e = BuildExpectation(true,true,true,true,true,true,true); MockAction action1 = new MockAction(); MockAction action2 = new MockAction(); e.AddAction(action1); e.AddAction(action2); e.Perform(invocation); Assert.AreSame( invocation, action1.Received, "action1 received"); Assert.AreSame( invocation, action2.Received, "action1 received"); } [Test] public void MatchesCallCountWhenMatchingInvocation() { Matcher irrelevant = Is.Anything; BuildableExpectation expectation = BuildExpectation( "description", irrelevant, Is.AtMost(4), irrelevant, irrelevant, irrelevant, irrelevant, irrelevant); AssertIsActive(expectation, "should be active before any invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 1st invocation"); expectation.Perform(invocation); AssertIsActive(expectation, "should be active before 2nd invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 2nd invocation"); expectation.Perform(invocation); AssertIsActive(expectation, "should be active before 3rd invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 3rd invocation"); expectation.Perform(invocation); AssertIsActive(expectation, "should be active before 4th invocation"); Assert.IsTrue(expectation.Matches(invocation), "should match 4th invocation"); expectation.Perform(invocation); AssertIsNotActive(expectation, "should not be active after 4th invocation"); Assert.IsFalse(expectation.Matches(invocation), "should not match 5th invocation"); } [Test] public void ChecksCallCountToAssertThatItHasBeenMet() { Matcher irrelevant = Is.Anything; BuildableExpectation expectation = BuildExpectation( "description", Is.AtLeast(2), Is.AtMost(4), irrelevant, irrelevant, irrelevant, irrelevant, irrelevant); AssertHasNotBeenMet(expectation, "should not have been met after no invocations"); expectation.Perform(invocation); AssertHasNotBeenMet(expectation, "should not have been met after 1 invocation"); expectation.Perform(invocation); AssertHasBeenMet(expectation, "should have been met after 2 invocations"); expectation.Perform(invocation); AssertHasBeenMet(expectation, "should have been met after 3 invocations"); expectation.Perform(invocation); AssertHasBeenMet(expectation, "should have been met after 4 invocations"); } [Test] public void HasReadableDescription() { BuildableExpectation expectation = BuildExpectation( "expectation", "required call count description is ignored", "matching call count description is ignored", "receiver", "method", "(arguments)", "extra matcher 1", "extra matcher 2" ); expectation.AddAction(new MockAction("action 1")); expectation.AddAction(new MockAction("action 2")); AssertDescriptionIsEqual(expectation, "expectation: receiver.method(arguments), extra matcher 1, extra matcher 2, will action 1, action 2 [called 0 times]"); } [Test] public void WillNotPrintAPeriodBetweenReceiverAndMethodIfToldToDescribeItselfAsAnIndexer() { BuildableExpectation expectation = BuildExpectation( "expectation", "required call count description is ignored", "matching call count description is ignored", "receiver", "", "[arguments]", "extra matcher 1", "extra matcher 2" ); expectation.AddAction(new MockAction("action 1")); expectation.AddAction(new MockAction("action 2")); expectation.DescribeAsIndexer(); AssertDescriptionIsEqual(expectation, "expectation: receiver[arguments], extra matcher 1, extra matcher 2, will action 1, action 2 [called 0 times]"); } private static BuildableExpectation BuildExpectation( bool matchRequiredCallCount, bool matchMatchingCallCount, bool matchReceiver, bool matchMethod, bool matchArguments, params bool[] matchExtraMatchers) { Matcher[] extraMatchers = new Matcher[matchExtraMatchers.Length]; for (int i = 0; i < extraMatchers.Length; i++) { extraMatchers[i] = new AlwaysMatcher(matchExtraMatchers[i], "extra matcher "+(i+1)); } return BuildExpectation( "description", new AlwaysMatcher(matchRequiredCallCount, "required call count"), new AlwaysMatcher(matchMatchingCallCount, "matching call count"), new AlwaysMatcher(matchReceiver, "receiver"), new AlwaysMatcher(matchMethod, "method"), new AlwaysMatcher(matchArguments, "argument"), extraMatchers ); } private static BuildableExpectation BuildExpectation( string expectationDescription, string matchRequiredCallCountDescription, string matchMatchingCallCountDescription, string matchReceiverDescription, string matchMethodDescription, string matchArgumentsDescription, params string[] extraMatcherDescriptions) { bool irrelevant = true; Matcher[] extraMatchers = new Matcher[extraMatcherDescriptions.Length]; for (int i = 0; i < extraMatchers.Length; i++) { extraMatchers[i] = new AlwaysMatcher(irrelevant, extraMatcherDescriptions[i]); } return BuildExpectation( expectationDescription, new AlwaysMatcher(irrelevant, matchRequiredCallCountDescription), new AlwaysMatcher(irrelevant, matchMatchingCallCountDescription), new AlwaysMatcher(irrelevant, matchReceiverDescription), new AlwaysMatcher(irrelevant, matchMethodDescription), new AlwaysMatcher(irrelevant, matchArgumentsDescription), extraMatchers); } private static BuildableExpectation BuildExpectation( string description, Matcher requiredCallCountMatcher, Matcher matchingCallCountMatcher, Matcher receiverMatcher, Matcher methodMatcher, Matcher argumentsMatcher, params Matcher[] extraMatchers) { BuildableExpectation e = new BuildableExpectation(description, requiredCallCountMatcher, matchingCallCountMatcher); e.ArgumentsMatcher = argumentsMatcher; e.MethodMatcher = methodMatcher; e.ReceiverMatcher = receiverMatcher; foreach (Matcher extraMatcher in extraMatchers) e.AddInvocationMatcher(extraMatcher); return e; } private void AssertIsActive(IExpectation expectation, string message) { Assert.IsTrue(expectation.IsActive, message); } private void AssertHasBeenMet(IExpectation expectation, string message) { Assert.IsTrue(expectation.HasBeenMet, message); } private void AssertHasNotBeenMet(IExpectation expectation, string message) { Assert.IsFalse(expectation.HasBeenMet, message); } private void AssertIsNotActive(IExpectation expectation, string message) { Assert.IsFalse(expectation.IsActive, message); } private void AssertDescriptionIsEqual(BuildableExpectation expectation, string expected) { DescriptionWriter writer = new DescriptionWriter(); expectation.DescribeActiveExpectationsTo(writer); Assert.AreEqual(expected, writer.ToString()); } } class MockAction : IAction { public Invocation Received = null; public MockAction Previous = null; public string Description; public MockAction() : this("MockAction") { } public MockAction(string description) { this.Description = description; } public void Invoke(Invocation invocation) { if (Previous != null) Assert.IsNotNull(Previous.Received, "called out of order"); Received = invocation; } public void DescribeTo(TextWriter writer) { writer.Write(Description); } } } |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:53
|
Update of /cvsroot/nmock/nmock2/lib In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/lib Added Files: nunit.framework.dll Log Message: first upload of nmock2 --- NEW FILE: nunit.framework.dll --- (This appears to be a binary file; contents omitted.) |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:51
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Syntax In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2/Syntax Added Files: IGetIndexerSyntax.cs IActionSyntax.cs IReceiverSyntax.cs IValueSyntax.cs ISetIndexerSyntax.cs IArgumentSyntax.cs IMethodSyntax.cs IMatchSyntax.cs Log Message: first upload of nmock2 --- NEW FILE: IValueSyntax.cs --- namespace NMock2.Syntax { public interface IValueSyntax { IMatchSyntax To(Matcher valueMatcher); IMatchSyntax To(object equalValue); } } --- NEW FILE: IActionSyntax.cs --- namespace NMock2.Syntax { public interface IActionSyntax { void Will(params IAction[] actions); } } --- NEW FILE: IReceiverSyntax.cs --- namespace NMock2.Syntax { public interface IReceiverSyntax { IMethodSyntax On(object o); } } --- NEW FILE: IMatchSyntax.cs --- namespace NMock2.Syntax { public interface IMatchSyntax : IActionSyntax { IActionSyntax Matching( Matcher matcher ); } } --- NEW FILE: IMethodSyntax.cs --- using System; using System.Reflection; namespace NMock2.Syntax { public interface IMethodSyntax { IArgumentSyntax Method(string name); IArgumentSyntax Method(Matcher nameMatcher); IArgumentSyntax Method(MethodInfo method); IValueSyntax SetProperty(string name); IMatchSyntax GetProperty(string name); IGetIndexerSyntax Get { get; } ISetIndexerSyntax Set { get; } IMatchSyntax EventAdd(string eventName, Matcher listenerMatcher); IMatchSyntax EventAdd(string eventName, Delegate equalListener); IMatchSyntax EventRemove(string eventName, Matcher listenerMatcher); IMatchSyntax EventRemove(string eventName, Delegate equalListener); } } --- NEW FILE: ISetIndexerSyntax.cs --- namespace NMock2.Syntax { public interface ISetIndexerSyntax { IValueSyntax this[params Matcher[] args] { get; } IValueSyntax this[params object[] args] { get; } } } --- NEW FILE: IGetIndexerSyntax.cs --- namespace NMock2.Syntax { public interface IGetIndexerSyntax { IMatchSyntax this[params Matcher[] args] { get; } IMatchSyntax this[params object[] args] { get; } } } --- NEW FILE: IArgumentSyntax.cs --- namespace NMock2.Syntax { public interface IArgumentSyntax : IMatchSyntax { IMatchSyntax With(params Matcher[] otherArgumentMatchers); IMatchSyntax With(params object[] equalArgumentValues); IMatchSyntax WithNoArguments(); IMatchSyntax WithAnyArguments(); } } |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:50
|
Update of /cvsroot/nmock/nmock2 In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181 Added Files: nant.build NMock2.sln README.TXT .cvsignore .project NMock2.nunit Log Message: first upload of nmock2 --- NEW FILE: .cvsignore --- _ReSharper.NMock2 build NMock2.resharperoptions NMock2.suo --- NEW FILE: .project --- <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>nmock2</name> <comment></comment> <projects> </projects> <buildSpec> </buildSpec> <natures> </natures> </projectDescription> --- NEW FILE: NMock2.nunit --- <NUnitProject> <Settings activeconfig="Debug" /> <Config name="Debug" binpathtype="Auto"> <assembly path="build\NMock2.Test\Debug\NMock2.Test.dll" /> <assembly path="build\NMock2.AcceptanceTests\Debug\NMock2.AcceptanceTests.dll" /> </Config> <Config name="Release" binpathtype="Auto"> <assembly path="build\NMock2.Test\Release\NMock2.Test.dll" /> <assembly path="build\NMock2.AcceptanceTests\Release\NMock2.AcceptanceTests.dll" /> </Config> </NUnitProject> --- NEW FILE: nant.build --- <project name="SharpMock" default="build"> <property name="configuration" value="Debug"/> <target name="clean" description="Delete all previously compiled binaries."> <delete> <fileset> <include name="build/**" /> <include name="**/obj/**" /> </fileset> </delete> </target> <target name="build" description="Build all targets."> <solution configuration="${configuration}" solutionfile="NMock2.sln" /> <property name="expected.output" value="build/NMock2/${configuration}/NMock2.dll"/> <fail unless="${file::exists(expected.output)}">Output file doesn't exist in ${expected.output}</fail> </target> <target name="rebuild" depends="clean, build" /> </project> --- NEW FILE: README.TXT --- Caveats: - No documentation yet. Read the acceptance tests to see how to use the library. - Cannot mock classes yet. Changes: - Added Has.Property(string PropertyName, Matcher propertyMatcher) matcher - Introduced ExpectationException and replaced all uses of AssertionException - Fixed ordered calls when using "at least..." and "between..." expectations - Renamed namespaces and build paths to contain NMock2, not SharpMock - Removed OO-Matron stuff from SharpMock.Monitoring namespace - Removed IExpectationCollection interface - Renamed AssertAllExpectationsHaveBeenMet to VerifyAllExpectationsHaveBeenMet - Added Verify.That assertion function that uses Matchers - Moved internal interfaces and classes into SharpMock.Internal namespace Todo: - Error message from unexpected method should show expectations that are allowed, that from VerifyAllExpectationsHaveMeenMet should show expectations that have not been met. - A Mockery that can mock classes (use NMock 1 bytecode generator?) - More matchers: Has.Property(string PropertyName, Matcher propertyMatcher), etc. - Default result stub to synthesise results based on return type [in progress] - Distinguish pure stubs from mocks: have a Mockery::NewStub method that returns a stub object that cannot be only used to set up stubbed methods, not expectations, and returns default values for methods that do not have explicit stubs. Questions: - Should I get rid of the ISelfDescribing interface and just put a DescribeTo method in each interface that currently extends it? Pro: ISelfDescribing is not used directly. Con: duplicated declarations of DescribeTo. --- NEW FILE: NMock2.sln --- Microsoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NMock2", "src\NMock2\NMock2.csproj", "{CEE959FE-C3AF-4B51-8F1A-CCB32BAA1E98}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NMock2.Test", "src\NMock2.Test\NMock2.Test.csproj", "{CC6D39F7-1387-401D-9303-088D39459F36}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NMock2.AcceptanceTests", "src\NMock2.AcceptanceTests\NMock2.AcceptanceTests.csproj", "{B4EED566-0F75-443F-9990-FBD7E489B9BD}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {CEE959FE-C3AF-4B51-8F1A-CCB32BAA1E98}.Debug.ActiveCfg = Debug|.NET {CEE959FE-C3AF-4B51-8F1A-CCB32BAA1E98}.Debug.Build.0 = Debug|.NET {CC6D39F7-1387-401D-9303-088D39459F36}.Debug.ActiveCfg = Debug|.NET {CC6D39F7-1387-401D-9303-088D39459F36}.Debug.Build.0 = Debug|.NET {B4EED566-0F75-443F-9990-FBD7E489B9BD}.Debug.ActiveCfg = Debug|.NET {B4EED566-0F75-443F-9990-FBD7E489B9BD}.Debug.Build.0 = Debug|.NET EndGlobalSection GlobalSection(SolutionItems) = postSolution README.txt = README.txt EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal |
Update of /cvsroot/nmock/nmock2/src/NMock2/Monitoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24181/src/NMock2/Monitoring Added Files: ProxiedObjectIdentity.cs IInvokable.cs ParameterList.cs Invocation.cs Invoker.cs MultiInterfaceFactory.cs ProxyInvokableAdapter.cs Log Message: first upload of nmock2 --- NEW FILE: MultiInterfaceFactory.cs --- using System; using System.Collections; using System.Reflection; using System.Reflection.Emit; namespace NMock2.Monitoring { public class MultiInterfaceFactory { private ModuleBuilder moduleBuilder; private Hashtable createdTypes = new Hashtable(); public MultiInterfaceFactory(string name) { AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = name; AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); moduleBuilder = assemblyBuilder.DefineDynamicModule(name); } public Type GetType(params Type[] baseInterfaces) { TypeId id = Id(baseInterfaces); if (createdTypes.ContainsKey(id)) { return (Type) createdTypes[id]; } else { string typeName = "MultiInterface" + (createdTypes.Count+1); Type newType = CreateType(typeName, baseInterfaces); createdTypes[id] = newType; return newType; } } private Type CreateType(string typeName, Type[] baseInterfaces) { TypeBuilder typeBuilder = moduleBuilder.DefineType( typeName, TypeAttributes.Public|TypeAttributes.Abstract|TypeAttributes.Interface, null, baseInterfaces ); return typeBuilder.CreateType(); } private TypeId Id(params Type[] types) { return new TypeId(types); } private class TypeId { Type[] types; public TypeId(params Type[] types) { this.types = types; } public override int GetHashCode() { int hashCode = 0; foreach (Type type in types) { hashCode ^= type.GetHashCode(); } return hashCode; } public override bool Equals(object obj) { return obj is TypeId && ContainsSameTypesAs( (TypeId)obj ); } private bool ContainsSameTypesAs(TypeId other) { if (other.types.Length != types.Length) return false; for (int i = 0; i < types.Length; i++) { if (Array.IndexOf(other.types, types[i]) < 0) return false; } return true; } } } } --- NEW FILE: ProxiedObjectIdentity.cs --- using System; using System.Reflection; namespace NMock2.Monitoring { public class ProxiedObjectIdentity : IInvokable { private static readonly MethodInfo EQUALS_METHOD = typeof(object).GetMethod("Equals",new Type[]{typeof(object)}); private readonly object identityProvider; private readonly IInvokable next; public ProxiedObjectIdentity(object identityProvider, IInvokable next) { this.identityProvider = identityProvider; this.next = next; } public void Invoke(Invocation invocation) { if (invocation.Method.DeclaringType == typeof(object)) { if (invocation.Method.Equals(EQUALS_METHOD)) { invocation.Result = Object.ReferenceEquals(invocation.Receiver, invocation.Parameters[0]); } else { invocation.InvokeOn(identityProvider); } } else { next.Invoke(invocation); } } } } --- NEW FILE: Invoker.cs --- using System; namespace NMock2.Monitoring { public class Invoker : IInvokable { private readonly Type targetType; private readonly object target; private readonly IInvokable next; public Invoker(Type targetType, object target, IInvokable next) { this.targetType = targetType; this.target = target; this.next = next; } public void Invoke(Invocation invocation) { if (targetType == invocation.Method.DeclaringType) { invocation.InvokeOn(target); } else { next.Invoke(invocation); } } } } --- NEW FILE: IInvokable.cs --- namespace NMock2.Monitoring { public interface IInvokable { void Invoke( Invocation invocation ); } } --- NEW FILE: ParameterList.cs --- using System; using System.Collections; using System.Reflection; namespace NMock2.Monitoring { public class ParameterList { private MethodInfo method; private object[] values; private BitArray isValueSet; public ParameterList(MethodInfo method, object[] values) { this.method = method; this.values = values; isValueSet = new BitArray(values.Length); ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { isValueSet[i] = !parameters[i].IsOut; } } public int Count { get { return values.Length; } } public object this[int i] { get { if (IsValueSet(i)) { return values[i]; } else { throw new InvalidOperationException("parameter "+ParameterName(i)+" has not been set"); } } set { if (CanValueBeSet(i)) { values[i] = value; isValueSet[i] = true; } else { throw new InvalidOperationException("cannot set the value of in parameter "+ParameterName(i)); } } } internal object[] AsArray { get { return values; } } internal void MarkAllValuesAsSet() { isValueSet.SetAll(true); } private bool CanValueBeSet(int i) { return !method.GetParameters()[i].IsIn; } public bool IsValueSet(int i) { return isValueSet[i]; } private string ParameterName(int i) { return method.GetParameters()[i].Name; } } } --- NEW FILE: ProxyInvokableAdapter.cs --- using System; using System.Collections; using System.Reflection; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; namespace NMock2.Monitoring { public class ProxyInvokableAdapter : RealProxy { private readonly IInvokable invokable; public ProxyInvokableAdapter(Type proxyType, IInvokable invokable ) : base(proxyType) { this.invokable = invokable; } public override IMessage Invoke(IMessage msg) { MethodCall call = new MethodCall(msg); ParameterInfo[] parameters = call.MethodBase.GetParameters(); Invocation invocation = new Invocation(GetTransparentProxy(), (MethodInfo)call.MethodBase, call.Args); invokable.Invoke(invocation); if (invocation.IsThrowing) { //TODO: it is impossible to set output parameters and throw an exception, // even though this is allowed by .NET method call semantics. return new ReturnMessage(invocation.Exception, call); } else { object[] outArgs = CollectOutputArguments(invocation, call, parameters); return new ReturnMessage( invocation.Result, outArgs, outArgs.Length, call.LogicalCallContext, call ); } } private static object[] CollectOutputArguments(Invocation invocation, MethodCall call, ParameterInfo[] parameters) { ArrayList outArgs = new ArrayList(call.ArgCount); for (int i = 0; i < call.ArgCount; i++) { if (!parameters[i].IsIn) outArgs.Add(invocation.Parameters[i]); } return outArgs.ToArray(); } } } --- NEW FILE: Invocation.cs --- using System; using System.IO; using System.Reflection; namespace NMock2.Monitoring { public class Invocation : ISelfDescribing { public readonly object Receiver; public readonly MethodInfo Method; public readonly ParameterList Parameters; private object result = null; private Exception exception = null; private bool isThrowing = false; public Invocation(object receiver, MethodInfo method, object[] parameters) { Receiver = receiver; Method = method; Parameters = new ParameterList(method, parameters); } public object Result { get { return result; } set { CheckReturnType(value); result = value; exception = null; isThrowing = false; } } private void CheckReturnType(object value) { if (Method.ReturnType == typeof(void) && value != null) { throw new ArgumentException("cannot return a value from a void method", "Result"); } if (Method.ReturnType != typeof(void) && Method.ReturnType.IsValueType && value == null) { throw new ArgumentException("cannot return a null value type", "Result"); } if (value != null && !Method.ReturnType.IsInstanceOfType(value)) { throw new ArgumentException("cannot return a value of type " + value.GetType() + " from a method returning " + Method.ReturnType, "Result"); } } public Exception Exception { get { return exception; } set { if (value == null) throw new ArgumentNullException("Exception"); exception = value; result = null; isThrowing = true; } } public bool IsThrowing { get { return isThrowing; } } public void InvokeOn(object otherReceiver) { try { Result = Method.Invoke(otherReceiver, Parameters.AsArray); Parameters.MarkAllValuesAsSet(); } catch(TargetInvocationException e) { Exception = e.InnerException; } } public void DescribeTo(TextWriter writer) { writer.Write(Receiver.ToString()); if (MethodIsIndexerGetter()) { DescribeAsIndexerGetter(writer); } else if (MethodIsIndexerSetter()) { DescribeAsIndexerSetter(writer); } else if (MethodIsEventAdder()) { DescribeAsEventAdder(writer); } else if (MethodIsEventRemover()) { DescribeAsEventRemover(writer); } else if (MethodIsProperty()) { DescribeAsProperty(writer); } else { DescribeNormalMethod(writer); } } private bool MethodIsProperty() { return Method.IsSpecialName && ((Method.Name.StartsWith("get_") && Parameters.Count == 0) || (Method.Name.StartsWith("set_") && Parameters.Count == 1)); } private bool MethodIsIndexerGetter() { return Method.IsSpecialName && Method.Name == "get_Item" && Parameters.Count >= 1; } private bool MethodIsIndexerSetter() { return Method.IsSpecialName && Method.Name == "set_Item" && Parameters.Count >= 2; } private bool MethodIsEventAdder() { return Method.IsSpecialName && Method.Name.StartsWith("add_") && Parameters.Count == 1 && typeof(Delegate).IsAssignableFrom(Method.GetParameters()[0].ParameterType); } private bool MethodIsEventRemover() { return Method.IsSpecialName && Method.Name.StartsWith("remove_") && Parameters.Count == 1 && typeof(Delegate).IsAssignableFrom(Method.GetParameters()[0].ParameterType); } private void DescribeAsProperty(TextWriter writer) { writer.Write("."); writer.Write(Method.Name.Substring(4)); if (Parameters.Count > 0) { writer.Write(" = "); writer.Write(Parameters[0]); } } private void DescribeAsIndexerGetter(TextWriter writer) { writer.Write("["); WriteParameterList(writer, Parameters.Count); writer.Write("]"); } private void DescribeAsIndexerSetter(TextWriter writer) { writer.Write("["); WriteParameterList(writer, Parameters.Count-1); writer.Write("] = "); writer.Write(Parameters[Parameters.Count-1]); } private void DescribeNormalMethod(TextWriter writer) { writer.Write("."); writer.Write(Method.Name); writer.Write("("); WriteParameterList(writer, Parameters.Count); writer.Write(")"); } private void WriteParameterList(TextWriter writer, int count) { for (int i = 0; i < count; i++) { if (i > 0) writer.Write(", "); if (Method.GetParameters()[i].IsOut) { writer.Write("out"); } else { writer.Write(Parameters[i]); } } } private void DescribeAsEventAdder(TextWriter writer) { writer.Write(" += "); writer.Write(Parameters[0]); } private void DescribeAsEventRemover(TextWriter writer) { writer.Write(" -= "); writer.Write(Parameters[0]); } } } |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:31
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Syntax In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2/Syntax Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2/Syntax added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:31
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Matchers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2/Matchers Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2/Matchers added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:29
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2.Test/Internal Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2.Test/Internal added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:29
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Monitoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2/Monitoring Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2/Monitoring added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:29
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Matchers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2.Test/Matchers Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2.Test/Matchers added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:29
|
Update of /cvsroot/nmock/nmock2/src/NMock2/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2/Internal Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2/Internal added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:29
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Monitoring In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2.Test/Monitoring Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2.Test/Monitoring added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:28
|
Update of /cvsroot/nmock/nmock2/src/NMock2.Test/Actions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2.Test/Actions Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2.Test/Actions added to the repository |
|
From: Steve F. <sm...@us...> - 2005-05-26 20:51:28
|
Update of /cvsroot/nmock/nmock2/src/NMock2.AcceptanceTests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23977/src/NMock2.AcceptanceTests Log Message: Directory /cvsroot/nmock/nmock2/src/NMock2.AcceptanceTests added to the repository |