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

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

Run JustMockLite automation tests on LambdaTest cloud grid

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

EventClassFactory.cs

Source: EventClassFactory.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Reflection;
5using System.Reflection.Emit;
6using System.Text;
7
8namespace Telerik.JustMock.Tests
9{
10	public static class EventClassFactory
11	{
12		private static ModuleBuilder moduleBuilder;
13		private const string ModuleName = "Telerik.JustMock.DemoLib.Dynamic";
14
15		public static Type CreateClassWithEventWithRaiseMethod()
16		{
17			if (moduleBuilder == null)
18			{
19#if !NETCORE
20				var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(ModuleName), AssemblyBuilderAccess.Run);
21#else
22				var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(ModuleName), AssemblyBuilderAccess.Run);
23#endif
24				moduleBuilder = assemblyBuilder.DefineDynamicModule(ModuleName);
25			}
26
27			var type = moduleBuilder.DefineType(ModuleName + ".Type" + Guid.NewGuid().ToString("N"), TypeAttributes.Public);
28
29			var probe = type.DefineField("Probe", typeof(Action), FieldAttributes.Public);
30
31			var raise = type.DefineMethod("Raise", MethodAttributes.Private);
32			var il = raise.GetILGenerator();
33			il.Emit(OpCodes.Ldarg_0);
34			il.Emit(OpCodes.Ldfld, probe);
35			il.Emit(OpCodes.Callvirt, typeof(Action).GetMethod("Invoke"));
36			il.Emit(OpCodes.Ret);
37
38			var evt = type.DefineEvent("StuffHappened", EventAttributes.None, typeof(Action));
39			evt.SetRaiseMethod(raise);
40
41
42			return type.CreateType();
43		}
44	}
45}
46
Full Screen

EventsFixture.cs

Source: EventsFixture.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.Collections.ObjectModel;
21using System.Collections.Specialized;
22using Telerik.JustMock.Core;
23using Telerik.JustMock.Tests.EventFixureDependencies;
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#if XUNIT2
53#pragma warning disable xUnit1013 
54#endif
55
56namespace Telerik.JustMock.Tests
57{
58	[TestClass]
59	public class EventsFixture
60	{
61
62		private ProjectNavigatorViewModel viewModel;
63		private ISolutionService solutionService;
64
65#if XUNIT
66		public EventsFixture()
67		{
68			Initialize();
69		}
70#endif
71
72		[TestInitialize]
73		public void Initialize()
74		{
75			this.solutionService = Mock.Create<ISolutionService>();
76			this.viewModel = new ProjectNavigatorViewModel(this.solutionService);
77		}
78
79		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
80		public void ShouldRaiseCustomEventOnMethodCall()
81		{
82			var foo = Mock.Create<IFoo>();
83
84			const string expected = "ping";
85			string actual = string.Empty;
86
87			Mock.Arrange(() => foo.RaiseMethod()).Raises(() => foo.CustomEvent += null, expected);
88
89			foo.CustomEvent += (s) => { actual = s; };
90			foo.RaiseMethod();
91
92			Assert.Equal(expected, actual);
93		}
94
95		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
96		public void ShoulRaiseCustomEventForFuncCalls()
97		{
98			bool echoed = false;
99
100			var foo = Mock.Create<IFoo>();
101
102			Mock.Arrange(() => foo.Echo("string")).Raises(() => foo.EchoEvent += null, true).Returns("echoed");
103			foo.EchoEvent += (c) => { echoed = c; };
104
105			Assert.Equal(foo.Echo("string"), "echoed");
106			Assert.True(echoed);
107		}
108
109		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
110		public void ShouldRaiseEventWhenExpectationIsMet()
111		{
112			var executor = Mock.Create<IExecutor<int>>();
113
114			bool raised = false;
115
116			Mock.Arrange(() => executor.Execute(Arg.IsAny<int>())).Raises(() => executor.Executed += null, EventArgs.Empty);
117
118			executor.Executed += delegate { raised = true; };
119
120			executor.Execute(1);
121
122			Assert.True(raised);
123		}
124
125		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
126		public void ShouldRaiseEventForEventArgsLambdaWithOneArgument()
127		{
128			var executor = Mock.Create<IExecutor<int>>();
129
130			Mock.Arrange(() => executor.Execute(Arg.IsAny<string>()))
131				.Raises(() => executor.Done += null, (string s) => new FooArgs { Value = s });
132
133			FooArgs args = null;
134			executor.Done += (sender, e) => args = e;
135			executor.Execute("done");
136
137			Assert.Equal(args.Value, "done");
138		}
139
140		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
141		public void ShouldRaiseEventForEventArgsLambdaWithTwoArguments()
142		{
143			var executor = Mock.Create<IExecutor<int>>();
144
145			Mock.Arrange(() => executor.Execute(Arg.IsAny<string>(), Arg.IsAny<int>()))
146				.Raises(() => executor.Done += null, (string s, int i) => new FooArgs { Value = s + i });
147
148			FooArgs args = null;
149			executor.Done += (sender, e) => args = e;
150			executor.Execute("done", 2);
151
152			Assert.Equal(args.Value, "done2");
153		}
154
155		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
156		public void ShouldRaiseEventForEventArgsLambdaWithThreeArguments()
157		{
158			var executor = Mock.Create<IExecutor<int>>();
159
160			Mock.Arrange(() => executor.Execute(Arg.IsAny<string>(), Arg.IsAny<int>(), Arg.IsAny<bool>()))
161				.Raises(() => executor.Done += null, (string s, int i, bool b) => new FooArgs { Value = s + i + b });
162
163			FooArgs args = null;
164			executor.Done += (sender, e) => args = e;
165			executor.Execute("done", 3, true);
166
167			Assert.Equal(args.Value, "done3True");
168		}
169
170		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
171		public void ShouldRaiseEventForEventArgsLambdaWithFourArguments()
172		{
173			var executor = Mock.Create<IExecutor<int>>();
174
175			Mock.Arrange(() => executor.Execute(Arg.IsAny<string>(), Arg.IsAny<int>(), Arg.IsAny<bool>(), Arg.IsAny<string>()))
176				.Raises(() => executor.Done += null, (string s, int i, bool b, string s1) => new FooArgs { Value = s + i + b + s1 });
177
178			FooArgs args = null;
179			executor.Done += (sender, e) => args = e;
180			executor.Execute("done", 4, true, "ok");
181
182			Assert.Equal(args.Value, "done4Trueok");
183		}
184
185		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
186		public void ShouldAssertRaiseAndReturnForFuncCallWithOneArg()
187		{
188			var executor = Mock.Create<IExecutor<int>>();
189
190			Mock.Arrange(() => executor.Echo(Arg.IsAny<string>()))
191			.Raises(() => executor.Done += null, (string s) => new FooArgs { Value = s })
192			.Returns((string s) => s);
193
194			FooArgs args = null;
195			executor.Done += (sender, e) => args = e;
196
197			Assert.Equal(executor.Echo("echo"), args.Value);
198		}
199
200		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
201		public void ShouldAssertMultipleEventSubscription()
202		{
203			var foo = Mock.Create<IFoo>();
204
205			Mock.Arrange(() => foo.Execute()).Raises(() => foo.EchoEvent += null, true);
206
207			bool echoed1 = false;
208			bool echoed2 = false;
209
210			foo.EchoEvent += c => { echoed1 = c; };
211			foo.EchoEvent += c => { echoed2 = c; };
212
213			foo.Execute();
214
215			Assert.True(echoed1);
216			Assert.True(echoed2);
217		}
218
219		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
220		public void ShouldRaiseEventWithStandardEventArgs()
221		{
222			var executor = Mock.Create<IExecutor<int>>();
223
224			string acutal = null;
225			string expected = "ping";
226
227			executor.Done += delegate(object sender, FooArgs args)
228			{
229				acutal = args.Value;
230			};
231
232			Mock.Raise(() => executor.Done += null, new FooArgs(expected));
233
234			Assert.Equal(expected, acutal);
235		}
236
237		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
238		public void ShouldRaiseEventWithCustomEventArgs()
239		{
240			var foo = Mock.Create<IFoo>();
241
242			string expected = "ping";
243			string acutal = string.Empty;
244
245
246			foo.CustomEvent += delegate(string s)
247			{
248				acutal = s;
249			};
250
251			Mock.Raise(() => foo.CustomEvent += null, expected);
252			Assert.Equal(expected, acutal);
253		}
254
255		[TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("MockingContext")]
256		public void ShouldAssertMockRaiseFromInsideAContainer()
257		{
258			var foo = Mock.Create<IFoo>();
259			var projectEventArgs = new ProjectEventArgs(foo);
260			Mock.Raise(() => this.solutionService.ProjectAdded += null, projectEventArgs);
261			Assert.True(this.viewModel.IsProjectAddedCalled);
262		}
263
264		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
265		public void ShouldNotCallDelegateAfterEventDetach()
266		{
267			var executor = Mock.Create<IExecutor<int>>();
268
269			Mock.Arrange(() => executor.Execute(Arg.IsAny<string>()))
270				.Raises(() => executor.Done += null, (string s) => new FooArgs { Value = s });
271
272			FooArgs args = null;
273			EventHandler<FooArgs> handler = (sender, e) => args = e;
274			executor.Done += (o, e) => { };
275
276			executor.Done += handler;
277			executor.Execute("done");
278			Assert.Equal(args.Value, "done");
279
280			executor.Done -= handler;
281			args = null;
282			executor.Execute("done");
283			Assert.Null(args);
284		}
285
286		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
287		public void ShouldRetainArrangementsInRaiseDelegate()
288		{
289			var activeDocument = Mock.Create<IDocument>(Behavior.Loose);
290			var activeView = Mock.Create<IDocumentView>();
291			Mock.Arrange(() => activeView.Document).Returns(activeDocument);
292			Mock.Raise(() => activeView.Document.IsDirtyChanged += null, EventArgs.Empty);
293		}
294
295		public interface IHasEvent
296		{
297			event Action StuffHappened;
298			int Value { get; }
299		}
300
301		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
302		public void ShouldRetainArrangementsInMockEventHandler()
303		{
304			var mock = Mock.Create<IHasEvent>();
305			Mock.Arrange(() => mock.Value).Returns(5);
306			int actualValue = 0;
307			mock.StuffHappened += () => actualValue = mock.Value;
308
309			Mock.Raise(() => mock.StuffHappened += null);
310
311			Assert.Equal(5, actualValue);
312		}
313
314#if !COREFX
315		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
316		public void ShouldRetainArrangementsInEventHandlerFromPrivateAccessor()
317		{
318			var mock = Mock.Create<IHasEvent>();
319			Mock.Arrange(() => mock.Value).Returns(5);
320			int actualValue = 0;
321			var coll = new ObservableCollection<object>();
322			coll.CollectionChanged += (o, e) => actualValue = mock.Value;
323
324			new PrivateAccessor(coll).RaiseEvent("CollectionChanged", coll, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
325
326			Assert.Equal(5, actualValue);
327		}
328
329		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
330		public void ShouldRetainArrangementsInEventHandlerFromPrivateAccessorForEventWithRaiseMethod()
331		{
332			var mock = Mock.Create<IHasEvent>();
333			Mock.Arrange(() => mock.Value).Returns(5);
334			int actualValue = 0;
335
336			var type = EventClassFactory.CreateClassWithEventWithRaiseMethod();
337			var obj = Activator.CreateInstance(type);
338			Action probe = () => actualValue = mock.Value;
339			type.GetField("Probe").SetValue(obj, probe);
340
341			new PrivateAccessor(obj).RaiseEvent("StuffHappened");
342
343			Assert.Equal(5, actualValue);
344		}
345#endif
346
347		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
348		public void ShouldAssertEventHandlerAddingOccurrence()
349		{
350			var doc = Mock.Create<IDocument>();
351			Mock.ArrangeSet<IDocument>(() => doc.IsDirtyChanged += null).IgnoreArguments().OccursOnce();
352
353			Assert.Throws<AssertionException>(() => Mock.Assert(doc));
354
355			doc.IsDirtyChanged += (o, e) => { };
356			Mock.Assert(doc);
357		}
358
359		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
360		public void ShouldRaiseEventWithNullEventArgsArgument()
361		{
362			var doc = Mock.Create<IDocument>();
363			EventArgs args = EventArgs.Empty;
364			doc.IsDirtyChanged += (o, e) => args = e;
365			Mock.Raise(() => doc.IsDirtyChanged += null, null);
366		}
367
368		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
369		public void ShouldThrowIncompatibleSignatureExceptionWhenExpectedArgumentsDontMatch()
370		{
371			var doc = Mock.Create<IDocument>();
372			doc.IsDirtyChanged += (o, e) => { };
373			Assert.Throws<Exception>(() => Mock.Raise(() => doc.IsDirtyChanged += null));
374			Assert.Throws<Exception>(() => Mock.Raise(() => doc.IsDirtyChanged += null, 1, 2));
375		}
376
377		public interface IDocumentView
378		{
379			IDocument Document { get; }
380		}
381
382		public interface IDocument
383		{
384			event EventHandler IsDirtyChanged;
385		}
386
387		[TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("NonPublic")]
388		public void ShouldRaiseCSharpEventOnNonmock()
389		{
390#if COREFX
391			if (Mock.IsProfilerEnabled)
392#endif
393			{
394				var hasEvent = new HasEvent();
395				bool called = false;
396				hasEvent.Event += () => called = true;
397				Mock.NonPublic.Raise(hasEvent, "Event");
398				Assert.True(called);
399			}
400		}
401
402		[TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("NonPublic")]
403		public void ShouldRaiseEventOnMockByName()
404		{
405#if COREFX
406			if (Mock.IsProfilerEnabled)
407#endif
408			{
409				var hasEvent = Mock.Create<HasEvent>();
410				bool called = false;
411				hasEvent.Event += () => called = true;
412				Mock.NonPublic.Raise(hasEvent, "Event");
413				Assert.True(called);
414			}
415		}
416
417		[TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("NonPublic")]
418		public void ShouldRaiseStaticEventOnNonmockByName()
419		{
420#if COREFX
421			if (Mock.IsProfilerEnabled)
422#endif
423			{
424				bool called = false;
425				HasEvent.StaticEvent += () => called = true;
426				Mock.NonPublic.Raise(typeof(HasEvent), "StaticEvent");
427				Assert.True(called);
428			}
429		}
430
431		public class HasEvent
432		{
433			public virtual event Action Event;
434			public static event Action StaticEvent;
435		}
436	}
437
438	[TestClass]
439	public class RecordingWorksWhenTestClassHasMockMixin
440	{
441		private IDocumentView activeView;
442
443#if XUNIT
444		public RecordingWorksWhenTestClassHasMockMixin()
445		{
446			BeforeEach();
447		}
448#endif
449
450		[TestInitialize]
451		public void BeforeEach()
452		{
453			var activeDocument = Mock.Create<IDocument>();
454			this.activeView = Mock.Create<IDocumentView>();
455			Mock.Arrange(() => this.activeView.Document).Returns(activeDocument);
456		}
457
458		[TestMethod, TestCategory("Lite"), TestCategory("Events")]
459		public void ActiveDocument_WhenIsDirtyChanged_ShouldRaiseCanExecuteChangedEvent()
460		{
461			Mock.Raise(() => this.activeView.Document.IsDirtyChanged += null, EventArgs.Empty);
462		}
463
464		public interface IDocumentView
465		{
466			IDocument Document { get; }
467		}
468
469		public interface IDocument
470		{
471			event EventHandler IsDirtyChanged;
472		}
473	}
474}
475
476#if XUNIT2
477#pragma warning restore xUnit1013 
478#endif
479
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 EventClassFactory

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)