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

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

Run JustMockLite automation tests on LambdaTest cloud grid

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

EventStubsBehavior.cs

Source: EventStubsBehavior.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;
22
23namespace Telerik.JustMock.Core.Behaviors
24{
25	/// <summary>
26	/// An implementation detail interface. Not intended for external usage.
27	/// </summary>
28	[Mixin]
29	public interface IEventsMixin
30	{
31		/// <summary>
32		/// An implementation detail. Not intended for external usage.
33		/// </summary>
34		void RaiseEvent(EventInfo evt, object[] delegateArguments);
35	}
36
37	internal class EventStubsBehavior : IBehavior
38	{
39		private readonly Dictionary<EventInfo, Delegate> eventHandlers = new Dictionary<EventInfo, Delegate>();
40
41		public object CreateMixin()
42		{
43			return new EventsMixin(this);
44		}
45
46		public void Process(Invocation invocation)
47		{
48			var method = invocation.Method;
49
50			var candidateEvent = method.GetEventFromAddOrRemove();
51			if (candidateEvent == null)
52				return;
53
54			invocation.UserProvidedImplementation = true;
55			var delg = (Delegate)invocation.Args[0];
56
57			if (candidateEvent.GetAddMethod(true) == invocation.Method)
58				this.AddEventHandler(candidateEvent, delg);
59			else
60				this.RemoveEventHandler(candidateEvent, delg);
61		}
62
63		private void AddEventHandler(EventInfo evt, Delegate handler)
64		{
65			Delegate existing;
66			eventHandlers.TryGetValue(evt, out existing);
67			eventHandlers[evt] = Delegate.Combine(existing, handler);
68		}
69
70		private void RemoveEventHandler(EventInfo evt, Delegate handler)
71		{
72			Delegate existing;
73			eventHandlers.TryGetValue(evt, out existing);
74			eventHandlers[evt] = Delegate.Remove(existing, handler);
75		}
76
77		public void RaiseEvent(EventInfo evt, object[] delegateArguments)
78		{
79			Delegate existing;
80			eventHandlers.TryGetValue(evt, out existing);
81
82			if (existing != null)
83			{
84				try
85				{
86					object state;
87					MockingUtil.BindToMethod(MockingUtil.Default, new[] { existing.Method }, ref delegateArguments, null, null, null, out state);
88				}
89				catch (MissingMethodException ex)
90				{
91					throw new MockException(String.Format("Event signature {0} is incompatible with argument types ({1})",
92						existing.Method, String.Join(", ", delegateArguments.Select(x => x != null ? x.GetType().ToString() : "null").ToArray())
93						), ex);
94				}
95
96				var invoker = MockingUtil.MakeFuncCaller(existing);
97				ProfilerInterceptor.GuardExternal(() => invoker(delegateArguments, existing));
98			}
99		}
100
101		private class EventsMixin : IEventsMixin
102		{
103			private readonly EventStubsBehavior events;
104
105			public EventsMixin(EventStubsBehavior events)
106			{
107				this.events = events;
108			}
109
110			public void RaiseEvent(EventInfo evt, object[] delegateArguments)
111			{
112				events.RaiseEvent(evt, delegateArguments);
113			}
114		}
115	}
116}
117
Full Screen

MockCreationSettings.cs

Source: MockCreationSettings.cs Github

copy
1/*
2 JustMock Lite
3 Copyright © 2010-2015,2108 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.Reflection;
23using System.Reflection.Emit;
24using Telerik.JustMock.Core.Behaviors;
25using Telerik.JustMock.Setup;
26
27namespace Telerik.JustMock.Core
28{
29    internal class MockCreationSettings
30    {
31        private static readonly Behavior DefaultBehavior = Behavior.RecursiveLoose;
32
33        internal object[] Args { get; set; }
34
35        internal IEnumerable<object> Mixins { get; set; }
36
37        internal IEnumerable<IBehavior> SupplementaryBehaviors { get; set; }
38
39        internal IEnumerable<IBehavior> FallbackBehaviors { get; set; }
40
41        internal Type[] AdditionalMockedInterfaces { get; set; }
42
43        internal bool MockConstructorCall { get; set; }
44
45        internal bool MustCreateProxy { get; set; }
46
47        internal IEnumerable<CustomAttributeBuilder> AdditionalProxyTypeAttributes { get; set; }
48
49        internal Expression<Predicate<MethodInfo>> InterceptorFilter { get; set; }
50
51        internal static MockCreationSettings GetSettings(object[] constructorArgs, Behavior? behavior,
52            Type[] additionalMockedInterfaces, bool? mockConstructorCall, IEnumerable<CustomAttributeBuilder> additionalProxyTypeAttributes = null,
53            List<IBehavior> supplementaryBehaviors = null, List<IBehavior> fallbackBehaviors = null, List<object> mixins = null, Expression<Predicate<MethodInfo>> interceptorFilter = null)
54        {
55            if (behavior == null)
56                behavior = DefaultBehavior;
57
58            MockCreationSettings settings = MockCreationSettings.DissectBehavior(behavior.Value, constructorArgs, mockConstructorCall);
59            settings.AdditionalMockedInterfaces = additionalMockedInterfaces;
60            settings.AdditionalProxyTypeAttributes = additionalProxyTypeAttributes;
61            settings.InterceptorFilter = interceptorFilter;
62
63            if (supplementaryBehaviors != null)
64            {
65                settings.SupplementaryBehaviors = new List<IBehavior>(settings.SupplementaryBehaviors.Concat(supplementaryBehaviors));
66            }
67
68            if (fallbackBehaviors != null)
69            {
70                settings.FallbackBehaviors = new List<IBehavior>(settings.FallbackBehaviors.Concat(fallbackBehaviors));
71            }
72
73            if (mixins != null)
74            {
75                settings.Mixins = new List<object>(settings.Mixins.Concat(mixins));
76            }
77
78            return settings;
79        }
80
81        /// <summary>
82        /// Creates instance <see cref="MockCreationSettings"/> for the default behavior <see cref="Behavior.RecursiveLoose"/>.
83        /// </summary>
84        /// <returns><see cref="MockCreationSettings"/> instance</returns>
85        internal static MockCreationSettings GetSettings()
86        {
87            MockCreationSettings settings = MockCreationSettings.DissectBehavior(MockCreationSettings.DefaultBehavior, constructorArgs: null, mockConstructorCall: null);
88            return settings;
89        }
90
91        /// <summary>
92        /// Creates instance <see cref="MockCreationSettings"/> for the specified behavior.
93        /// </summary>
94        /// <param name="behavior">Behavior for which to create the settings</param>
95        /// <returns><see cref="MockCreationSettings"/> instance</returns>
96        internal static MockCreationSettings GetSettings(Behavior behavior)
97        {
98            MockCreationSettings settings = MockCreationSettings.DissectBehavior(behavior, constructorArgs: null, mockConstructorCall: null);
99            return settings;
100        }
101
102        private static MockCreationSettings DissectBehavior(Behavior behavior, object[] constructorArgs, bool? mockConstructorCall)
103        {
104            var supplementaryBehaviors = new List<IBehavior>();
105            var fallbackBehaviors = new List<IBehavior>();
106            var mixins = new List<object>();
107
108            mixins.Add(new MockingBehaviorConfiguration { Behavior = behavior });
109
110            var eventStubs = new EventStubsBehavior();
111            mixins.Add(eventStubs.CreateMixin());
112
113            switch (behavior)
114            {
115                case Behavior.RecursiveLoose:
116                case Behavior.Loose:
117                    fallbackBehaviors.Add(eventStubs);
118                    fallbackBehaviors.Add(new PropertyStubsBehavior());
119                    fallbackBehaviors.Add(new CallOriginalObjectMethodsBehavior());
120                    fallbackBehaviors.Add(new RecursiveMockingBehavior(behavior == Behavior.RecursiveLoose
121                        ? RecursiveMockingBehaviorType.ReturnMock : RecursiveMockingBehaviorType.ReturnDefault));
122                    fallbackBehaviors.Add(new StaticConstructorMockBehavior());
123                    fallbackBehaviors.Add(new ExecuteConstructorBehavior());
124                    break;
125                case Behavior.Strict:
126                    fallbackBehaviors.Add(eventStubs);
127                    fallbackBehaviors.Add(new RecursiveMockingBehavior(RecursiveMockingBehaviorType.OnlyDuringAnalysis));
128                    fallbackBehaviors.Add(new StaticConstructorMockBehavior());
129                    fallbackBehaviors.Add(new ExecuteConstructorBehavior());
130                    fallbackBehaviors.Add(new StrictBehavior(throwOnlyOnValueReturningMethods: false));
131                    supplementaryBehaviors.Add(new StrictBehavior(throwOnlyOnValueReturningMethods: true));
132                    break;
133                case Behavior.CallOriginal:
134                    fallbackBehaviors.Add(new CallOriginalBehavior());
135                    fallbackBehaviors.Add(eventStubs);
136                    fallbackBehaviors.Add(new RecursiveMockingBehavior(RecursiveMockingBehaviorType.OnlyDuringAnalysis));
137                    fallbackBehaviors.Add(new StaticConstructorMockBehavior());
138                    fallbackBehaviors.Add(new ExecuteConstructorBehavior());
139                    break;
140            }
141
142            if (!mockConstructorCall.HasValue)
143            {
144                switch (behavior)
145                {
146                    case Behavior.RecursiveLoose:
147                    case Behavior.Loose:
148                    case Behavior.Strict:
149                        mockConstructorCall = constructorArgs == null;
150                        break;
151                    case Behavior.CallOriginal:
152                        mockConstructorCall = false;
153                        break;
154                }
155            }
156
157            return new MockCreationSettings
158            {
159                Args = constructorArgs,
160                Mixins = mixins,
161                SupplementaryBehaviors = supplementaryBehaviors,
162                FallbackBehaviors = fallbackBehaviors,
163                MockConstructorCall = mockConstructorCall.Value,
164            };
165        }
166    }
167}
168
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)