How to use NonPublicFixture class of Telerik.JustMock.Tests package

Best JustMockLite code snippet using Telerik.JustMock.Tests.NonPublicFixture

Run JustMockLite automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

NonPublicFixture.cs

Source: NonPublicFixture.cs Github

copy
1/*
2 JustMock Lite
3 Copyright © 2010-2015 Progress Software Corporation
4
5   Licensed under the Apache License, Version 2.0 (the "License");
6   you may not use this file except in compliance with the License.
7   You may obtain a copy of the License at
8
9   http://www.apache.org/licenses/LICENSE-2.0
10
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16*/
17
18using System;
19using System.Collections.Generic;
20using System.Linq;
21using System.Reflection;
22using System.Text;
23
24
25#region JustMock Test Attributes
26#if NUNIT
27using NUnit.Framework;
28using TestCategory = NUnit.Framework.CategoryAttribute;
29using TestClass = NUnit.Framework.TestFixtureAttribute;
30using TestMethod = NUnit.Framework.TestAttribute;
31using TestInitialize = NUnit.Framework.SetUpAttribute;
32using TestCleanup = NUnit.Framework.TearDownAttribute;
33using AssertionException = NUnit.Framework.AssertionException;
34#elif XUNIT
35using Xunit;
36using Telerik.JustMock.XUnit.Test.Attributes;
37using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute;
38using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute;
39using TestMethod = Xunit.FactAttribute;
40using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute;
41using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute;
42using AssertionException = Telerik.JustMock.XUnit.AssertFailedException;
43#elif VSTEST_PORTABLE
44using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
45using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException;
46#else
47using Microsoft.VisualStudio.TestTools.UnitTesting;
48using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException;
49#endif
50#endregion
51
52
53
54namespace Telerik.JustMock.Tests
55{
56	[TestClass]
57	public class NonPublicFixture
58	{
59		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
60		public void ShouldMockProtectedVirtualMembers()
61		{
62			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
63
64			Mock.NonPublic.Arrange(foo, "Load").MustBeCalled();
65
66			foo.Init();
67
68			Mock.Assert(foo);
69		}
70
71		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
72		public void ShouldMockProtectedProperty()
73		{
74			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
75
76			Mock.NonPublic.Arrange<int>(foo, "IntValue").Returns(10);
77
78			int ret = foo.GetMultipleOfIntValue();
79
80			Assert.Equal(20, ret);
81		}
82
83		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
84		public void ShouldMockOverloadUsingMatchers()
85		{
86			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
87
88			bool called = false;
89
90			Mock.NonPublic
91				.Arrange(foo, "ExecuteProtected", Arg.Expr.IsAny<int>(), Arg.Expr.IsNull<Foo>())
92				.DoInstead(() => called = true);
93
94			foo.Execute(10, null);
95
96			Assert.True(called);
97		}
98
99		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
100		public void ShouldMockOverloadUsingConcreteValues()
101		{
102			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
103
104			bool called = false, called2 = false;
105
106			Mock.NonPublic
107				.Arrange(foo, "ExecuteProtected", 10, Arg.Expr.IsNull<FooDerived>())
108				.DoInstead(() => called = true);
109
110			Mock.NonPublic
111				.Arrange(foo, "ExecuteProtected", Arg.Expr.IsNull<FooDerived>(), 10)
112				.DoInstead(() => called2 = true);
113
114			foo.Execute(10, null);
115			foo.Execute(null, 10);
116
117			Assert.True(called);
118			Assert.True(called2);
119		}
120
121		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
122		public void ShouldThrowArgumentExpectionForNullArguments()
123		{
124			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
125			Assert.Throws<ArgumentException>(() => Mock.NonPublic.Arrange(foo, "ExecuteProtected", 0, null));
126		}
127
128		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
129		public void ShouldAssertNonPublicActions()
130		{
131			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
132
133			Mock.NonPublic.Arrange(foo, "ExecuteProtected", 10);
134
135			foo.Execute(10);
136
137			// assert if called as expected.
138			Mock.NonPublic.Assert(foo, "ExecuteProtected", 10);
139		}
140
141		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
142		public void ShouldAssertNonPublicFunctions()
143		{
144			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
145
146			Mock.NonPublic.Arrange<int>(foo, "IntValue").Returns(10);
147
148			foo.GetMultipleOfIntValue();
149
150			Mock.NonPublic.Assert<int>(foo, "IntValue");
151		}
152
153		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
154		public void ShouldThrowForAssertingCallsThatWereNotInvoked()
155		{
156			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
157
158			Mock.NonPublic.Arrange(foo, "ExecuteProtected", 10);
159
160			// assert if called as expected.
161			Assert.Throws<AssertionException>(() => Mock.NonPublic.Assert(foo, "ExecuteProtected", 10));
162		}
163
164		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
165		public void ShouldAssertOccrenceForNonPublicFunction()
166		{
167			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
168			Mock.NonPublic.Assert<int>(foo, "IntValue", Occurs.Never());
169		}
170
171		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
172		public void ShouldAssertOccurenceForNonPublicAction()
173		{
174			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
175
176			Mock.NonPublic.Arrange(foo, "ExecuteProtected", 10);
177
178			foo.Execute(10);
179
180			Mock.NonPublic.Assert(foo, "ExecuteProtected", Occurs.Exactly(1), 10);
181		}
182
183		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
184		public void ShouldThrowMissingMethodExceptionForMethodSpecification()
185		{
186			var foo = Mock.Create<Foo>(Behavior.CallOriginal);
187			Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "ExecuteProtected"));
188		}
189
190#if !SILVERLIGHT
191
192		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
193		public void ShouldCreateMockFromClassHavingAbstractInternalMethodInBase()
194		{
195			var foo = Mock.Create<FooAbstract2>();
196			foo.TryCreateToken(string.Empty);
197		}
198
199		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
200		public void ShouldMockTypeWithInternalCtorWhenInternalVisibleToIsApplied()
201		{
202			// Provided that InternalsVisibleTo attribute is included in assemblyinfo.cs.
203			var foo = Mock.Create<FooInternal>(Behavior.CallOriginal);
204			Assert.NotNull(foo.Builder);
205		}
206
207		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
208		public void ShouldAssertNonPublicMethodFromBase()
209		{
210			var baz = Mock.Create<Baz>(Behavior.CallOriginal);
211
212			const string targetMethod = "MethodToMock";
213
214			Mock.NonPublic.Arrange(baz, targetMethod).DoNothing();
215
216			baz.MethodToTest();
217
218			Mock.NonPublic.Assert(baz, targetMethod);
219		}
220
221#if !PORTABLE
222		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
223		public void ShouldAssertNonPublicCallWhenOccurrenceIsApplied()
224		{
225			var baz = Mock.Create<Bar>(Behavior.CallOriginal);
226
227			const string targetMethod = "MethodToMock";
228
229			Mock.NonPublic.Arrange(baz, targetMethod).OccursOnce();
230
231			baz.GetType().GetMethod(targetMethod, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(baz, null);
232
233			Mock.NonPublic.Assert(baz, targetMethod);
234		}
235
236		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic"), TestCategory("Assertion")]
237		public void ShouldGetTimesCalledOfNonPublicMethod()
238		{
239			var mock = Mock.Create<Bar>();
240			Mock.NonPublic.MakePrivateAccessor(mock).CallMethod("MethodToMock");
241
242			Assert.Equal(1, Mock.NonPublic.GetTimesCalled(mock, "MethodToMock"));
243			Assert.Equal(1, Mock.NonPublic.GetTimesCalled(mock, typeof(Bar).GetMethod("MethodToMock", BindingFlags.NonPublic | BindingFlags.Instance)));
244		}
245#endif
246
247		public class Bar
248		{
249			protected virtual void MethodToMock()
250			{
251				throw new ArgumentException("Base method Invoked");
252			}
253		}
254
255		public class Baz : Bar
256		{
257			public virtual void MethodToTest()
258			{
259				MethodToMock();
260			}
261		}
262
263		internal class FooInternal
264		{
265			internal FooInternal()
266			{
267				builder = new StringBuilder();
268			}
269
270			public StringBuilder Builder
271			{
272				get
273				{
274					return builder;
275				}
276			}
277
278			private StringBuilder builder;
279		}
280
281#endif
282
283		internal abstract class FooAbstract
284		{
285			protected internal abstract bool TryCreateToken(string literal);
286		}
287
288		internal abstract class FooAbstract2 : FooAbstract
289		{
290
291		}
292
293		public class Foo
294		{
295			protected virtual void ExecuteProtected(Foo foo, int arg1)
296			{
297				throw new NotImplementedException();
298			}
299
300			protected virtual void ExecuteProtected(int arg1, Foo foo)
301			{
302				throw new NotImplementedException();
303			}
304
305			protected virtual void ExecuteProtected(int arg1)
306			{
307				throw new NotImplementedException();
308			}
309
310			public virtual void Execute(int arg1)
311			{
312				ExecuteProtected(arg1);
313			}
314
315			public virtual void Execute(int arg1, Foo foo)
316			{
317				ExecuteProtected(arg1, foo);
318			}
319
320			public virtual void Execute(Foo foo, int arg1)
321			{
322				ExecuteProtected(foo, arg1);
323			}
324
325			protected virtual void Load()
326			{
327				throw new NotImplementedException();
328			}
329
330			protected virtual int IntValue
331			{
332				get
333				{
334					throw new NotImplementedException();
335				}
336			}
337
338			public virtual void Init()
339			{
340				Load();
341			}
342
343			public virtual int GetMultipleOfIntValue()
344			{
345				return IntValue * 2;
346			}
347		}
348
349		public class FooDerived : Foo
350		{
351
352		}
353
354		public class RefTest
355		{
356			protected virtual void Test(string arg1, ref string asd)
357			{
358
359			}
360
361			public void ExecuteTest(ref string asd)
362			{
363				this.Test("test1", ref asd);
364			}
365		}
366
367		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
368		public void ShouldArrangeNonPublicUsingByRefArgumentWithMatcher()
369		{
370			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);
371			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Ref(Arg.Expr.IsAny<string>())).MustBeCalled();
372			string asd = "asd";
373			foo.ExecuteTest(ref asd);
374			Mock.Assert(foo);
375		}
376
377		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
378		public void ShouldArrangeNonPublicUsingByRefArgumentWithConstant()
379		{
380			int call = 1;
381			int callA = 0, callB = 0;
382
383			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);
384			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Ref(Arg.Expr.IsAny<string>())).DoInstead(() => callB = call++);
385			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Ref("asd")).DoInstead(() => callA = call++);
386
387			string input = "asd";
388			foo.ExecuteTest(ref input);
389			input = "foo";
390			foo.ExecuteTest(ref input);
391
392			Assert.Equal(1, callA);
393			Assert.Equal(2, callB);
394		}
395
396		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
397		public void ShouldArrangeNonPublicUsingByRefArgumentAsOutputParameter()
398		{
399			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);
400			Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), Arg.Expr.Out("asd"));
401
402			string input = "";
403			foo.ExecuteTest(ref input);
404			Assert.Equal("asd", input);
405		}
406
407		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
408		public void ShouldNotArrangeNonPublicUsingConstantArgumentWhereByRefIsExpected()
409		{
410			var foo = Mock.Create<RefTest>(Behavior.CallOriginal);
411			Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "Test", Arg.Expr.IsAny<string>(), "asd"));
412		}
413
414		public abstract class WeirdSignature
415		{
416			protected abstract int Do(int a, string b, ref object c, IEnumerable<int> d);
417			protected abstract void Do(bool b);
418			protected abstract DateTime Do(DateTime dateTime);
419			protected static void Do(int d) { }
420			protected static int Do(char e) { return 0; }
421		}
422
423		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
424		public void ShouldProvideHelpfulExceptionMessageWhenNonPublicMethodIsMissing()
425		{
426			var foo = Mock.Create<WeirdSignature>();
427			var exception = Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "Do"));
428			var message = exception.Message;
429			Assert.Equal(("Method 'Do' with the given signature was not found on type Telerik.JustMock.Tests.NonPublicFixture+WeirdSignature\r\n" +
430"Review the available methods in the message below and optionally paste the appropriate arrangement snippet.\r\n" +
431"----------\r\n" +
432"Method 1: Int32 Do(Int32, System.String, System.Object ByRef, System.Collections.Generic.IEnumerable`1[System.Int32])\r\n" +
433"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" +
434"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" +
435"----------\r\n" +
436"Method 2: Void Do(Boolean)\r\n" +
437"C#: Mock.NonPublic.Arrange(mock, \"Do\", Arg.Expr.IsAny<bool>());\r\n" +
438"VB: Mock.NonPublic.Arrange(mock, \"Do\", Arg.Expr.IsAny(Of Boolean)())\r\n" +
439"----------\r\n" +
440"Method 3: System.DateTime Do(System.DateTime)\r\n" +
441"C#: Mock.NonPublic.Arrange<DateTime>(mock, \"Do\", Arg.Expr.IsAny<DateTime>());\r\n" +
442"VB: Mock.NonPublic.Arrange(Of Date)(mock, \"Do\", Arg.Expr.IsAny(Of Date)())\r\n" +
443"----------\r\n" +
444"Method 4: Void Do(Int32)\r\n" +
445"C#: Mock.NonPublic.Arrange(\"Do\", Arg.Expr.IsAny<int>());\r\n" +
446"VB: Mock.NonPublic.Arrange(\"Do\", Arg.Expr.IsAny(Of Integer)())\r\n" +
447"----------\r\n" +
448"Method 5: Int32 Do(Char)\r\n" +
449"C#: Mock.NonPublic.Arrange<int>(\"Do\", Arg.Expr.IsAny<char>());\r\n" +
450"VB: Mock.NonPublic.Arrange(Of Integer)(\"Do\", Arg.Expr.IsAny(Of Char)())\r\n").Replace("\r\n", Environment.NewLine), message);
451
452			var exception2 = Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange(foo, "Dont"));
453			var message2 = exception2.Message;
454			Assert.Equal(("Method 'Dont' with the given signature was not found on type Telerik.JustMock.Tests.NonPublicFixture+WeirdSignature\r\n" +
455				"No methods or properties found with the given name.\r\n").Replace("\r\n", Environment.NewLine), message2);
456		}
457
458		public abstract class NonPublicOverloads
459		{
460			protected abstract int NotOverloaded(int a, out object b);
461
462			protected abstract int Overloaded(int a);
463			protected abstract int Overloaded(string a);
464
465			protected abstract int Prop { set; }
466
467			public int CallNotOverloaded(int a, out object b)
468			{
469				return NotOverloaded(a, out b);
470			}
471
472			public int SetProp
473			{
474				set { Prop = value; }
475			}
476		}
477
478		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
479		public void ShouldQuickArrangeNonPublicNonOverloadedMethod()
480		{
481			var mock = Mock.Create<NonPublicOverloads>(Behavior.CallOriginal);
482
483			Mock.NonPublic.Arrange<int>(mock, "NotOverloaded").Returns(5);
484
485			object b;
486			var result = mock.CallNotOverloaded(5, out b);
487
488			Assert.Equal(5, result);
489		}
490
491		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
492		public void ShouldQuickArrangeNonPublicSetter()
493		{
494			var mock = Mock.Create<NonPublicOverloads>(Behavior.CallOriginal);
495			bool called = false;
496			Mock.NonPublic.Arrange(mock, "Prop").DoInstead(() => called = true);
497
498			mock.SetProp = 5;
499
500			Assert.True(called);
501		}
502
503		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
504		public void ShouldFailToQuickArrangeNonPublicOverloadedMethods()
505		{
506			var mock = Mock.Create<NonPublicOverloads>();
507			Assert.Throws<MissingMemberException>(() => Mock.NonPublic.Arrange<int>(mock, "Overloaded"));
508		}
509
510		public abstract class GenericTest
511		{
512			protected abstract T Do<T>(T x);
513
514			protected abstract IEnumerable<T> Enumerate<T>();
515
516			public int TestDo()
517			{
518				return Do(10);
519			}
520
521			public IEnumerable<int> TestEnumerate()
522			{
523				return Enumerate<int>();
524			}
525		}
526
527		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
528		public void ShouldArrangeNonPublicMethodReturningGenericValue()
529		{
530			var mock = Mock.Create<GenericTest>(Behavior.CallOriginal);
531			Mock.NonPublic.Arrange<int>(mock, "Do", Arg.Expr.IsAny<int>()).Returns(123);
532			Assert.Equal(123, mock.TestDo());
533		}
534
535		[TestMethod, TestCategory("Lite"), TestCategory("NonPublic")]
536		public void ShouldArrangeNonPublicMethodReturningGenericValueComplexType()
537		{
538			var mock = Mock.Create<GenericTest>(Behavior.CallOriginal);
539			Mock.NonPublic.Arrange<IEnumerable<int>>(mock, "Enumerate").Returns(new[] { 123 });
540			var actual = mock.TestEnumerate().ToArray();
541			Assert.Equal(1, actual.Length);
542			Assert.Equal(123, actual[0]);
543		}
544	}
545}
546
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)