How to use MSTestMockingContextResolver class of Telerik.JustMock.Core.Context package

Best JustMockLite code snippet using Telerik.JustMock.Core.Context.MSTestMockingContextResolver

Run JustMockLite automation tests on LambdaTest cloud grid

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

MSTestMockingContextResolver.cs

Source: MSTestMockingContextResolver.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.Linq;
20using System.Threading;
21
22namespace Telerik.JustMock.Core.Context
23{
24	internal class MSTestMockingContextResolver : HierarchicalTestFrameworkContextResolver
25	{
26#if SILVERLIGHT
27		private const string MstestAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight";
28#else
29		private const string MstestAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework";
30#endif
31
32		private const string MstestAssertionFailedName = "Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException, " + MstestAssemblyName;
33
34		public MSTestMockingContextResolver()
35			: base(MstestAssertionFailedName)
36		{
37			this.SetupStandardHierarchicalTestStructure(
38				new[] { "Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute, " + MstestAssemblyName },
39				new[] { "Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute, " + MstestAssemblyName, "Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute, " + MstestAssemblyName },
40				new[] { "Microsoft.VisualStudio.TestTools.UnitTesting.ClassInitializeAttribute, " + MstestAssemblyName, "Microsoft.VisualStudio.TestTools.UnitTesting.ClassCleanupAttribute, " + MstestAssemblyName },
41				new[] { "Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyInitializeAttribute, " + MstestAssemblyName, "Microsoft.VisualStudio.TestTools.UnitTesting.AssemblyCleanupAttribute, " + MstestAssemblyName },
42				FixtureConstuctorSemantics.InstanceConstructorCalledOncePerFixture);
43		}
44
45		public static bool IsAvailable
46		{
47			get { return FindType(MstestAssertionFailedName, false) != null; }
48		}
49
50#if !SILVERLIGHT
51		private const int DefaultGcFrequency = 50;
52		private int createdRepoCount;
53		private int lastGcCount;
54		private int gcFrequency = GetGcFrequency();
55		private bool synchronousGc = GetSynchronousGc();
56
57		private static int GetGcFrequency()
58		{
59			var valueStr = SecuredRegistryMethods.GetValue(false, @"Software\Telerik\JustMock", "MSTestGcFrequency");
60			int value;
61			if (!String.IsNullOrEmpty(valueStr) && int.TryParse(valueStr, out value) && value >= 1)
62				return value;
63
64			return DefaultGcFrequency;
65		}
66
67		private static bool GetSynchronousGc()
68		{
69			var valueStr = SecuredRegistryMethods.GetValue(false, @"Software\Telerik\JustMock", "SynchronousGc");
70			int value;
71			return !String.IsNullOrEmpty(valueStr) && int.TryParse(valueStr, out value) && value == 1;
72		}
73
74		protected override void OnMocksRepositoryCreated(MocksRepository repo)
75		{
76			// MSTest runs every test in a different thread. We'd like to collect Thread objects often so that their handle is released.
77			// At every N created repos (we assume that each test creates a single repo, so the number of repos created is close to
78			// the number of threads created) do a garbage collection, but only if it hasn't been already done in this interval.
79
80			createdRepoCount++;
81
82			if (createdRepoCount % gcFrequency == 0)
83			{
84				var gen2Collections = GC.CollectionCount(GC.MaxGeneration);
85				if (gen2Collections == lastGcCount)
86				{
87					if (synchronousGc)
88					{
89						GC.Collect();
90					}
91					else
92					{
93						ThreadPool.QueueUserWorkItem(_ => GC.Collect());
94					}
95
96					gen2Collections++;
97				}
98				lastGcCount = gen2Collections;
99			}
100		}
101#endif
102	}
103}
104
Full Screen

MockingContext.cs

Source: MockingContext.cs Github

copy
1/*
2 JustMock Lite
3 Copyright © 2010-2015,2020 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.Diagnostics;
21using System.IO;
22using System.Linq;
23using System.Reflection;
24using System.Text;
25using Telerik.JustMock.Diagnostics;
26#if !PORTABLE
27using Telerik.JustMock.Helpers;
28using Telerik.JustMock.Plugins;
29using Telerik.JustMock.AutoMock.Ninject.Parameters;
30#if NETCORE
31using System.Text.RegularExpressions;
32using System.Runtime.InteropServices;
33#endif
34#endif
35
36namespace Telerik.JustMock.Core.Context
37{
38	internal enum UnresolvedContextBehavior
39	{
40		DoNotCreateNew,
41		CreateNewContextual,
42		CreateNewContextualOrLocal,
43	}
44
45	internal static class MockingContext
46	{
47		internal const string DebugViewPluginAssemblyFileName = "Telerik.JustMock.DebugWindow.Plugin.dll";
48
49		public static MocksRepository CurrentRepository
50		{
51			get { return ResolveRepository(UnresolvedContextBehavior.CreateNewContextualOrLocal); }
52		}
53
54		public static MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
55		{
56			if (unresolvedContextBehavior != UnresolvedContextBehavior.DoNotCreateNew)
57			{
58				DebugView.TraceEvent(IndentLevel.StackTrace, () => String.Format("Resolving repository with unresolved context behavior {0}", unresolvedContextBehavior));
59			}
60
61			foreach (var resolver in registeredContextResolvers)
62			{
63				var repo = resolver.ResolveRepository(unresolvedContextBehavior);
64				if (repo != null)
65				{
66					lastFrameworkAwareRepository = repo;
67					return repo;
68				}
69			}
70
71			if (lastFrameworkAwareRepository != null && !ProfilerInterceptor.IsProfilerAttached)
72				return lastFrameworkAwareRepository;
73
74			return LocalMockingContextResolver.ResolveRepository(unresolvedContextBehavior);
75		}
76
77		public static void RetireRepository()
78		{
79			foreach (var resolver in registeredContextResolvers)
80			{
81				if (resolver.RetireRepository())
82					return;
83			}
84
85			LocalMockingContextResolver.RetireRepository();
86
87#if !PORTABLE
88			DynamicTypeHelper.Reset();
89#endif
90		}
91
92		public static MethodBase GetTestMethod()
93		{
94			foreach (IMockingContextResolver resolver in registeredContextResolvers)
95			{
96				var testMethod = resolver.GetTestMethod();
97				if (testMethod != null)
98				{
99					return testMethod;
100				}
101			}
102
103			return null;
104		}
105
106		public static void Fail(string message, params object[] args)
107		{
108			var formattedMessage = String.Format(message, args);
109
110			if (failureAggregator == null)
111				Fail(formattedMessage);
112			else
113				failureAggregator.AddFailure(formattedMessage);
114		}
115
116		public static string GetStackTrace(string indent)
117		{
118#if SILVERLIGHT
119			var trace = new System.Diagnostics.StackTrace().ToString();
120#elif PORTABLE
121			var trace = new StackTrace().ToString();
122#else
123			var skipCount = new System.Diagnostics.StackTrace().GetFrames().TakeWhile(frame => frame.GetMethod().DeclaringType.Assembly == typeof(DebugView).Assembly).Count();
124			var trace = new System.Diagnostics.StackTrace(skipCount, true).ToString();
125#endif
126
127			return "\n".Join(trace
128					.Split('\n')
129					.Select(p => indent + p.Trim()));
130		}
131
132		public static IDisposable BeginFailureAggregation(string message)
133		{
134			if (failureAggregator == null)
135			{
136				failureAggregator = new FailureAggregator(message);
137			}
138			else
139			{
140				failureAggregator.AddRef(message);
141			}
142
143			return failureAggregator;
144		}
145
146		private static readonly List<IMockingContextResolver> registeredContextResolvers = new List<IMockingContextResolver>();
147
148		private static Action<string, Exception> failThrower;
149
150		[ThreadStatic]
151		private static FailureAggregator failureAggregator;
152
153		[ThreadStatic]
154		private static MocksRepository lastFrameworkAwareRepository;
155
156#if !PORTABLE
157		public static PluginsRegistry Plugins { get; private set; }
158		private static PluginLoadHelper pluginLoadHelper;
159#if NETCORE
160        private const string NET_CORE_DESC_PATTERN = @".NET(\sCore)?\s(\d+(\.)?)+";
161        private const string NET_CORE_SUBDIR = "netcoreapp2.1";
162#endif
163#endif
164
165        static MockingContext()
166		{
167#if !PORTABLE
168			MockingContext.Plugins = new PluginsRegistry();
169			AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
170
171			try
172			{
173#if !NETCORE
174				var clrVersion = Environment.Version;
175				if (clrVersion.Major >= 4 && clrVersion.Minor >= 0
176					&& clrVersion.Build >= 30319 && clrVersion.Revision >= 42000)
177#endif
178				{
179					var debugWindowEnabledEnv = Environment.GetEnvironmentVariable("JUSTMOCK_DEBUG_VIEW_ENABLED");
180					var debugWindowServicesStringEnv = Environment.GetEnvironmentVariable("JUSTMOCK_DEBUG_VIEW_SERVICES");
181					var debugWindowAssemblyDirectoryEnv = Environment.GetEnvironmentVariable("JUSTMOCK_DEBUG_VIEW_PLUGIN_DIRECTORY");
182					if (!string.IsNullOrEmpty(debugWindowEnabledEnv)
183						&& !string.IsNullOrEmpty(debugWindowServicesStringEnv)
184						&& !string.IsNullOrEmpty(debugWindowAssemblyDirectoryEnv)
185						&& debugWindowEnabledEnv == "1" && Directory.Exists(debugWindowAssemblyDirectoryEnv))
186					{
187#if NETCORE
188						if (Regex.IsMatch(RuntimeInformation.FrameworkDescription, NET_CORE_DESC_PATTERN))
189						{
190							// append .NET Core suffix if necessary
191							if (string.Compare(Path.GetDirectoryName(debugWindowAssemblyDirectoryEnv), NET_CORE_SUBDIR, StringComparison.InvariantCultureIgnoreCase) != 0)
192							{
193								debugWindowAssemblyDirectoryEnv = Path.Combine(debugWindowAssemblyDirectoryEnv, NET_CORE_SUBDIR);
194							}
195						}
196#endif
197						var debugWindowAssemblyPath = Path.Combine(debugWindowAssemblyDirectoryEnv, DebugViewPluginAssemblyFileName);
198						MockingContext.pluginLoadHelper = new PluginLoadHelper(debugWindowAssemblyDirectoryEnv);
199						MockingContext.Plugins.Register<IDebugWindowPlugin>(
200							debugWindowAssemblyPath, new ConstructorArgument("debugWindowServicesString", debugWindowServicesStringEnv));
201						DebugView.IsRemoteTraceEnabled = true;
202					}
203				}
204			}
205			catch (Exception e)
206			{
207				System.Diagnostics.Trace.WriteLine("Exception thrown during plugin registration: " + e);
208			}
209#endif
210
211#if PORTABLE
212			if (VisualStudioPortableContextResolver.IsAvailable)
213				registeredContextResolvers.Add(new VisualStudioPortableContextResolver());
214			if (XamarinAndroidNUnitContextResolver.IsAvailable)
215				registeredContextResolvers.Add(new XamarinAndroidNUnitContextResolver());
216			if (XamarinIosNUnitContextResolver.IsAvailable)
217				registeredContextResolvers.Add(new XamarinIosNUnitContextResolver());
218#else
219			if (XUnit1xMockingContextResolver.IsAvailable)
220				registeredContextResolvers.Add(new XUnit1xMockingContextResolver());
221			if (XUnit2xMockingContextResolver.IsAvailable)
222				registeredContextResolvers.Add(new XUnit2xMockingContextResolver());
223			if (NUnit2xMockingContextResolver.IsAvailable)
224				registeredContextResolvers.Add(new NUnit2xMockingContextResolver());
225			if (NUnit3xMockingContextResolver.IsAvailable)
226				registeredContextResolvers.Add(new NUnit3xMockingContextResolver());
227			if (NUnit3_8_xMockingContextResolver.IsAvailable)
228				registeredContextResolvers.Add(new NUnit3_8_xMockingContextResolver());
229			if (MSpecContextResolver.IsAvailable)
230				registeredContextResolvers.Add(new MSpecContextResolver());
231			if (MbUnitContextResolver.IsAvailable)
232				registeredContextResolvers.Add(new MbUnitContextResolver());
233			if (MSTestMockingContextResolver.IsAvailable)
234				registeredContextResolvers.Add(new MSTestMockingContextResolver());
235			if (MSTestV2MockingContextResolver.IsAvailable)
236				registeredContextResolvers.Add(new MSTestV2MockingContextResolver());
237#endif
238
239			foreach (var resolver in registeredContextResolvers)
240			{
241				failThrower = resolver.GetFailMethod();
242				if (failThrower != null)
243					break;
244			}
245
246			if (failThrower == null)
247				failThrower = LocalMockingContextResolver.GetFailMethod();
248		}
249
250#if !PORTABLE
251		private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
252		{
253			MockingContext.Plugins.Dispose();
254		}
255#endif
256
257		private static void Fail(string msg)
258		{
259			failThrower(msg, DebugView.GetStateAsException());
260		}
261
262		private class FailureAggregator : IDisposable
263		{
264			private List<string> failures;
265			private int references = 1;
266			private string userMessage;
267
268			public FailureAggregator(string message)
269			{
270				userMessage = message;
271			}
272
273			public void AddRef(string message)
274			{
275				references++;
276				userMessage = message;
277			}
278
279			public void AddFailure(string msg)
280			{
281				if (failures == null)
282					failures = new List<string>();
283
284				failures.Add(msg);
285			}
286
287			public void Dispose()
288			{
289				if (references > 1)
290				{
291					references--;
292					return;
293				}
294
295				failureAggregator = null;
296
297				if (failures == null)
298					return;
299
300				if (failures.Count == 1)
301					Fail((userMessage != null ? userMessage + Environment.NewLine : null) + failures[0]);
302
303				var sb = new StringBuilder();
304				if (userMessage != null)
305					sb.AppendLine(userMessage);
306				sb.AppendLine("Multiple assertion failures:");
307				for (int i = 0; i < failures.Count; ++i)
308				{
309					sb.AppendFormat("{0}. ", i + 1);
310					sb.AppendLine(failures[i]);
311				}
312				Fail(sb.ToString());
313			}
314		}
315
316#if PORTABLE
317		private class StackTraceGeneratorException : Exception
318		{ }
319#endif
320	}
321}
322
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)