Best JustMockLite code snippet using Telerik.JustMock.Tests.Baz.Test
NonPublicFixture.cs
Source:NonPublicFixture.cs  
...15using System.Collections.Generic;16using System.Linq;17using System.Reflection;18using System.Text;19#region JustMock Test Attributes20#if NUNIT21using NUnit.Framework;22using TestCategory = NUnit.Framework.CategoryAttribute;23using TestClass = NUnit.Framework.TestFixtureAttribute;24using TestMethod = NUnit.Framework.TestAttribute;25using TestInitialize = NUnit.Framework.SetUpAttribute;26using TestCleanup = NUnit.Framework.TearDownAttribute;27using AssertionException = NUnit.Framework.AssertionException;28#elif XUNIT29using Xunit;30using Telerik.JustMock.XUnit.Test.Attributes;31using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute;32using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute;33using TestMethod = Xunit.FactAttribute;34using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute;35using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute;36using AssertionException = Telerik.JustMock.XUnit.AssertFailedException;37#elif VSTEST_PORTABLE38using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;39using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException;40#else41using Microsoft.VisualStudio.TestTools.UnitTesting;42using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException;43#endif44#endregion45namespace Telerik.JustMock.Tests46{47	[TestClass]48	public class NonPublicFixture49	{50		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]51		public void ShouldMockProtectedVirtualMembers()52		{53			var foo = Mock.Create<Foo>(Behavior.CallOriginal);54			Mock.NonPublic.Arrange(foo, "Load").MustBeCalled();55			foo.Init();56			Mock.Assert(foo);57		}58		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]59		public void ShouldMockProtectedProperty()60		{61			var foo = Mock.Create<Foo>(Behavior.CallOriginal);62			Mock.NonPublic.Arrange<int>(foo, "IntValue").Returns(10);63			int ret = foo.GetMultipleOfIntValue();64			Assert.Equal(20, ret);65		}66		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]67		public void ShouldMockOverloadUsingMatchers()68		{69			var foo = Mock.Create<Foo>(Behavior.CallOriginal);70			bool called = false;71			Mock.NonPublic72				.Arrange(foo, "ExecuteProtected", Arg.Expr.IsAny<int>(), Arg.Expr.IsNull<Foo>())73				.DoInstead(() => called = true);74			foo.Execute(10, null);75			Assert.True(called);76		}77		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]78		public void ShouldMockOverloadUsingConcreteValues()79		{80			var foo = Mock.Create<Foo>(Behavior.CallOriginal);81			bool called = false, called2 = false;82			Mock.NonPublic83				.Arrange(foo, "ExecuteProtected", 10, Arg.Expr.IsNull<FooDerived>())84				.DoInstead(() => called = true);85			Mock.NonPublic86				.Arrange(foo, "ExecuteProtected", Arg.Expr.IsNull<FooDerived>(), 10)87				.DoInstead(() => called2 = true);88			foo.Execute(10, null);89			foo.Execute(null, 10);90			Assert.True(called);91			Assert.True(called2);92		}93		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]94		public void ShouldThrowArgumentExpectionForNullArguments()95		{96			var foo = Mock.Create<Foo>(Behavior.CallOriginal);97			Assert.Throws<ArgumentException>(() => Mock.NonPublic.Arrange(foo, "ExecuteProtected", 0, null));98		}99		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]100		public void ShouldAssertNonPublicActions()101		{102			var foo = Mock.Create<Foo>(Behavior.CallOriginal);103			Mock.NonPublic.Arrange(foo, "ExecuteProtected", 10);104			foo.Execute(10);105			// assert if called as expected.106			Mock.NonPublic.Assert(foo, "ExecuteProtected", 10);107		}108		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]109		public void ShouldAssertNonPublicFunctions()110		{111			var foo = Mock.Create<Foo>(Behavior.CallOriginal);112			Mock.NonPublic.Arrange<int>(foo, "IntValue").Returns(10);113			foo.GetMultipleOfIntValue();114			Mock.NonPublic.Assert<int>(foo, "IntValue");115		}116		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]117		public void ShouldThrowForAssertingCallsThatWereNotInvoked()118		{119			var foo = Mock.Create<Foo>(Behavior.CallOriginal);120			Mock.NonPublic.Arrange(foo, "ExecuteProtected", 10);121			// assert if called as expected.122			Assert.Throws<AssertionException>(() => Mock.NonPublic.Assert(foo, "ExecuteProtected", 10));123		}124		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]125		public void ShouldAssertOccrenceForNonPublicFunction()126		{127			var foo = Mock.Create<Foo>(Behavior.CallOriginal);128			Mock.NonPublic.Assert<int>(foo, "IntValue", Occurs.Never());129		}130		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]131		public void ShouldAssertOccurenceForNonPublicAction()132		{133			var foo = Mock.Create<Foo>(Behavior.CallOriginal);134			Mock.NonPublic.Arrange(foo, "ExecuteProtected", 10);135			foo.Execute(10);136			Mock.NonPublic.Assert(foo, "ExecuteProtected", Occurs.Exactly(1), 10);137		}138		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]139		public void ShouldThrowMissingMethodExceptionForMethodSpecification()140		{141			var foo = Mock.Create<Foo>(Behavior.CallOriginal);142			Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "ExecuteProtected"));143		}144#if !SILVERLIGHT145		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]146		public void ShouldCreateMockFromClassHavingAbstractInternalMethodInBase()147		{148			var foo = Mock.Create<FooAbstract2>();149			foo.TryCreateToken(string.Empty);150		}151		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]152		public void ShouldMockTypeWithInternalCtorWhenInternalVisibleToIsApplied()153		{154			// Provided that InternalsVisibleTo attribute is included in assemblyinfo.cs.155			var foo = Mock.Create<FooInternal>(Behavior.CallOriginal);156			Assert.NotNull(foo.Builder);157		}158		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]159		public void ShouldAssertNonPublicMethodFromBase()160		{161			var baz = Mock.Create<Baz>(Behavior.CallOriginal);162			const string targetMethod = "MethodToMock";163			Mock.NonPublic.Arrange(baz, targetMethod).DoNothing();164			baz.MethodToTest();165			Mock.NonPublic.Assert(baz, targetMethod);166		}167#if !PORTABLE168		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]169		public void ShouldAssertNonPublicCallWhenOccurrenceIsApplied()170		{171			var baz = Mock.Create<Bar>(Behavior.CallOriginal);172			const string targetMethod = "MethodToMock";173			Mock.NonPublic.Arrange(baz, targetMethod).OccursOnce();174			baz.GetType().GetMethod(targetMethod, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(baz, null);175			Mock.NonPublic.Assert(baz, targetMethod);176		}177		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic"), TestCategory("Assertion")]178		public void ShouldGetTimesCalledOfNonPublicMethod()179		{180			var mock = Mock.Create<Bar>();181			Mock.NonPublic.MakePrivateAccessor(mock).CallMethod("MethodToMock");182			Assert.Equal(1, Mock.NonPublic.GetTimesCalled(mock, "MethodToMock"));183			Assert.Equal(1, Mock.NonPublic.GetTimesCalled(mock, typeof(Bar).GetMethod("MethodToMock", BindingFlags.NonPublic | BindingFlags.Instance)));184		}185#endif186		public class Bar187		{188			protected virtual void MethodToMock()189			{190				throw new ArgumentException("Base method Invoked");191			}192		}193		public class Baz : Bar194		{195			public virtual void MethodToTest()196			{197				MethodToMock();198			}199		}200		internal class FooInternal201		{202			internal FooInternal()203			{204				builder = new StringBuilder();205			}206			public StringBuilder Builder207			{208				get209				{210					return builder;211				}212			}213			private StringBuilder builder;214		}215#endif216		internal abstract class FooAbstract217		{218			protected internal abstract bool TryCreateToken(string literal);219		}220		internal abstract class FooAbstract2 : FooAbstract221		{222		}223		public class Foo224		{225			protected virtual void ExecuteProtected(Foo foo, int arg1)226			{227				throw new NotImplementedException();228			}229			protected virtual void ExecuteProtected(int arg1, Foo foo)230			{231				throw new NotImplementedException();232			}233			protected virtual void ExecuteProtected(int arg1)234			{235				throw new NotImplementedException();236			}237			public virtual void Execute(int arg1)238			{239				ExecuteProtected(arg1);240			}241			public virtual void Execute(int arg1, Foo foo)242			{243				ExecuteProtected(arg1, foo);244			}245			public virtual void Execute(Foo foo, int arg1)246			{247				ExecuteProtected(foo, arg1);248			}249			protected virtual void Load()250			{251				throw new NotImplementedException();252			}253			protected virtual int IntValue254			{255				get256				{257					throw new NotImplementedException();258				}259			}260			public virtual void Init()261			{262				Load();263			}264			public virtual int GetMultipleOfIntValue()265			{266				return IntValue * 2;267			}268		}269		public class FooDerived : Foo270		{271		}272		public class RefTest273		{274			protected virtual void Test(string arg1, ref string asd)275			{276			}277			public void ExecuteTest(ref string asd)278			{279				this.Test("test1", ref asd);280			}281		}282		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]283		public void ShouldArrangeNonPublicUsingByRefArgumentWithMatcher()284		{285			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);286			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Ref(Arg.Expr.IsAny<string>())).MustBeCalled();287			string asd = "asd";288			foo.ExecuteTest(ref asd);289			Mock.Assert(foo);290		}291		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]292		public void ShouldArrangeNonPublicUsingByRefArgumentWithConstant()293		{294			int call = 1;295			int callA = 0, callB = 0;296			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);297			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Ref(Arg.Expr.IsAny<string>())).DoInstead(() => callB = call++);298			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Ref("asd")).DoInstead(() => callA = call++);299			string input = "asd";300			foo.ExecuteTest(ref input);301			input = "foo";302			foo.ExecuteTest(ref input);303			Assert.Equal(1, callA);304			Assert.Equal(2, callB);305		}306		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]307		public void ShouldArrangeNonPublicUsingByRefArgumentAsOutputParameter()308		{309			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);310			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Out("asd"));311			string input = "";312			foo.ExecuteTest(ref input);313			Assert.Equal("asd", input);314		}315		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]316		public void ShouldNotArrangeNonPublicUsingConstantArgumentWhereByRefIsExpected()317		{318			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);319			Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), "asd"));320		}321		public abstract class WeirdSignature322		{323			protected abstract int Do(int a, string b, ref object c, IEnumerable<int> d);324			protected abstract void Do(bool b);325			protected abstract DateTime Do(DateTime dateTime);326			protected static void Do(int d) { }327			protected static int Do(char e) { return 0; }328		}329		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]330		public void ShouldProvideHelpfulExceptionMessageWhenNonPublicMethodIsMissing()331		{332			var foo = Mock.Create<WeirdSignature>();333			var exception = Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "Do"));334			var message = exception.Message;335			Assert.Equal(("Method 'Do' with the given signature was not found on type Telerik.JustMock.Tests.NonPublicFixture+WeirdSignature\r\n" +336"Review the available methods in the message below and optionally paste the appropriate arrangement snippet.\r\n" +337"----------\r\n" +338"Method 1: Int32 Do(Int32, System.String, System.Object ByRef, System.Collections.Generic.IEnumerable`1[System.Int32])\r\n" +339"C#: Mock.NonPublic.Arrange<int>(mock, \"Do\", Arg.Expr.IsAny<int>(), Arg.Expr.IsAny<string>(), Arg.Expr.Ref(Arg.Expr.IsAny<object>()), Arg.Expr.IsAny<IEnumerable<int>>());\r\n" +340"VB: Mock.NonPublic.Arrange(Of Integer)(mock, \"Do\", Arg.Expr.IsAny(Of Integer)(), Arg.Expr.IsAny(Of String)(), Arg.Expr.Ref(Arg.Expr.IsAny(Of Object)()), Arg.Expr.IsAny(Of IEnumerable(Of Integer))())\r\n" +341"----------\r\n" +342"Method 2: Void Do(Boolean)\r\n" +343"C#: Mock.NonPublic.Arrange(mock, \"Do\", Arg.Expr.IsAny<bool>());\r\n" +344"VB: Mock.NonPublic.Arrange(mock, \"Do\", Arg.Expr.IsAny(Of Boolean)())\r\n" +345"----------\r\n" +346"Method 3: System.DateTime Do(System.DateTime)\r\n" +347"C#: Mock.NonPublic.Arrange<DateTime>(mock, \"Do\", Arg.Expr.IsAny<DateTime>());\r\n" +348"VB: Mock.NonPublic.Arrange(Of Date)(mock, \"Do\", Arg.Expr.IsAny(Of Date)())\r\n" +349"----------\r\n" +350"Method 4: Void Do(Int32)\r\n" +351"C#: Mock.NonPublic.Arrange(\"Do\", Arg.Expr.IsAny<int>());\r\n" +352"VB: Mock.NonPublic.Arrange(\"Do\", Arg.Expr.IsAny(Of Integer)())\r\n" +353"----------\r\n" +354"Method 5: Int32 Do(Char)\r\n" +355"C#: Mock.NonPublic.Arrange<int>(\"Do\", Arg.Expr.IsAny<char>());\r\n" +356"VB: Mock.NonPublic.Arrange(Of Integer)(\"Do\", Arg.Expr.IsAny(Of Char)())\r\n").Replace("\r\n", Environment.NewLine), message);357			var exception2 = Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "Dont"));358			var message2 = exception2.Message;359			Assert.Equal(("Method 'Dont' with the given signature was not found on type Telerik.JustMock.Tests.NonPublicFixture+WeirdSignature\r\n" +360				"No methods or properties found with the given name.\r\n").Replace("\r\n", Environment.NewLine), message2);361		}362		public abstract class NonPublicOverloads363		{364			protected abstract int NotOverloaded(int a, out object b);365			protected abstract int Overloaded(int a);366			protected abstract int Overloaded(string a);367			protected abstract int Prop { set; }368			public int CallNotOverloaded(int a, out object b)369			{370				return NotOverloaded(a, out b);371			}372			public int SetProp373			{374				set { Prop = value; }375			}376		}377		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]378		public void ShouldQuickArrangeNonPublicNonOverloadedMethod()379		{380			var mock = Mock.Create<NonPublicOverloads>(Behavior.CallOriginal);381			Mock.NonPublic.Arrange<int>(mock, "NotOverloaded").Returns(5);382			object b;383			var result = mock.CallNotOverloaded(5, out b);384			Assert.Equal(5, result);385		}386		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]387		public void ShouldQuickArrangeNonPublicSetter()388		{389			var mock = Mock.Create<NonPublicOverloads>(Behavior.CallOriginal);390			bool called = false;391			Mock.NonPublic.Arrange(mock, "Prop").DoInstead(() => called = true);392			mock.SetProp = 5;393			Assert.True(called);394		}395		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]396		public void ShouldFailToQuickArrangeNonPublicOverloadedMethods()397		{398			var mock = Mock.Create<NonPublicOverloads>();399			Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange<int>(mock, "Overloaded"));400		}401		public abstract class GenericTest402		{403			protected abstract T Do<T>(T x);404			protected abstract IEnumerable<T> Enumerate<T>();405			public int TestDo()406			{407				return Do(10);408			}409			public IEnumerable<int> TestEnumerate()410			{411				return Enumerate<int>();412			}413		}414		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]415		public void ShouldArrangeNonPublicMethodReturningGenericValue()416		{417			var mock = Mock.Create<GenericTest>(Behavior.CallOriginal);418			Mock.NonPublic.Arrange<int>(mock, "Do", Arg.Expr.IsAny<int>()).Returns(123);419			Assert.Equal(123, mock.TestDo());420		}421		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]422		public void ShouldArrangeNonPublicMethodReturningGenericValueComplexType()423		{424			var mock = Mock.Create<GenericTest>(Behavior.CallOriginal);425			Mock.NonPublic.Arrange<IEnumerable<int>>(mock, "Enumerate").Returns(new[] { 123 });426			var actual = mock.TestEnumerate().ToArray();427			Assert.Equal(1, actual.Length);428			Assert.Equal(123, actual[0]);429		}430	}431}...RecursiveFixture.cs
Source:RecursiveFixture.cs  
...14using System;15using System.Collections.Generic;16using System.Linq;17using Telerik.JustMock.Core;18#region JustMock Test Attributes19#if NUNIT20using NUnit.Framework;21using TestCategory = NUnit.Framework.CategoryAttribute;22using TestClass = NUnit.Framework.TestFixtureAttribute;23using TestMethod = NUnit.Framework.TestAttribute;24using TestInitialize = NUnit.Framework.SetUpAttribute;25using TestCleanup = NUnit.Framework.TearDownAttribute;26using AssertionException = NUnit.Framework.AssertionException;27#elif XUNIT28using Xunit;29using Telerik.JustMock.XUnit.Test.Attributes;30using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute;31using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute;32using TestMethod = Xunit.FactAttribute;33using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute;34using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute;35using AssertionException = Telerik.JustMock.XUnit.AssertFailedException;36#elif VSTEST_PORTABLE37using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;38using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException;39#else40using Microsoft.VisualStudio.TestTools.UnitTesting;41using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException;42#endif43#endregion44#if PORTABLE45[assembly: Telerik.JustMock.MockedType(typeof(Telerik.JustMock.Tests.RecursiveFixture.ValidateMember))]46#endif47#if XUNIT248#pragma warning disable xUnit1013 49#endif50namespace Telerik.JustMock.Tests51{52	[TestClass]53	public class RecursiveFixture54	{55		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]56		public void ShouldAssertNestedPropertySetups()57		{58			var foo = Mock.Create<IFoo>();59			Mock.Arrange(() => foo.Bar.Value).Returns(10);60			Assert.Equal(10, foo.Bar.Value);61		}62		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]63		public void ShouldAssertNestedProperyCallsAsEqual()64		{65			var foo = Mock.Create<IFoo>();66			var b1 = foo.Bar;67			var b2 = foo.Bar;68			Assert.NotNull(b1);69			Assert.Same(b1, b2);70		}71		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]72		public void ShouldAssertNestedSetupWithSimilarMethods()73		{74			var foo = Mock.Create<IFoo>();75			Mock.Arrange(() => foo.Bar.Do("x")).Returns("xit");76			Mock.Arrange(() => foo.Bar1.Baz.Do("y")).Returns("yit");77			Assert.Equal(foo.Bar.Do("x"), "xit");78			Assert.Equal(foo.Bar1.Baz.Do("y"), "yit");79		}80		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]81		public void ShouldAssertNestedSetupForSimilarRootAndSimilarMethods()82		{83			var foo = Mock.Create<IFoo>();84			Mock.Arrange(() => foo.Bar.Do("x")).Returns("xit");85			Mock.Arrange(() => foo.Bar.Baz.Do("y")).Returns("yit");86			Assert.Equal(foo.Bar.Do("x"), "xit");87			Assert.Equal(foo.Bar.Baz.Do("y"), "yit");88		}89		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]90		public void ShouldNotAutoInstantiateIfNotArranged()91		{92			var foo = Mock.Create<IFoo>(Behavior.Loose);93			Assert.Equal(foo.Bar, null);94		}95		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]96		public void ShouldAssertNestedPropertySet()97		{98			var foo = Mock.Create<IFoo>(Behavior.Strict);99			Mock.ArrangeSet<IFoo>(() => { foo.Bar.Value = 5; }).DoNothing();100			Assert.Throws<MockException>(() => foo.Bar.Value = 10);101			foo.Bar.Value = 5;102			Assert.NotNull(foo.Bar);103		}104		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]105		public void ShouldAssertNestedVerifables()106		{107			var foo = Mock.Create<IFoo>();108			string ping = "ping";109			Mock.Arrange(() => foo.Do(ping)).Returns("ack");110			Mock.Arrange(() => foo.Bar.Do(ping)).Returns("ack2");111			Assert.Equal(foo.Do(ping), "ack");112			var bar = foo.Bar;113			Assert.Throws<AssertionException>(() => Mock.Assert(() => foo.Bar.Do(ping)));114			Assert.Equal(foo.Bar.Do(ping), "ack2");115			Mock.Assert(() => foo.Bar.Do(ping));116		}117#if !SILVERLIGHT118		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]119		public void ShouldNotAutoCreateNestedInstanceWhenSetExplictly()120		{121			var foo = Mock.Create<Foo>();122			foo.Bar = Mock.Create(() => new Bar(10));123			Mock.Arrange(() => foo.Bar.Echo()).CallOriginal();124			Assert.Equal(10, foo.Bar.Echo());125		}126#endif127		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]128		public void ShouldMockIEnumerableImplementer()129		{130			var regionManager = Mock.Create<IRegionManager>();131			Mock.Arrange(() => regionManager.Regions["SomeRegion"]).Returns(5);132			Assert.Equal(5, regionManager.Regions["SomeRegion"]);133		}134		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]135		public void ShouldMockIDictionaryImplementer()136		{137			var regionManager = Mock.Create<IRegionManager>();138			Mock.Arrange(() => regionManager.RegionsByName["SomeRegion"]).Returns(5);139			Assert.Equal(5, regionManager.RegionsByName["SomeRegion"]);140		}141		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]142		public void ShouldRaiseEventsFromMockIEnumerable()143		{144			var regionManager = Mock.Create<IRegionManager>();145			Mock.Arrange(() => regionManager.Regions[""]).Returns(new object()); // auto-arrange Regions with mock collection146			bool ienumerableEventRaised = false;147			regionManager.Regions.CollectionChanged += (o, e) => ienumerableEventRaised = true;148			Mock.Raise(() => regionManager.Regions.CollectionChanged += null, EventArgs.Empty);149			Assert.True(ienumerableEventRaised);150		}151		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]152		public void ShouldRaiseEventsFromMockIDictionary()153		{154			var regionManager = Mock.Create<IRegionManager>();155			Mock.Arrange(() => regionManager.RegionsByName[""]).Returns(new object()); // auto-arrange RegionsByName with mock collection156			bool idictionaryEventRaised = false;157			regionManager.Regions.CollectionChanged += (o, e) => idictionaryEventRaised = true;158			Mock.Raise(() => regionManager.Regions.CollectionChanged += null, EventArgs.Empty);159			Assert.True(idictionaryEventRaised);160		}161		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]162		public void ShouldBeAbleToEnumerateMockEnumerable()163		{164			var mock = Mock.Create<IDataLocator>();165			Assert.Equal(0, mock.RecentEvents.Count());166		}167		private IMatrix Matrix { get; set; }168		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]169		public void ShouldNotAutoArrangeIfPropertyInThis()170		{171			var mockedMatrix = Mock.Create<IMatrix>();172			this.Matrix = mockedMatrix;173			var mockedArray = new object[0];174			Mock.Arrange(() => Matrix.Raw).Returns(mockedArray);175			Assert.Equal(mockedMatrix, this.Matrix);176			Assert.Equal(mockedArray, this.Matrix.Raw);177		}178		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]179		public void ShouldReturnNullOnLoose()180		{181			var foo = Mock.Create<IFoo>(Behavior.Loose);182			Assert.Null(foo.Bar);183		}184		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]185		public void ShouldAutoMockInArrangeOnLoose()186		{187			var foo = Mock.Create<IFoo>(Behavior.Loose);188			Mock.Arrange(() => foo.Bar.Baz);189			Assert.NotNull(foo.Bar);190		}191		public interface IRegionManager192		{193			IRegionCollection Regions { get; }194			IRegionLookup RegionsByName { get; }195		}196		public interface IRegionCollection : IEnumerable<object>197		{198			object this[string regionName] { get; }199			event EventHandler CollectionChanged;200		}201		public interface IRegionLookup : IDictionary<string, object>202		{203			object this[string regionName] { get; }204			event EventHandler CollectionChanged;205		}206		public interface IMatrix207		{208			Array Raw { get; }209		}210		public interface IDataLocator211		{212			IDataFeed RecentEvents { get; }213		}214		public interface IDataFeed : IEnumerable<object>215		{ }216		public class Bar217		{218			int arg1;219			public Bar(int arg1)220			{221				this.arg1 = arg1;222			}223			public virtual int Echo()224			{225				return arg1;226			}227		}228		public class Foo229		{230			public virtual Bar Bar { get; set; }231		}232		public interface IFoo233		{234			IBar Bar { get; set; }235			IBar Bar1 { get; set; }236			IBar this[int index] { get; set; }237			string Do(string command);238		}239		public interface IBar240		{241			int Value { get; set; }242			string Do(string command);243			IBaz Baz { get; set; }244			IBaz GetBaz(string value);245		}246		public interface IBaz247		{248			int Value { get; set; }249			string Do(string command);250			void Do();251		}252		public abstract class ValidateMember253		{254			public readonly object session;255			public ValidateMember(object session)256			{257				this.session = session;258			}259			public abstract bool With(string model);260		}261		public interface IServiceProvider262		{263			T Query<T>();264		}265		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]266		public void ShouldRecursivelyArrangeGenericMethod()267		{268			var service = Mock.Create<IServiceProvider>();269			Mock.Arrange(() => service.Query<ValidateMember>().With("me")).Returns(true);270			var actual = service.Query<ValidateMember>().With("me");271			Assert.Equal(true, actual);272		}273		public interface IBenefits274		{275		}276		public interface IOuter277		{278			IEnumerableWithBenefits Bar { get; }279			IDictionaryWithBenefits Dict { get; }280		}281		public interface IEnumerableWithBenefits : IEnumerable<Object>282		{283			IBenefits GetBaz();284		}285		public interface IDictionaryWithBenefits : IDictionary<string, int>286		{287			IBenefits GetBaz();288		}289		[TestMethod, TestCategory("Lite"), TestCategory("Recursive")]290		public void ShouldMockRecursivelyCustomMembersOnIEnumerable()291		{292			var foo = Mock.Create<IOuter>(Behavior.RecursiveLoose);293			Assert.NotNull(foo.Bar.GetBaz());294			Assert.NotNull(foo.Dict.GetBaz());295		}296	}297	[TestClass]298	public class RecursiveMockRepositoryInheritance299	{300		public interface IDataItem301		{302			int Id { get; }303		}304		public interface IDataProcessor305		{306			IDataItem Item { get; }307		}308		private IDataProcessor mock;309#if XUNIT310		public RecursiveMockRepositoryInheritance()311		{312			BeforeEach();313		}314#endif315		[TestInitialize]316		public void BeforeEach()317		{318			mock = Mock.Create<IDataProcessor>();319		}320		[TestMethod, TestCategory("Lite"), TestCategory("MockingContext"), TestCategory("Recursive")]321		public void ShouldSetUseContextualRepositoryForRecursiveMock()322		{323			Mock.Arrange(() => mock.Item.Id).Returns(5);324			Assert.Equal(5, mock.Item.Id);325		}326	}327}...RecursiveMocking.cs
Source:RecursiveMocking.cs  
...11   See the License for the specific language governing permissions and12   limitations under the License.13*/14using System;15using Microsoft.VisualStudio.TestTools.UnitTesting;16using Telerik.JustMock;17namespace JustMock.NonElevatedExamples.BasicUsage.RecursiveMocking18{19    /// <summary>20    /// Recursive mocks enable you to mock members that are obtained as a result of "chained" calls on a mock. 21    /// For example, recursive mocking is useful in the cases when you test code like this: foo.Bar.Baz.Do("x"). 22    /// See http://www.telerik.com/help/justmock/basic-usage-recursive-mocking.html for full documentation of the feature.23    /// </summary>24    [TestClass]25    public class RecursiveMocking_Tests26    {27        [TestMethod]28        public void ShouldAssertNestedVeriables()29        {30            string pingArg = "ping";31            var expected = "test";32            // ARRANGE33            // Creating a mocked instance of the "IFoo" interface.34            var foo = Mock.Create<IFoo>();35            // Arranging: When foo.Bar.Do() is called, it should return the expected string. 36            //              This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.37            Mock.Arrange(() => foo.Bar.Do(pingArg)).Returns(expected);38            // ACT39            var actualFooBarDo = foo.Bar.Do(pingArg);40            // ASSERT41            Assert.AreEqual(expected, actualFooBarDo);42        }43        [TestMethod]44        public void ShouldInstantiateFooBar()45        {46            // ARRANGE47            // Creating a mocked instance of the "IFoo" interface.48            var foo = Mock.Create<IFoo>();49            // ASSERT - Not arranged members in a RecursiveLoose mocks should not be null.50            Assert.IsNotNull(foo.Bar);51        }52        [TestMethod]53        public void ShouldAssertNestedPropertyGet()54        {55            var expected = 10;56            // ARRANGE57            // Creating a mocked instance of the "IFoo" interface.58            var foo = Mock.Create<IFoo>();59            // Arranging: When foo.Bar.Value is called, it should return expected value. 60            //              This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.61            Mock.Arrange(() => foo.Bar.Value).Returns(expected);62            // ACT63            var actual = foo.Bar.Value;64            // ASSERT65            Assert.AreEqual(expected, actual);66        }67        [TestMethod]68        public void ShouldAssertNestedPropertySet()69        {70            // ARRANGE71            // Creating a mocked instance of the "IFoo" interface.72            var foo = Mock.Create<IFoo>();73            // Arranging: Setting foo.Bar.Value to 5, should do nothing. 74            //              This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.75            Mock.ArrangeSet<IFoo>(() => { foo.Bar.Value = 5; }).DoNothing().MustBeCalled();76            // ACT77            foo.Bar.Value = 5;78            // ASSERT79            Mock.Assert(foo);80        }81        [TestMethod]82        public void NestedPropertyAndMethodCalls()83        {84            // ARRANGE85            // Creating a mocked instance of the "IFoo" interface.86            var foo = Mock.Create<IFoo>();87            // Arranging: When foo.Bar.Do() is called with "x" as an argument, it return "xit". 88            //              This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.89            Mock.Arrange(() => foo.Bar.Do("x")).Returns("xit");90            // Arranging: When foo.Bar.Baz.Do() is called with "y" as an argument, it return "yit". 91            //              This will automatically create mock of foo.Bar and foo.Bar.Baz and a 92            //              NullReferenceException will be avoided.93            Mock.Arrange(() => foo.Bar.Baz.Do("y")).Returns("yit");94            // ACT95            var actualFooBarDo = foo.Bar.Do("x");...Test
Using AI Code Generation
1using Telerik.JustMock.Tests;2{3    {4        public void Bar()5        {6            Baz baz = new Baz();7            baz.Test();8        }9    }10}11using Telerik.JustMock.Tests;12{13    {14        public void Bar()15        {16            Baz baz = new Baz();17            baz.Test();18        }19    }20}Test
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Telerik.JustMock;7using Telerik.JustMock.Helpers;8{9    {10        public void Bar()11        {12            var mock = Mock.Create<Baz>();13            Mock.Arrange(() => mock.Test(Arg.AnyInt)).Returns(1);14            int result = mock.Test(1);15        }16    }17}18using System;19using System.Collections.Generic;20using System.Linq;21using System.Text;22using System.Threading.Tasks;23using Telerik.JustMock;24using Telerik.JustMock.Helpers;25{26    {27        public void Bar()28        {29            var mock = Mock.Create<Baz>();30            Mock.Arrange(() => mock.Test(Arg.AnyInt)).Returns(1);31            int result = mock.Test(1);32        }33    }34}Test
Using AI Code Generation
1Baz baz = Mock.Create<Baz>();2Mock.Arrange(() => baz.Test()).Returns(5);3Assert.AreEqual(5, baz.Test());4Baz baz = Mock.Create<Baz>();5Mock.Arrange(() => baz.Test()).Returns(5);6Assert.AreEqual(5, baz.Test());7Baz baz = Mock.Create<Baz>();8Mock.Arrange(() => baz.Test()).Returns(5);9Assert.AreEqual(5, baz.Test());10Baz baz = Mock.Create<Baz>();11Mock.Arrange(() => baz.Test()).Returns(5);12Assert.AreEqual(5, baz.Test());13Baz baz = Mock.Create<Baz>();14Mock.Arrange(() => baz.Test()).Returns(5);15Assert.AreEqual(5, baz.Test());16Baz baz = Mock.Create<Baz>();17Mock.Arrange(() => baz.Test()).Returns(5);18Assert.AreEqual(5, baz.Test());19Baz baz = Mock.Create<Baz>();20Mock.Arrange(() => baz.Test()).Returns(5);21Assert.AreEqual(5, baz.Test());22Baz baz = Mock.Create<Baz>();23Mock.Arrange(() => baz.Test()).Returns(5);24Assert.AreEqual(5, baz.Test());25Baz baz = Mock.Create<Baz>();26Mock.Arrange(() => baz.Test()).Returns(5);27Assert.AreEqual(5, baz.Test());28Baz baz = Mock.Create<Baz>();29Mock.Arrange(() => baz.Test()).Returns(5Test
Using AI Code Generation
1using Telerik.JustMock.Tests;2{3    {4        public virtual void Test()5        {6        }7    }8}9using Telerik.JustMock.Tests;10{11    {12        public virtual void Test()13        {14        }15    }16}17using Telerik.JustMock.Tests;18{19    {20        public virtual void Test()21        {22        }23    }24}25using Telerik.JustMock.Tests;26{27    {28        public virtual void Test()29        {30        }31    }32}33using Telerik.JustMock.Tests;34{35    {36        public virtual void Test()37        {38        }39    }40}41using Telerik.JustMock.Tests;42{43    {44        public virtual void Test()45        {46        }47    }48}49using Telerik.JustMock.Tests;50{51    {52        public virtual void Test()53        {54        }55    }56}57using Telerik.JustMock.Tests;58{59    {60        public virtual void Test()61        {62        }63    }64}65using Telerik.JustMock.Tests;66{67    {68        public virtual void Test()69        {70        }71    }72}Test
Using AI Code Generation
1using Telerik.JustMock.Tests;2Baz baz = Mock.Create<Baz>();3Mock.Arrange(() => baz.Test()).Returns(1);4using Telerik.JustMock.Tests;5Baz baz = Mock.Create<Baz>();6Mock.Arrange(() => baz.Test()).Returns(1);7using Telerik.JustMock.Tests;8Baz baz = Mock.Create<Baz>();9Mock.Arrange(() => baz.Test()).Returns(1);10using Telerik.JustMock.Tests;11Baz baz = Mock.Create<Baz>();12Mock.Arrange(() => baz.Test()).Returns(1);13using Telerik.JustMock.Tests;14Baz baz = Mock.Create<Baz>();15Mock.Arrange(() => baz.Test()).Returns(1);Test
Using AI Code Generation
1mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");2Assert.AreEqual("Test", baz.Test("foo"));3mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");4Assert.AreEqual("Test", baz.Test("foo"));5mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");6Assert.AreEqual("Test", baz.Test("foo"));7mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");8Assert.AreEqual("Test", baz.Test("foo"));9mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");10Assert.AreEqual("Test", baz.Test("foo"));11mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");12Assert.AreEqual("Test", baz.Test("foo"));13mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");14Assert.AreEqual("Test", baz.Test("foo"));15mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");16Assert.AreEqual("Test", baz.Test("foo"));17mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");18Assert.AreEqual("Test", baz.Test("foo"));19mock.Arrange(() => baz.Test(Arg.AnyString)).Returns("Test");20Assert.AreEqual("Test", baz.Test("foo"));21mock.Arrange(() => baz.TestLearn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
