How to use AfterAllBehavior class of Telerik.JustMock.Core.Behaviors package

Best JustMockLite code snippet using Telerik.JustMock.Core.Behaviors.AfterAllBehavior

Run JustMockLite automation tests on LambdaTest cloud grid

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

AfterAllBehavior.cs

Source: AfterAllBehavior.cs Github

copy
1/*
2 JustMock Lite
3 Copyright © 2019 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 Telerik.JustMock.Core.Context;
20using Telerik.JustMock.Expectations.Abstraction;
21
22namespace Telerik.JustMock.Core.Behaviors
23{
24    internal class AfterAllBehavior : IAssertableBehavior
25    {
26        private readonly IPrerequisite[] prerequisites;
27        private string processedStackTrace;
28
29        public string DebugView
30        {
31            get { return String.Format("{0}: after all prerequisite expectations.", this.IsMet ? "Met" : "Unmet"); }
32        }
33
34        public AfterAllBehavior(IPrerequisite[] prerequisites)
35        {
36            this.prerequisites = prerequisites;
37        }
38
39        private string ExecutionMessage
40        {
41            get
42            {
43                var message = this.processedStackTrace;
44                return !String.IsNullOrEmpty(message) ? message : "--no calls--\n";
45            }
46        }
47
48        private bool IsMet
49        {
50            get
51            {
52                foreach (var prerequisite in this.prerequisites)
53                {
54                    if (!prerequisite.IsMet)
55                    {
56                        return false;
57                    }
58                }
59                return true;
60            }
61        }
62
63        public void Process(Invocation invocation)
64        {
65            this.processedStackTrace = invocation.InputToString() + " called at:\n" + MockingContext.GetStackTrace("    ");
66        }
67
68        public void Assert()
69        {
70            if (!this.IsMet)
71            {
72                MockingContext.Fail("Not all prerequisites are met. Actual call processed:\n{0}", this.ExecutionMessage);
73            }
74        }
75    }
76}
77
Full Screen

CommonExpectation.cs

Source: CommonExpectation.cs Github

copy
1/*
2 JustMock Lite
3 Copyright © 2010-2015,2019,2021 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.Linq.Expressions;
22using System.Threading;
23using Telerik.JustMock.Core;
24using Telerik.JustMock.Core.Behaviors;
25using Telerik.JustMock.Core.MatcherTree;
26using Telerik.JustMock.Expectations.Abstraction;
27
28namespace Telerik.JustMock.Expectations
29{
30	/// <summary>
31	/// Implements common expectations.
32	/// </summary>
33	public partial class CommonExpectation<TContainer> : IAction<TContainer>, IInstanceScope<TContainer>, IMethodMock
34	{
35		private readonly List<IBehavior> behaviors = new List<IBehavior>();
36		private readonly InvocationOccurrenceBehavior occurences;
37		private ImplementationOverrideBehavior acceptCondition;
38
39		MocksRepository IMethodMock.Repository { get; set; }
40
41		IMockMixin IMethodMock.Mock { get; set; }
42
43		bool IMethodMock.IsSequential { get; set; }
44        bool IMethodMock.IsInOrder { get; set; }
45        bool IMethodMock.IsUsed { get; set; }
46		CallPattern IMethodMock.CallPattern { get; set; }
47		ICollection<IBehavior> IMethodMock.Behaviors { get { return this.behaviors; } }
48		InvocationOccurrenceBehavior IMethodMock.OccurencesBehavior { get { return this.occurences; } }
49		string IMethodMock.ArrangementExpression { get; set; }
50
51		ImplementationOverrideBehavior IMethodMock.AcceptCondition
52		{
53			get { return this.acceptCondition; }
54			set
55			{
56				if (value == null)
57					throw new ArgumentNullException("value");
58				if (this.acceptCondition != null)
59					throw new MockException("Condition already specified.");
60				this.acceptCondition = value;
61			}
62		}
63
64		private MocksRepository Repository
65		{
66			get { return ((IMethodMock)this).Repository; }
67		}
68
69		private CallPattern CallPattern
70		{
71			get { return ((IMethodMock)this).CallPattern; }
72		}
73
74		internal IMockMixin Mock
75		{
76			get { return ((IMethodMock)this).Mock; }
77		}
78
79		internal CommonExpectation()
80		{
81			this.occurences = new InvocationOccurrenceBehavior(this);
82			this.behaviors.Add(this.occurences);
83		}
84
85		#region Implementation from ICommon<TContainer>
86
87		/// <summary>
88		/// Implementation detail.
89		/// </summary>
90		/// <param name="delg"></param>
91		/// <param name="ignoreDelegateReturnValue"></param>
92		protected void ProcessDoInstead(Delegate delg, bool ignoreDelegateReturnValue)
93		{
94			if (delg == null)
95			{
96				var returnType = CallPattern.Method.GetReturnType();
97				if (returnType == typeof(void))
98					returnType = typeof(object);
99				if (returnType.IsValueType && Nullable.GetUnderlyingType(returnType) == null)
100					throw new MockException(String.Format("Cannot return null value for non-nullable return type '{0}'.", returnType));
101
102				delg = Expression.Lambda(typeof(Func<>).MakeGenericType(returnType),
103					Expression.Constant(null, returnType)).Compile();
104			}
105
106			this.behaviors.Add(new ImplementationOverrideBehavior(delg, ignoreDelegateReturnValue));
107		}
108
109		/// <summary>
110		/// Defines the body of the expected method that will be executed instead of the orginal method body.
111		/// </summary>
112		/// <param name="action">delegate the method body</param>
113		/// <returns></returns>
114		public TContainer DoInstead(Action action)
115		{
116			return ProfilerInterceptor.GuardInternal(() =>
117				{
118					ProcessDoInstead(action, true);
119					return (TContainer)(object)this;
120				});
121		}
122
123		/// <summary>
124		/// Specifies the delegate that will execute for the expected method.
125		/// </summary>
126		/// <param name="delegate">Target delegate to evaluate.</param>
127		public TContainer DoInstead(Delegate @delegate)
128		{
129			return ProfilerInterceptor.GuardInternal(() =>
130				{
131					ProcessDoInstead(@delegate, true);
132					return (TContainer)(object)this;
133				});
134		}
135
136		private void ProcessRaises(Action eventExpression, Func<object, Delegate> eventArgumentsFactoryFactory)
137		{
138			object instance = null;
139			var evt = Repository.ParseAddHandlerAction(eventExpression, out instance);
140			this.behaviors.Add(new RaiseEventBehavior(instance, evt, eventArgumentsFactoryFactory(instance)));
141		}
142
143		///<summary>
144		/// Raises the expected with sepecic arguments
145		///</summary>
146		public TContainer Raises(Action eventExpression, params object[] args)
147		{
148			return ProfilerInterceptor.GuardInternal(() =>
149				{
150#if !PORTABLE
151					IWaitDuration wait = args.OfType<IWaitDuration>().FirstOrDefault();
152					if (wait != null)
153					{
154						args = args.Where(obj => obj != wait).ToArray();
155					}
156#endif
157
158					this.ProcessRaises(eventExpression, instance => new Func<object[]>(() =>
159						{
160#if !PORTABLE
161							if (wait != null)
162								Thread.Sleep(wait.Miliseconds);
163#endif
164							return args;
165						}));
166					return (TContainer)(object)this;
167				});
168		}
169
170		///<summary>
171		/// Raises the expected event with provided <see cref="EventArgs"/>.
172		///</summary>
173		///<param name="eventExpression"></param>
174		///<param name="args">Event arguments</param>
175		///<returns></returns>
176		///<exception cref="InvalidOperationException"></exception>
177		public TContainer Raises(Action eventExpression, EventArgs args)
178		{
179			return ProfilerInterceptor.GuardInternal(() =>
180				{
181					this.ProcessRaises(eventExpression, instance => new Func<object[]>(() => new object[] { instance, args }));
182					return (TContainer)(object)this;
183				});
184		}
185
186		///<summary>
187		/// Raises the expected event for the setup.
188		///</summary>
189		///<param name="eventExpression"></param>
190		///<param name="func">Function that will be used to construct event arguments</param>
191		///<returns></returns>
192		///<exception cref="InvalidOperationException"></exception>
193		public TContainer Raises<T1>(Action eventExpression, Func<T1, EventArgs> func)
194		{
195			return ProfilerInterceptor.GuardInternal(() =>
196				{
197					this.ProcessRaises(eventExpression, instance => new Func<T1, object[]>(t1 => new object[] { instance, func(t1) }));
198					return (TContainer)(object)this;
199				});
200		}
201
202		///<summary>
203		/// Raises the expected event for the setup.
204		///</summary>
205		///<param name="eventExpression"></param>
206		///<param name="func">An function that will be used to construct event arguments</param>
207		///<returns></returns>
208		///<exception cref="InvalidOperationException"></exception>
209		public TContainer Raises<T1, T2>(Action eventExpression, Func<T1, T2, EventArgs> func)
210		{
211			return ProfilerInterceptor.GuardInternal(() =>
212				{
213					this.ProcessRaises(eventExpression, instance => new Func<T1, T2, object[]>((t1, t2) => new object[] { instance, func(t1, t2) }));
214					return (TContainer)(object)this;
215				});
216		}
217
218		///<summary>
219		/// Raises the expected event for the setup.
220		///</summary>
221		///<param name="eventExpression"></param>
222		///<param name="func">An function that will be used to construct event arguments</param>
223		///<returns></returns>
224		///<exception cref="InvalidOperationException"></exception>
225		public TContainer Raises<T1, T2, T3>(Action eventExpression, Func<T1, T2, T3, EventArgs> func)
226		{
227			return ProfilerInterceptor.GuardInternal(() =>
228				{
229					this.ProcessRaises(eventExpression, instance => new Func<T1, T2, T3, object[]>((t1, t2, t3) => new object[] { instance, func(t1, t2, t3) }));
230					return (TContainer)(object)this;
231				});
232		}
233
234		///<summary>
235		/// Raises the expected event for the setup.
236		///</summary>
237		///<param name="eventExpression"></param>
238		///<param name="func">An function that will be used to construct event arguments</param>
239		///<returns></returns>
240		///<exception cref="InvalidOperationException"></exception>
241		public TContainer Raises<T1, T2, T3, T4>(Action eventExpression, Func<T1, T2, T3, T4, EventArgs> func)
242		{
243			return ProfilerInterceptor.GuardInternal(() =>
244				{
245					this.ProcessRaises(eventExpression, instance => new Func<T1, T2, T3, T4, object[]>((t1, t2, t3, t4) => new object[] { instance, func(t1, t2, t3, t4) }));
246					return (TContainer)(object)this;
247				});
248		}
249
250		/// <summary>
251		/// Throws a the specified expection for target call.
252		/// </summary>
253		/// <param name="exception"></param>
254		/// <returns></returns>
255		public IAssertable Throws(Exception exception)
256		{
257			return ProfilerInterceptor.GuardInternal(() =>
258				{
259					this.behaviors.Add(new ThrowExceptionBehavior(exception));
260					return this;
261				});
262		}
263
264		/// <summary>
265		/// Throws a the specified expection for target call.
266		/// </summary>
267		/// <returns></returns>
268		public IAssertable Throws<T>() where T : Exception
269		{
270			return ProfilerInterceptor.GuardInternal(() =>
271				{
272					this.behaviors.Add(new ThrowExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T))));
273					return this;
274				});
275		}
276
277		/// <summary>
278		/// Throws a the specified expection for target call.
279		/// </summary>
280		/// <returns></returns>
281		public IAssertable Throws<T>(params object[] args) where T : Exception
282		{
283			return ProfilerInterceptor.GuardInternal(() =>
284				{
285					this.behaviors.Add(new ThrowExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T), args)));
286					return this;
287				});
288		}
289
290#if !LITE_EDITION
291		/// <summary>
292		/// Throws a the specified exception for the target async call causing returned task to fail.
293		/// </summary>
294		/// <param name="exception"></param>
295		/// <returns></returns>
296		public IAssertable ThrowsAsync(Exception exception)
297		{
298			return ProfilerInterceptor.GuardInternal(() =>
299			{
300				this.behaviors.Add(new ThrowAsyncExceptionBehavior(exception));
301				return this;
302			});
303		}
304
305		/// <summary>
306		/// Throws a the specified exception for the target async call causing returned task to fail.
307		/// </summary>
308		/// <returns></returns>
309		public IAssertable ThrowsAsync<T>() where T : Exception
310		{
311			return ProfilerInterceptor.GuardInternal(() =>
312			{
313				this.behaviors.Add(new ThrowAsyncExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T))));
314				return this;
315			});
316		}
317
318		/// <summary>
319		/// Throws a the specified exception for the target async call causing returned task to fail.
320		/// </summary>
321		/// <returns></returns>
322		public IAssertable ThrowsAsync<T>(params object[] args) where T : Exception
323		{
324			return ProfilerInterceptor.GuardInternal(() =>
325			{
326				this.behaviors.Add(new ThrowAsyncExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T), args)));
327				return this;
328			});
329		}
330#endif
331
332		/// <summary>
333		/// Use it to call the real implementation.
334		/// </summary>
335		/// <returns></returns>
336		public IAssertable CallOriginal()
337		{
338			return ProfilerInterceptor.GuardInternal(() =>
339				{
340					this.behaviors.Add(new CallOriginalBehavior());
341					return this;
342				});
343		}
344
345		/// <summary>
346		///  Specfies call a to step over.
347		/// </summary>
348		/// <remarks>
349		/// For loose mocks by default the behavior is step over.
350		/// </remarks>
351		/// <returns>Refarence to <see cref="IAssertable"/></returns>
352		public IAssertable DoNothing()
353		{
354			return ProfilerInterceptor.GuardInternal(() =>
355				{
356					ProcessDoInstead(new Action(() => { }), true);
357					return this;
358				});
359		}
360
361		#endregion
362
363		#region Implementation of IAssertable
364
365		/// <summary>
366		/// Specifies that the arranged member must be called. Asserting the mock will throw if the expectation is not fulfilled.
367		/// </summary>
368		public IDisposable MustBeCalled(string message = null)
369		{
370			return ProfilerInterceptor.GuardInternal(() => SetOccurrenceBounds(1, null, message));
371		}
372
373		#endregion
374
375		#region Occurrence
376
377		/// <summary>
378		/// Specifies how many times the call should occur.
379		/// </summary>
380		/// <param name="numberOfTimes">Specified number of times</param>
381		public IDisposable Occurs(int numberOfTimes, string message = null)
382		{
383			return ProfilerInterceptor.GuardInternal(() => SetOccurrenceBounds(numberOfTimes, numberOfTimes, message));
384		}
385
386		/// <summary>
387		/// Specifies how many times atleast the call should occur.
388		/// </summary>
389		/// <param name="numberOfTimes">Specified number of times</param>
390		public IDisposable OccursAtLeast(int numberOfTimes, string message = null)
391		{
392			return ProfilerInterceptor.GuardInternal(() => SetOccurrenceBounds(numberOfTimes, null, message));
393		}
394
395		/// <summary>
396		/// Specifies how many times maximum the call can occur.
397		/// </summary>
398		/// <param name="numberOfTimes">Specified number of times</param>
399		public IDisposable OccursAtMost(int numberOfTimes, string message = null)
400		{
401			return ProfilerInterceptor.GuardInternal(() => SetOccurrenceBounds(null, numberOfTimes, message));
402		}
403
404		/// <summary>
405		/// Specifies that the call must occur once.
406		/// </summary>
407		public IDisposable OccursOnce(string message = null)
408		{
409			return ProfilerInterceptor.GuardInternal(() => SetOccurrenceBounds(1, 1, message));
410		}
411
412		/// <summary>
413		/// Specifies that the call must never occur.
414		/// </summary>
415		public IDisposable OccursNever(string message = null)
416		{
417			return ProfilerInterceptor.GuardInternal(() => SetOccurrenceBounds(0, 0, message));
418		}
419
420		#endregion
421
422		/// <summary>
423		/// Specifies that JustMock should invoke different mock instance for each setup.
424		/// </summary>
425		/// <remarks>
426		/// When this modifier is applied
427		/// for similar type call, the flow of setups will be maintained.
428		/// </remarks>
429		public IAssertable InSequence()
430		{
431			return ProfilerInterceptor.GuardInternal(() =>
432				{
433					(this as IMethodMock).IsSequential = true;
434					return this;
435				});
436		}
437
438		/// <summary>
439		/// Specifies a call should occur in a specific order.
440		/// </summary>
441		public IOccurrence InOrder(string message = null)
442		{
443			return ProfilerInterceptor.GuardInternal(() =>
444				{
445                    (this as IMethodMock).IsInOrder = true;
446                    this.behaviors.Add(new InOrderBehavior(this.Repository, this.Mock, message));
447					return this;
448				});
449		}
450
451		/// <summary>
452		/// Determines whether prerequisite is met
453		/// </summary>
454		public bool IsMet
455		{
456			get
457			{
458				return ProfilerInterceptor.GuardInternal(() => ((IMethodMock)this).IsUsed);
459			}
460		}
461
462		/// <summary>
463		/// Specifies that a call should occur only after all of the given prerequisites have been met.
464		/// </summary>
465		public IAssertable AfterAll(params IPrerequisite[] prerequisites)
466		{
467			return ProfilerInterceptor.GuardInternal(() =>
468			{
469				this.behaviors.Add(new AfterAllBehavior(prerequisites));
470				return this;
471			});
472		}
473
474		/// <summary>
475		/// Defines that the expectation should occur for all instance.
476		/// </summary>
477		public TContainer IgnoreInstance()
478		{
479			return ProfilerInterceptor.GuardInternal(() =>
480				{
481					this.CallPattern.InstanceMatcher = new AnyMatcher();
482					this.CallPattern.MethodMockNode.ReattachMethodMock();
483					return (TContainer)(object)this;
484				});
485		}
486
487		/// <summary>
488		/// Specifies that the arrangement will be respected regardless of the thread
489		/// on which the call to the arranged member happens.
490		/// </summary>
491		/// <remarks>
492		/// This is only needed for arrangements of static members. Arrangements on
493		/// instance members are always respected, regardless of the current thread.
494		/// 
495		/// Cross-thread arrangements are active as long as the current context
496		/// (test method) is on the call stack. Be careful when arranging
497		/// static members cross-thread because the effects of the arrangement may
498		/// affect and even crash the testing framework.
499		/// </remarks>
500		public IAssertable OnAllThreads()
501		{
502			return ProfilerInterceptor.GuardInternal(() =>
503				{
504					this.Repository.InterceptGlobally(this.CallPattern.Method);
505					return this;
506				});
507		}
508
509		/// <summary>
510		/// Specifies an additional condition that must be true for this arrangement to be
511		/// considered when the arranged member is called. This condition is evaluated in addition
512		/// to the conditions imposed by any argument matchers in the arrangement.
513		/// 
514		/// This method allows a more general way of matching arrangements than argument matchers do.
515		/// </summary>
516		/// <param name="condition">A function that should return 'true' when this
517		/// arrangement should be considered and 'false' if this arrangement doesn't match the user criteria.</param>
518		public TContainer When(Func<bool> condition)
519		{
520			return ProfilerInterceptor.GuardInternal(() =>
521			{
522				this.SetAcceptCondition(condition);
523				return (TContainer)(object)this;
524			});
525		}
526
527		private void SetAcceptCondition(Delegate condition)
528		{
529			((IMethodMock)this).AcceptCondition = new ImplementationOverrideBehavior(condition, false);
530		}
531
532		/// <summary>
533		/// Specifies to ignore any argument for the target call.
534		/// </summary>
535		/// <returns>Func or Action Container</returns>
536		public TContainer IgnoreArguments()
537		{
538			return ProfilerInterceptor.GuardInternal(() =>
539			{
540				var callPattern = this.CallPattern;
541				for (int i = 0; i < callPattern.ArgumentMatchers.Count; i++)
542				{
543					callPattern.ArgumentMatchers[i] = new AnyMatcher();
544				}
545
546#if !PORTABLE
547				this.Repository.UpdateMockDebugView(callPattern.Method, callPattern.ArgumentMatchers.ToArray());
548#endif
549
550				callPattern.MethodMockNode.ReattachMethodMock();
551
552				return (TContainer)(object)this;
553			});
554		}
555
556		/// <summary>
557		/// Removes this arrangement. Its side effects will no longer be executed and its expectations will not be asserted.
558		/// </summary>
559		public void Dispose()
560		{
561			ProfilerInterceptor.GuardInternal(() => CallPattern.MethodMockNode.DetachMethodMock());
562		}
563
564		private IDisposable SetOccurrenceBounds(int? lowerBound, int? upperBound, string message)
565		{
566			this.occurences.SetBounds(lowerBound, upperBound, message);
567			return this;
568		}
569	}
570}
571
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

Most used methods in AfterAllBehavior

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)