Best JustMockLite code snippet using Telerik.JustMock.Core.MatcherTree.AnyMatcher.Equals
MocksRepository.cs
Source:MocksRepository.cs
...214 equal = AreValueTypeObjectsInRegistryEqual(obj, otherObj);215 }216 catch217 {218 throw new MockException("Implementation of method Equals in value types must not throw for mocked instances.");219 }220 if (equal)221 return entry.Value;222 }223 }224 }225 else226 {227 IMockMixin result;228 externalReferenceMixinDatabase.TryGetValue(obj, out result);229 return result;230 }231 }232 return null;233 }234 private static bool AreTypesInRegistrySame(Type queryType, Type typeInRegistry)235 {236 if (queryType == typeInRegistry)237 return true;238 return false;239 }240 private static bool AreValueTypeObjectsInRegistryEqual(object queryObj, object objInRegistry)241 {242 return Object.Equals(queryObj, objInRegistry); // no guard - Object.Equals on a value type can't get intercepted243 }244 private MethodInfoMatcherTreeNode DeepCopy(MethodInfoMatcherTreeNode root)245 {246 var newRoot = (MethodInfoMatcherTreeNode)root.Clone();247 Queue<MatcherNodeAndParent> queue = new Queue<MatcherNodeAndParent>();248 foreach (var child in root.Children)249 queue.Enqueue(new MatcherNodeAndParent(child, newRoot));250 while (queue.Count > 0)251 {252 MatcherNodeAndParent current = queue.Dequeue();253 IMatcherTreeNode newCurrent = current.Node.Clone();254 foreach (IMatcherTreeNode node in current.Node.Children)255 {256 queue.Enqueue(new MatcherNodeAndParent(node, newCurrent));257 }258 current.Parent.Children.Add(newCurrent);259 newCurrent.Parent = current.Parent;260 }261 return newRoot;262 }263 private void CopyConfigurationFromParent()264 {265 this.arrangementTreeRoots.Clear();266 this.invocationTreeRoots.Clear();267 this.valueStore.Clear();268 this.controlledMocks.Clear();269 if (parentRepository != null)270 {271 foreach (var root in parentRepository.arrangementTreeRoots)272 {273 this.arrangementTreeRoots.Add(root.Key, DeepCopy(root.Value));274 }275 foreach (var root in parentRepository.invocationTreeRoots)276 {277 this.invocationTreeRoots.Add(root.Key, DeepCopy(root.Value));278 }279 foreach (var kvp in parentRepository.valueStore)280 {281 this.valueStore.Add(kvp.Key, kvp.Value);282 }283 foreach (WeakReference mockRef in parentRepository.controlledMocks)284 {285 IMockMixin mixin = GetMockMixinFromAnyMock(mockRef.Target);286 if (mixin != null)287 {288 mixin.Repository = this;289 this.controlledMocks.Add(mockRef);290 }291 }292 }293 }294 internal void Retire()295 {296 this.IsRetired = true;297 this.Reset();298 }299 internal void InterceptGlobally(MethodBase method)300 {301 if (this.globallyInterceptedMethods.Add(method))302 {303 ProfilerInterceptor.RegisterGlobalInterceptor(method, this);304 }305 }306 internal void Reset()307 {308 DebugView.TraceEvent(IndentLevel.Configuration, () => String.Format("Resetting mock repository related to {0}.", this.Method));309 foreach (var type in this.arrangedTypes)310 {311 ProfilerInterceptor.EnableInterception(type, false, this);312 }313 this.arrangedTypes.Clear();314 this.staticMixinDatabase.Clear();315 foreach (var method in this.globallyInterceptedMethods)316 {317 ProfilerInterceptor.UnregisterGlobalInterceptor(method, this);318 }319 this.globallyInterceptedMethods.Clear();320 lock (externalMixinDatabase)321 {322 foreach (WeakReference mockRef in this.controlledMocks)323 {324 IMockMixin mock = GetMockMixinFromAnyMock(mockRef.Target);325 if (mock != null && mock.ExternalizedMock != null && mock.Originator == this)326 {327 externalMixinDatabase.RemoveAll(kvp => kvp.Value == mock);328 externalReferenceMixinDatabase.Remove(mock.ExternalizedMock);329 }330 }331 }332 this.controlledMocks.Clear();333 this.CopyConfigurationFromParent();334 }335 internal void DispatchInvocation(Invocation invocation)336 {337 DebugView.TraceEvent(IndentLevel.DispatchResult, () => String.Format("Handling dispatch in repo #{0} servicing {1}", this.repositoryId, this.Method));338 if (this.disabledTypes.Contains(invocation.Method.DeclaringType))339 {340 invocation.CallOriginal = true;341 return;342 }343 invocation.InArrange = this.sharedContext.InArrange;344 invocation.InArrangeArgMatching = this.sharedContext.InArrangeArgMatching;345 invocation.InAssertSet = this.sharedContext.InAssertSet;346 invocation.InRunClassConstructor = this.sharedContext.RunClassConstructorCount > 0;347 invocation.Recording = this.Recorder != null;348 invocation.RetainBehaviorDuringRecording = this.sharedContext.DispatchToMethodMocks;349 invocation.Repository = this;350 bool methodMockProcessed = false;351 if (invocation.Recording)352 {353 this.Recorder.Record(invocation);354 }355 if (!invocation.Recording || invocation.RetainBehaviorDuringRecording)356 {357 methodMockProcessed = DispatchInvocationToMethodMocks(invocation);358 }359 invocation.ThrowExceptionIfNecessary();360 if (!methodMockProcessed)361 {362 // We have to be careful for the potential exception throwing in the assertion context,363 // so skip CallOriginalBehavior processing364 var mock = invocation.MockMixin;365 if (mock != null)366 {367 var fallbackBehaviorsToExecute =368 mock.FallbackBehaviors369 .Where(behavior => !invocation.InAssertSet || !(behavior is CallOriginalBehavior))370 .ToList();371 foreach (var fallbackBehavior in fallbackBehaviorsToExecute)372 {373 fallbackBehavior.Process(invocation);374 }375 }376 else377 {378 invocation.CallOriginal = CallOriginalBehavior.ShouldCallOriginal(invocation) && !invocation.InAssertSet;379 }380 }381 if (!invocation.CallOriginal && !invocation.IsReturnValueSet && invocation.Method.GetReturnType() != typeof(void))382 {383 Type returnType = invocation.Method.GetReturnType();384 object defaultValue = null;385#if !PORTABLE386 if (returnType.BaseType != null && returnType.BaseType == typeof(Task))387 {388 Type taskGenericArgument = returnType.GenericTypeArguments.FirstOrDefault();389 object taskArgumentDefaultValue = taskGenericArgument.GetDefaultValue();390 // create a task with default value to return, by using the casting help method in MockingUtil391 MethodInfo castMethod = typeof(MockingUtil).GetMethod("TaskFromObject", BindingFlags.Static | BindingFlags.Public);392 MethodInfo castMethodGeneric = castMethod.MakeGenericMethod(taskGenericArgument);393 defaultValue = castMethodGeneric.Invoke(null, new object[] { taskArgumentDefaultValue });394 }395 else396#endif397 {398 defaultValue = returnType.GetDefaultValue();399 }400 invocation.ReturnValue = defaultValue;401 }402#if !PORTABLE403 try404 {405 if (MockingContext.Plugins.Exists<IDebugWindowPlugin>())406 {407 Func<object, Type, ObjectInfo> CreateObjectInfo = (value, type) =>408 {409 ObjectInfo resultInfo = (value != null) ? ObjectInfo.FromObject(value) : ObjectInfo.FromNullObject(type);410 return resultInfo;411 };412 var debugWindowPlugin = MockingContext.Plugins.Get<IDebugWindowPlugin>();413 var mockInfo = MockInfo.FromMethodBase(invocation.Method);414 ObjectInfo[] invocationsArgInfos =415 invocation.Args.Select(416 (arg, index) =>417 {418 var argInfo = CreateObjectInfo(arg, invocation.Method.GetParameters()[index].ParameterType);419 return argInfo;420 }).ToArray();421 ObjectInfo invocationInstanceInfo = ObjectInfo.FromObject(invocation.Instance ?? invocation.Method.DeclaringType);422 ObjectInfo invocationResultInfo = CreateObjectInfo(invocation.ReturnValue, invocation.Method.GetReturnType());423 var invocationInfo = new InvocationInfo(invocationInstanceInfo, invocationsArgInfos, invocationResultInfo);424 debugWindowPlugin.MockInvoked(425 invocation.Repository.RepositoryId,426 invocation.Repository.GetRepositoryPath(),427 mockInfo,428 invocationInfo);429 }430 }431 catch (Exception e)432 {433 System.Diagnostics.Trace.WriteLine("Exception thrown calling IDebugWindowPlugin plugin: " + e);434 }435#endif436 }437 internal T GetValue<T>(object owner, object key, T dflt)438 {439 object value;440 if (valueStore.TryGetValue(new KeyValuePair<object, object>(owner, key), out value))441 {442 return (T)value;443 }444 else445 {446 return dflt;447 }448 }449 internal void StoreValue<T>(object owner, object key, T value)450 {451 valueStore[new KeyValuePair<object, object>(owner, key)] = value;452 }453 internal IDisposable StartRecording(IRecorder recorder, bool dispatchToMethodMocks)454 {455 return this.sharedContext.StartRecording(recorder, dispatchToMethodMocks);456 }457 internal IDisposable StartArrangeArgMatching()458 {459 return this.sharedContext.StartArrangeArgMatching();460 }461 internal void AddMatcherInContext(IMatcher matcher)462 {463 if (!this.sharedContext.InArrange || this.sharedContext.Recorder != null)464 {465 this.MatchersInContext.Add(matcher);466 }467 }468 internal object Create(Type type, MockCreationSettings settings)469 {470 object delegateResult;471 if (TryCreateDelegate(type, settings, out delegateResult))472 {473 return delegateResult;474 }475 bool isSafeMock = settings.FallbackBehaviors.OfType<CallOriginalBehavior>().Any();476 this.CheckIfCanMock(type, !isSafeMock);477 this.EnableInterception(type);478 bool canCreateProxy = !type.IsSealed;479 MockMixin mockMixinImpl = this.CreateMockMixin(type, settings);480 ConstructorInfo[] ctors = type.GetConstructors();481 bool isCoclass = ctors.Any(ctor => ctor.IsExtern());482 bool hasAdditionalInterfaces = settings.AdditionalMockedInterfaces != null && settings.AdditionalMockedInterfaces.Length > 0;483 bool hasAdditionalProxyTypeAttributes = settings.AdditionalProxyTypeAttributes != null && settings.AdditionalProxyTypeAttributes.Any();484 bool shouldCreateProxy = settings.MustCreateProxy485 || hasAdditionalInterfaces486 || isCoclass487 || type.IsAbstract || type.IsInterface488 || !settings.MockConstructorCall489 || hasAdditionalProxyTypeAttributes490 || !ProfilerInterceptor.IsProfilerAttached491 || !ProfilerInterceptor.TypeSupportsInstrumentation(type);492 bool createTransparentProxy = MockingProxy.CanCreate(type) && !ProfilerInterceptor.IsProfilerAttached;493 Exception proxyFailure = null;494 object instance = null;495 if (canCreateProxy && shouldCreateProxy)496 {497 try498 {499 instance = mockFactory.Create(type, this, mockMixinImpl, settings, createTransparentProxy);500 }501 catch (ProxyFailureException ex)502 {503 proxyFailure = ex.InnerException;504 }505 }506 IMockMixin mockMixin = instance as IMockMixin;507 if (instance == null)508 {509 if (type.IsInterface || type.IsAbstract)510 throw new MockException(String.Format("Abstract type '{0}' is not accessible for inheritance.", type));511 if (hasAdditionalInterfaces)512 throw new MockException(String.Format("Type '{0}' is not accessible for inheritance. Cannot create mock object implementing the specified additional interfaces.", type));513 if (!ProfilerInterceptor.IsProfilerAttached && !createTransparentProxy)514 ProfilerInterceptor.ThrowElevatedMockingException(type);515 if (settings.MockConstructorCall && type.IsValueType)516 {517 settings.MockConstructorCall = false;518 settings.Args = null;519 }520 if (!settings.MockConstructorCall)521 {522 try523 {524 instance = type.CreateObject(settings.Args);525 }526 catch (MissingMethodException)527 {528 settings.MockConstructorCall = true;529 }530 }531 if (settings.MockConstructorCall)532 {533 instance = MockingUtil.GetUninitializedObject(type);534 }535 if (!createTransparentProxy)536 {537 mockMixin = this.CreateExternalMockMixin(type, instance, settings);538 }539 }540 else541 {542 this.controlledMocks.Add(new WeakReference(instance));543 }544 if (type.IsClass)545 GC.SuppressFinalize(instance);546 if (createTransparentProxy)547 {548 if (mockMixin == null)549 {550 mockMixin = mockMixinImpl;551 }552 instance = MockingProxy.CreateProxy(instance, this, mockMixin);553 }554 mockMixin.IsInstanceConstructorMocked = settings.MockConstructorCall;555 return instance;556 }557 internal IMockMixin CreateExternalMockMixin(Type mockObjectType, object mockObject, MockCreationSettings settings)558 {559 if (mockObjectType == null)560 {561 if (mockObject == null)562 throw new ArgumentNullException("mockObject");563 mockObjectType = mockObject.GetType();564 }565 this.EnableInterception(mockObjectType);566 if (mockObject == null)567 throw new MockException(String.Format("Failed to create instance of type '{0}'", mockObjectType));568 MockMixin mockMixin = this.CreateMockMixin(mockObjectType, settings, false);569 IMockMixin compoundMockMixin = mockFactory.CreateExternalMockMixin(mockMixin, settings.Mixins);570 lock (externalMixinDatabase)571 {572 if (mockObjectType.IsValueType())573 {574 externalMixinDatabase.RemoveAll(kvp => kvp.Key.Equals(mockObject));575 externalMixinDatabase.Add(new KeyValuePair<object, IMockMixin>(mockObject, compoundMockMixin));576 }577 else578 {579 externalReferenceMixinDatabase.Add(mockObject, compoundMockMixin);580 }581 compoundMockMixin.ExternalizedMock = mockObject;582 this.controlledMocks.Add(new WeakReference(compoundMockMixin));583 }584 return compoundMockMixin;585 }586 internal ProxyTypeInfo CreateClassProxyType(Type classToProxy, MockCreationSettings settings)587 {588 MockMixin mockMixinImpl = this.CreateMockMixin(classToProxy, settings);589 return mockFactory.CreateClassProxyType(classToProxy, this, settings, mockMixinImpl);590 }591 private void CheckIfCanMock(Type type, bool checkSafety)592 {593 if (KnownUnmockableTypes.Contains(type)594 || typeof(Delegate).IsAssignableFrom(type))595 throw new MockException("Cannot create mock for type due to CLR limitations.");596 if (checkSafety)597 ProfilerInterceptor.CheckIfSafeToInterceptWholesale(type);598 }599 internal void InterceptStatics(Type type, MockCreationSettings settings, bool mockStaticConstructor)600 {601 if (!ProfilerInterceptor.IsProfilerAttached)602 ProfilerInterceptor.ThrowElevatedMockingException(type);603 if (!settings.FallbackBehaviors.OfType<CallOriginalBehavior>().Any())604 ProfilerInterceptor.CheckIfSafeToInterceptWholesale(type);605 var mockMixin = (IMockMixin)Create(typeof(ExternalMockMixin),606 new MockCreationSettings607 {608 Mixins = settings.Mixins,609 SupplementaryBehaviors = settings.SupplementaryBehaviors,610 FallbackBehaviors = settings.FallbackBehaviors,611 MustCreateProxy = true,612 });613 mockMixin.IsStaticConstructorMocked = mockStaticConstructor;614 lock (staticMixinDatabase)615 staticMixinDatabase[type] = mockMixin;616 this.EnableInterception(type);617 }618 private MockMixin CreateMockMixin(Type declaringType, MockCreationSettings settings)619 {620 return CreateMockMixin(declaringType, settings, settings.MockConstructorCall);621 }622 private MockMixin CreateMockMixin(Type declaringType, MockCreationSettings settings, bool mockConstructorCall)623 {624 var mockMixin = new MockMixin625 {626 Repository = this,627 DeclaringType = declaringType,628 IsInstanceConstructorMocked = mockConstructorCall,629 };630 foreach (var behavior in settings.SupplementaryBehaviors)631 mockMixin.SupplementaryBehaviors.Add(behavior);632 foreach (var behavior in settings.FallbackBehaviors)633 mockMixin.FallbackBehaviors.Add(behavior);634 return mockMixin;635 }636 [ArrangeMethod]637 internal TMethodMock Arrange<TMethodMock>(Expression expression, Func<TMethodMock> methodMockFactory)638 where TMethodMock : IMethodMock639 {640 TMethodMock result = methodMockFactory();641 using (this.sharedContext.StartArrange())642 {643 result.Repository = this;644 result.ArrangementExpression = ExpressionUtil.ConvertMockExpressionToString(expression);645 result.CallPattern = CallPatternCreator.FromExpression(this, expression);646 AddArrange(result);647 }648#if !PORTABLE649 var createInstanceLambda = ActivatorCreateInstanceTBehavior.TryCreateArrangementExpression(result.CallPattern.Method);650 if (createInstanceLambda != null)651 {652 var createInstanceMethodMock = Arrange(createInstanceLambda, methodMockFactory);653 ActivatorCreateInstanceTBehavior.Attach(result, createInstanceMethodMock);654 }655#endif656 return result;657 }658 /// <summary>659 /// Since we are not able to record deffered execution, check whether mock is about to present660 /// IQueryable<> or IEnumerable<>. If it so, then throw an exception to prompt the user to use661 /// Mock.Arrange overloads with expressions.662 /// See also https://stackoverflow.com/questions/3894490/linq-what-is-the-quickest-way-to-find-out-deferred-execution-or-not663 /// </summary>664 /// <typeparam name="TMethodMock">Mock return type</typeparam>665 /// <param name="methodMockFactory">Mock factory</param>666 private void CheckDefferedExecutionTypes<TMethodMock>(Func<TMethodMock> methodMockFactory)667 {668 var mockFactoryType = methodMockFactory.GetType().GetGenericArguments().FirstOrDefault();669 if (mockFactoryType.IsGenericType && mockFactoryType.GetGenericTypeDefinition() == typeof(FuncExpectation<>))670 {671 var mockFactoryGenericArguments = mockFactoryType.GetGenericArguments();672 if (mockFactoryGenericArguments673 .Where(a => a.IsGenericType)674 .Where(a => a.GetGenericTypeDefinition() == typeof(IQueryable<>)675 || a.GetGenericTypeDefinition() == typeof(IEnumerable<>))676 .Any())677 {678 throw new MockException("Cannot arrange action with potential deffered execution, use Mock.Arrange with expressions instead.");679 }680 }681 }682 [ArrangeMethod]683 internal TMethodMock Arrange<TMethodMock>(Action memberAction, Func<TMethodMock> methodMockFactory)684 where TMethodMock : IMethodMock685 {686 using (this.sharedContext.StartArrange())687 {688 var result = methodMockFactory();689 CheckDefferedExecutionTypes(methodMockFactory);690 result.Repository = this;691 result.CallPattern = CallPatternCreator.FromAction(this, memberAction);692 AddArrange(result);693 return result;694 }695 }696 [ArrangeMethod]697 internal TMethodMock Arrange<TMethodMock>(object instance, MethodBase method, object[] arguments, Func<TMethodMock> methodMockFactory)698 where TMethodMock : IMethodMock699 {700 using (this.sharedContext.StartArrange())701 {702 var result = methodMockFactory();703 result.Repository = this;704 result.CallPattern = CallPatternCreator.FromMethodBase(this, instance, method, arguments);705 AddArrange(result);706 return result;707 }708 }709 [ArrangeMethod]710 internal TMethodMock Arrange<TMethodMock>(CallPattern callPattern, Func<TMethodMock> methodMockFactory)711 where TMethodMock : IMethodMock712 {713 using (this.sharedContext.StartArrange())714 {715 var result = methodMockFactory();716 result.Repository = this;717 result.CallPattern = callPattern;718 AddArrange(result);719 return result;720 }721 }722 private void AssertBehaviorsForMocks(IEnumerable<IMethodMock> mocks, bool ignoreMethodMockOccurrences)723 {724 foreach (var methodMock in mocks)725 {726 bool occurrenceAsserted = ignoreMethodMockOccurrences;727 if (!ignoreMethodMockOccurrences728 && !methodMock.OccurencesBehavior.LowerBound.HasValue729 && !methodMock.OccurencesBehavior.UpperBound.HasValue)730 {731 methodMock.OccurencesBehavior.Assert(1, null);732 occurrenceAsserted = true;733 }734 foreach (var behavior in methodMock.Behaviors.OfType<IAssertableBehavior>())735 if (!occurrenceAsserted || behavior != methodMock.OccurencesBehavior)736 behavior.Assert();737 }738 }739 internal void AssertAll(string message, object mock)740 {741 using (MockingContext.BeginFailureAggregation(message))742 {743 var mocks = GetMethodMocksFromObject(mock);744 AssertBehaviorsForMocks(mocks.Select(m => m.MethodMock), false);745 }746 }747 internal void AssertAll(string message)748 {749 using (MockingContext.BeginFailureAggregation(message))750 {751 var mocks = GetAllMethodMocks();752 AssertBehaviorsForMocks(mocks.Select(m => m.MethodMock), false);753 }754 }755 internal void Assert(string message, object mock, Expression expr = null, Args args = null, Occurs occurs = null)756 {757 using (MockingContext.BeginFailureAggregation(message))758 {759 if (expr == null)760 {761 List<IMethodMock> mocks = new List<IMethodMock>();762 mocks.AddRange(GetMethodMocksFromObject(mock).Select(m => m.MethodMock));763 foreach (var methodMock in mocks)764 {765 foreach (var behavior in methodMock.Behaviors.OfType<IAssertableBehavior>())766 behavior.Assert();767 }768 MockingUtil.UnwrapDelegateTarget(ref mock);769 var mockMixin = GetMockMixin(mock, null);770 if (mockMixin != null)771 {772 foreach (var behavior in mockMixin.FallbackBehaviors.OfType<IAssertableBehavior>()773 .Concat(mockMixin.SupplementaryBehaviors.OfType<IAssertableBehavior>()))774 behavior.Assert();775 }776 }777 else778 {779 CallPattern callPattern = CallPatternCreator.FromExpression(this, expr);780 AssertForCallPattern(callPattern, args, occurs);781 }782 }783 }784 internal void AssertAction(string message, Action memberAction, Args args = null, Occurs occurs = null)785 {786 using (MockingContext.BeginFailureAggregation(message))787 {788 CallPattern callPattern = CallPatternCreator.FromAction(this, memberAction);789 AssertForCallPattern(callPattern, args, occurs);790 }791 }792 internal void AssertSetAction(string message, Action memberAction, Args args = null, Occurs occurs = null)793 {794 using (MockingContext.BeginFailureAggregation(message))795 {796 using (this.sharedContext.StartAssertSet())797 {798 CallPattern callPattern = CallPatternCreator.FromAction(this, memberAction, true);799 AssertForCallPattern(callPattern, args, occurs);800 }801 }802 }803 internal void AssertMethodInfo(string message, object instance, MethodBase method, object[] arguments, Occurs occurs)804 {805 using (MockingContext.BeginFailureAggregation(message))806 {807 CallPattern callPattern = CallPatternCreator.FromMethodBase(instance, method, arguments);808 AssertForCallPattern(callPattern, null, occurs);809 }810 }811 internal void AssertIgnoreInstance(string message, Type type, bool ignoreMethodMockOccurrences)812 {813 using (MockingContext.BeginFailureAggregation(message))814 {815 var methodMocks = GetMethodMocksFromObject(null, type);816 AssertBehaviorsForMocks(methodMocks.Select(m => m.MethodMock), ignoreMethodMockOccurrences);817 }818 }819 internal int GetTimesCalled(Expression expression, Args args)820 {821 CallPattern callPattern = CallPatternCreator.FromExpression(this, expression);822 int callsCount;823 CountMethodMockInvocations(callPattern, args, out callsCount);824 return callsCount;825 }826 internal int GetTimesCalledFromAction(Action action, Args args)827 {828 var callPattern = CallPatternCreator.FromAction(this, action);829 int callsCount;830 CountMethodMockInvocations(callPattern, args, out callsCount);831 return callsCount;832 }833 internal int GetTimesCalledFromMethodInfo(object instance, MethodBase method, object[] arguments)834 {835 var callPattern = CallPatternCreator.FromMethodBase(instance, method, arguments);836 int callsCount;837 CountMethodMockInvocations(callPattern, null, out callsCount);838 return callsCount;839 }840 private HashSet<IMethodMock> CountMethodMockInvocations(CallPattern callPattern, Args args, out int callsCount)841 {842 if (callPattern.IsDerivedFromObjectEquals)843 throw new MockException("Cannot assert calls to methods derived from Object.Equals");844 PreserveRefOutValuesBehavior.ReplaceRefOutArgsWithAnyMatcher(callPattern);845 if (args != null)846 {847 if (args.Filter != null)848 {849 if (args.IsIgnored == null)850 {851 args.IsIgnored = true;852 }853 if (!callPattern.Method.IsStatic854 && args.IsInstanceIgnored == null855 && args.Filter.Method.GetParameters().Length == callPattern.Method.GetParameters().Length + 1)856 {857 args.IsInstanceIgnored = true;858 }859 }860 if (args.IsIgnored == true)861 {862 for (int i = 0; i < callPattern.ArgumentMatchers.Count; i++)863 callPattern.ArgumentMatchers[i] = new AnyMatcher();864 }865 if (args.IsInstanceIgnored == true)866 {867 callPattern.InstanceMatcher = new AnyMatcher();868 }869 callPattern.Filter = args.Filter;870 }871 MethodInfoMatcherTreeNode root;872 callsCount = 0;873 var mocks = new HashSet<IMethodMock>();874 var method = callPattern.Method;875 if (invocationTreeRoots.TryGetValue(method, out root))876 {877 var occurences = root.GetOccurences(callPattern);878 callsCount = occurences.Select(x => x.Calls).Sum();879 foreach (var mock in occurences.SelectMany(x => x.Mocks))880 {881 mocks.Add(mock);882 }883 }884 return mocks;885 }886 private void AssertForCallPattern(CallPattern callPattern, Args args, Occurs occurs)887 {888 int callsCount;889 var mocks = CountMethodMockInvocations(callPattern, args, out callsCount);890 if (occurs != null)891 {892 InvocationOccurrenceBehavior.Assert(occurs.LowerBound, occurs.UpperBound, callsCount, null, null);893 }894 if (mocks.Count == 0)895 {896 MethodInfoMatcherTreeNode funcRoot;897 if (arrangementTreeRoots.TryGetValue(callPattern.Method, out funcRoot))898 {899 var arranges = funcRoot.GetAllMethodMocks(callPattern);900 foreach (var arrange in arranges)901 {902 mocks.Add(arrange.MethodMock);903 }904 }905 }906 if (occurs == null && mocks.Count == 0)907 {908 InvocationOccurrenceBehavior.Assert(Occurs.AtLeastOnce().LowerBound, Occurs.AtLeastOnce().UpperBound, callsCount, null, null);909 }910 else911 {912 AssertBehaviorsForMocks(mocks, occurs != null);913 }914 }915 internal MethodBase GetMethodFromCallPattern(CallPattern callPattern)916 {917 var method = callPattern.Method as MethodInfo;918 if (method == null || !method.IsVirtual)919 return callPattern.Method;920 method = method.NormalizeComInterfaceMethod();921 var valueMatcher = callPattern.InstanceMatcher as IValueMatcher;922 if (valueMatcher != null && valueMatcher.Value != null)923 {924 var valueType = valueMatcher.Value.GetType();925 var mockMixin = GetMockMixin(valueMatcher.Value, null);926 var type = mockMixin != null ? mockMixin.DeclaringType : valueType;927 if (!type.IsInterface && method.DeclaringType.IsAssignableFrom(type))928 {929 var concreteMethod = MockingUtil.GetConcreteImplementer(method, type);930 if (!concreteMethod.IsInheritable() && !ProfilerInterceptor.IsProfilerAttached)931 {932 var reimplementedInterfaceMethod = (MethodInfo)method.GetInheritanceChain().Last();933 if (reimplementedInterfaceMethod.DeclaringType.IsInterface934 && mockFactory.IsAccessible(reimplementedInterfaceMethod.DeclaringType))935 {936 concreteMethod = reimplementedInterfaceMethod;937 }938 }939 method = concreteMethod;940 }941 }942 if (method.DeclaringType != method.ReflectedType)943 method = (MethodInfo)MethodBase.GetMethodFromHandle(method.MethodHandle, method.DeclaringType.TypeHandle);944 return method;945 }946 /// <summary>947 /// Converts the given object to a matcher as follows. This method is most useful for948 /// creating a matcher out of an argument expression.949 /// 950 /// It works as follows:951 /// If the object is not an expression, then a value matcher for that object is returned.952 /// If the object is an expression then:953 /// * if the top of the expression is a method call expression and the member954 /// has the ArgMatcherAttribute then the specific matcher type is instantiaded955 /// with the parameters passed to the method call expression and returned.956 /// If the matcher type is generic, then it is defined with the type of the expression.957 /// * if the top expression is a member or method call and the member958 /// has the ArgIgnoreAttribute, then a TypeMatcher is returned959 /// * otherwise, the expression is evaluated and a ValueMatcher is returned960 /// </summary>961 /// <param name="argumentObj"></param>962 /// <returns></returns>963 internal static IMatcher CreateMatcherForArgument(object argumentObj)964 {965 var argExpr = argumentObj as Expression;966 if (argExpr == null)967 {968 return new ValueMatcher(argumentObj);969 }970 else971 {972 var argMatcher = TryCreateMatcherFromArgMember(argExpr);973 if (argMatcher != null)974 {975 return argMatcher;976 }977 else978 {979 //no matcher, evaluate the original expression980 var argValue = argExpr.EvaluateExpression();981 return new ValueMatcher(argValue);982 }983 }984 }985 internal static IMatcher TryCreateMatcherFromArgMember(Expression argExpr)986 {987 // The expression may end with a conversion which erases the type of the required matcher.988 // Remove the conversion before working with matchers989 while (argExpr.NodeType == ExpressionType.Convert)990 argExpr = ((UnaryExpression)argExpr).Operand;991 ArgMatcherAttribute argAttribute = null;992 Expression[] matcherArguments = null;993 if (argExpr is MethodCallExpression)994 {995 var methodCall = (MethodCallExpression)argExpr;996 argAttribute = (ArgMatcherAttribute)Attribute.GetCustomAttribute(methodCall.Method, typeof(ArgMatcherAttribute));997 matcherArguments = methodCall.Arguments.ToArray();998 }999 else if (argExpr is MemberExpression)1000 {1001 var memberExpr = (MemberExpression)argExpr;1002 argAttribute = (ArgMatcherAttribute)Attribute.GetCustomAttribute(memberExpr.Member, typeof(ArgMatcherAttribute));1003 }1004 if (argAttribute != null)1005 {1006 if (argAttribute.GetType() == typeof(ArgIgnoreAttribute))1007 {1008 return new TypeMatcher(argExpr.Type);1009 }1010 else if (argAttribute.GetType() == typeof(ArgIgnoreTypeAttribute))1011 {1012 var func = Expression.Lambda(argExpr).Compile();1013 var funcResult = func.DynamicInvoke();1014 return new TypeMatcher(funcResult.GetType());1015 }1016 else if (argAttribute.GetType() == typeof(RefArgAttribute) || argAttribute.GetType() == typeof(OutArgAttribute))1017 {1018 var asMemberExpr = argExpr as MemberExpression;1019 if (asMemberExpr != null)1020 {1021 argExpr = asMemberExpr.Expression;1022 }1023 var refCall = (MethodCallExpression)argExpr;1024 var actualArg = refCall.Arguments[0];1025 var memberExpr = actualArg as MemberExpression;1026 if (memberExpr != null && typeof(Expression).IsAssignableFrom(memberExpr.Type) && memberExpr.Expression.Type.DeclaringType == typeof(ArgExpr))1027 {1028 actualArg = (Expression)actualArg.EvaluateExpression();1029 }1030 var argMatcher = CreateMatcherForArgument(actualArg);1031 argMatcher.ProtectRefOut = argAttribute.GetType() == typeof(RefArgAttribute);1032 return argMatcher;1033 }1034 else1035 {1036 var matcherType = argAttribute.Matcher;1037 var matcherArgs = argAttribute.MatcherArgs;1038 if (matcherType.IsGenericTypeDefinition)1039 matcherType = matcherType.MakeGenericType(argExpr.Type);1040 if (matcherArgs == null && matcherArguments != null)1041 matcherArgs = matcherArguments.Select(matcherArgExpr => matcherArgExpr.EvaluateExpression()).ToArray();1042 var matcher = (IMatcher)MockingUtil.CreateInstance(matcherType, matcherArgs);1043 return matcher;1044 }1045 }1046 else1047 {1048 return null;1049 }1050 }1051 private void AddArrange(IMethodMock methodMock)1052 {1053 var method = methodMock.CallPattern.Method;1054 if (methodMock.CallPattern.IsDerivedFromObjectEquals && method.ReflectedType.IsValueType())1055 throw new MockException("Cannot mock Equals method because JustMock depends on it. Also, when Equals is called internally by JustMock, all methods called by it will not be intercepted and will have only their original implementations called.");1056 CheckMethodInterceptorAvailable(methodMock.CallPattern.InstanceMatcher, method);1057 Type declaringType = method.DeclaringType;1058 // If we're arranging a call to a mock object, overwrite its repository.1059 // This will ensure correct behavior when a mock object is arranged1060 // in multiple contexts.1061 var refMatcher = methodMock.CallPattern.InstanceMatcher as ReferenceMatcher;1062 if (refMatcher != null)1063 {1064 var value = refMatcher.Value;1065 var mock = GetMockMixin(value, declaringType);1066 if (mock != null)1067 {1068 methodMock.Mock = mock;1069 mock.Repository = this;...
CallPattern.cs
Source:CallPattern.cs
...19namespace Telerik.JustMock.Core20{21 internal class CallPattern22 {23 internal static readonly MethodInfo ObjectEqualsMethod = typeof(object).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);24 internal static readonly HashSet<MethodBase> uninterceptedMethods = new HashSet<MethodBase>25 {26 typeof(object).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static),27 typeof(object).GetMethod("ReferenceEquals", BindingFlags.Public | BindingFlags.Static),28 typeof(object).GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance),29 };30 public MethodMockMatcherTreeNode MethodMockNode;31 public IMatcher InstanceMatcher;32 public List<IMatcher> ArgumentMatchers = new List<IMatcher>();33 public Delegate Filter;34 private MethodBase method;35 public MethodBase Method36 {37 get38 {39 return this.method;40 }41 }42 public void SetMethod(MethodBase method, bool checkCompatibility)43 {44 if (checkCompatibility)45 {46 if (method == typeof(object).GetConstructor(MockingUtil.EmptyTypes))47 DebugView.TraceEvent(Diagnostics.IndentLevel.Warning, () => "System.Object constructor will be intercepted only in 'new' expressions, i.e. 'new object()'.");48 CheckMethodCompatibility(method);49 CheckInstrumentationAvailability(method);50 }51 this.method = method;52 }53 public static void CheckMethodCompatibility(MethodBase method)54 {55 var sigTypes = method.GetParameters().Select(p => p.ParameterType).Concat(new[] { method.GetReturnType() });56 if (sigTypes.Any(sigType =>57 {58 while (sigType.IsByRef || sigType.IsArray)59 sigType = sigType.GetElementType();60 return sigType == typeof(TypedReference);61 }))62 throw new MockException("Mocking methods with TypedReference in their signature is not supported.");63#if PORTABLE64 if (method.GetReturnType().IsByRef)65 throw new MockException("Cannot mock method with by-ref return value.");66#endif67 if (method.CallingConvention == CallingConventions.VarArgs)68 throw new MockException("Cannot mock method with __arglist.");69 }70 private static bool IsInterceptedAtTheCallSite(MethodBase method)71 {72 return method.IsConstructor;73 }74 public static void CheckInstrumentationAvailability(MethodBase value)75 {76 if (IsInterceptedAtTheCallSite(value))77 {78 return;79 }80#if !PORTABLE81 var methodImpl = value.GetMethodImplementationFlags();82 if ((((methodImpl & MethodImplAttributes.InternalCall) != 083 || (methodImpl & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL)84 && value.Module.Assembly == typeof(object).Assembly)85 && !value.IsInheritable())86 throw new MockException("Cannot mock a method that is implemented internally by the CLR.");87#endif88 if (!value.IsInheritable() && !ProfilerInterceptor.TypeSupportsInstrumentation(value.DeclaringType))89 throw new MockException(String.Format("Cannot mock non-inheritable member '{0}' on type '{1}' due to CLR limitations.", value, value.DeclaringType));90 if ((value.Attributes & MethodAttributes.PinvokeImpl) != 0)91 {92 if (!ProfilerInterceptor.IsProfilerAttached)93 throw new MockException("The profiler must be enabled to mock DllImport methods.");94 string fullName = value.DeclaringType.FullName + "." + value.Name;95 if ((value.Attributes & MethodAttributes.HasSecurity) != 0)96 throw new MockException(string.Format("DllImport method {0} cannot be mocked because it has security information attached.", fullName));97 // method could be the profiler generated shadow method or is inside an assembly which doesn't contain managed code (valid RVA)98 throw new MockException(string.Format("DllImport method {0} cannot be mocked due to internal limitation.", fullName));99 }100 if (uninterceptedMethods.Contains(value))101 throw new MockException("Cannot mock Object..ctor, Object.Equals, Object.ReferenceEquals or Finalize");102 var asMethodInfo = value as MethodInfo;103 if (asMethodInfo != null)104 {105 if (uninterceptedMethods.Contains(asMethodInfo.GetBaseDefinition()))106 throw new MockException("Cannot mock Object.Equals, Object.ReferenceEquals or Finalize");107 }108 }109 public bool IsDerivedFromObjectEquals110 {111 get112 {113 var asMethodInfo = this.Method as MethodInfo;114 return asMethodInfo != null && asMethodInfo.GetBaseDefinition() == ObjectEqualsMethod;115 }116 }117 internal CallPattern Clone()118 {119 var newCallPattern = new CallPattern();120 newCallPattern.method = this.method;121 newCallPattern.InstanceMatcher = this.InstanceMatcher;122 for (int i = 0; i < this.ArgumentMatchers.Count; i++)123 {124 newCallPattern.ArgumentMatchers.Add(this.ArgumentMatchers[i]);125 }126 return newCallPattern;127 }128 internal static CallPattern CreateUniversalCallPattern(MethodBase method)...
AnyMatcher.cs
Source:AnyMatcher.cs
...29 protected override bool MatchesCore(IMatcher other)30 {31 return true;32 }33 public override bool Equals(IMatcher other)34 {35 return other is AnyMatcher;36 }37 public override Expression ToExpression(Type argumentType)38 {39 return Expression.Call(null, typeof(AnyMatcher).GetMethod("Create").MakeGenericMethod(argumentType));40 }41 [ArgMatcher(Matcher = typeof(AnyMatcher))]42 public static T Create<T>()43 {44 throw new NotSupportedException();45 }46 }47}...
Equals
Using AI Code Generation
1{2 public static AnyMatcher<T> Equals<T>(T value)3 {4 return new AnyMatcher<T>(value);5 }6}7{8 public AnyMatcher(T value)9 {10 this.Value = value;11 }12 public T Value { get; set; }13}14{15 public AnyMatcher(T value)16 {17 this.Value = value;18 }19 public T Value { get; set; }20 public bool Matches(object value)21 {22 return value == null || this.Value.Equals(value);23 }24 public override string ToString()25 {26 return string.Format("Any<{0}>", typeof(T).Name);27 }28}29{30 bool Matches(object value);31}32{33 public AnyMatcher(T value)34 {35 this.Value = value;36 }37 public T Value { get; set; }38 public bool Matches(object value)39 {40 return value == null || this.Value.Equals(value);41 }42 public override string ToString()43 {44 return string.Format("Any<{0}>", typeof(T).Name);45 }46}47{48 public AnyMatcher(T value)49 {50 this.Value = value;51 }52 public T Value { get; set; }53 public bool Matches(object value)54 {55 return value == null || this.Value.Equals(value);56 }57 public override string ToString()58 {59 return string.Format("Any<{0}>", typeof(T).Name);60 }61}
Equals
Using AI Code Generation
1using System;2using System.Collections.Generic;3using Telerik.JustMock;4using Telerik.JustMock.Core.MatcherTree;5{6 static void Main()7 {8 var mock = Mock.Create<IFoo>();9 var anyMatcher = new AnyMatcher();10 Mock.Arrange(() => mock.Bar(Arg.Matches<int>(anyMatcher))).Returns(1);11 Console.WriteLine(mock.Bar(1));12 }13}14using System;15using System.Collections.Generic;16using Telerik.JustMock;17using Telerik.JustMock.Core.MatcherTree;18{19 static void Main()20 {21 var mock = Mock.Create<IFoo>();22 var anyMatcher = new AnyMatcher();23 Mock.Arrange(() => mock.Bar(Arg.Matches<int>(anyMatcher))).Returns(1);24 Console.WriteLine(mock.Bar(2));25 }26}27using System;28using System.Collections.Generic;29using Telerik.JustMock;30using Telerik.JustMock.Core.MatcherTree;31{32 static void Main()33 {34 var mock = Mock.Create<IFoo>();35 var anyMatcher = new AnyMatcher();36 Mock.Arrange(() => mock.Bar(Arg.Matches<int>(anyMatcher))).Returns(1);37 Console.WriteLine(mock.Bar(3));38 }39}40using System;41using System.Collections.Generic;42using Telerik.JustMock;43using Telerik.JustMock.Core.MatcherTree;44{45 static void Main()46 {47 var mock = Mock.Create<IFoo>();48 var anyMatcher = new AnyMatcher();49 Mock.Arrange(() => mock.Bar(Arg.Matches<int>(anyMatcher))).Returns(1);50 Console.WriteLine(mock.Bar(4));51 }52}53using System;54using System.Collections.Generic;55using Telerik.JustMock;56using Telerik.JustMock.Core.MatcherTree;57{58 static void Main()59 {60 var mock = Mock.Create<IFoo>();61 var anyMatcher = new AnyMatcher();
Equals
Using AI Code Generation
1var mock = Mock.Create<IFoo>();2Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");3Assert.AreEqual("hello", mock.Echo("world"));4var mock = Mock.Create<IFoo>();5Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");6Assert.AreEqual("hello", mock.Echo("world"));7var mock = Mock.Create<IFoo>();8Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");9Assert.AreEqual("hello", mock.Echo("world"));10var mock = Mock.Create<IFoo>();11Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");12Assert.AreEqual("hello", mock.Echo("world"));13var mock = Mock.Create<IFoo>();14Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");15Assert.AreEqual("hello", mock.Echo("world"));16var mock = Mock.Create<IFoo>();17Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");18Assert.AreEqual("hello", mock.Echo("world"));19var mock = Mock.Create<IFoo>();20Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");21Assert.AreEqual("hello", mock.Echo("world"));22var mock = Mock.Create<IFoo>();23Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");24Assert.AreEqual("hello", mock.Echo("world"));25var mock = Mock.Create<IFoo>();26Mock.Arrange(() => mock.Echo(Arg.IsAny<string>())).Returns("hello");27Assert.AreEqual("hello", mock.Echo("world"));
Equals
Using AI Code Generation
1var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;2Assert.IsTrue(matcher.Equals(matcher));3Assert.IsFalse(matcher.Equals(null));4Assert.IsFalse(matcher.Equals(""));5Assert.IsFalse(matcher.Equals(new Telerik.JustMock.Core.MatcherTree.AnyMatcher()));6var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;7Assert.IsTrue(matcher.Equals(matcher));8Assert.IsFalse(matcher.Equals(null));9Assert.IsFalse(matcher.Equals(""));10Assert.IsFalse(matcher.Equals(new Telerik.JustMock.Core.MatcherTree.AnyMatcher()));11var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;12Assert.IsTrue(matcher.Equals(matcher));13Assert.IsFalse(matcher.Equals(null));14Assert.IsFalse(matcher.Equals(""));15Assert.IsFalse(matcher.Equals(new Telerik.JustMock.Core.MatcherTree.AnyMatcher()));16var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;17Assert.IsTrue(matcher.Equals(matcher));18Assert.IsFalse(matcher.Equals(null));19Assert.IsFalse(matcher.Equals(""));20Assert.IsFalse(matcher.Equals(new Telerik.JustMock.Core.MatcherTree.AnyMatcher()));21var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;22Assert.IsTrue(matcher.Equals(matcher));23Assert.IsFalse(matcher.Equals(null));24Assert.IsFalse(matcher.Equals(""));25Assert.IsFalse(matcher.Equals(new Telerik.JustMock.Core.MatcherTree.AnyMatcher()));26var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;27Assert.IsTrue(matcher.Equals(matcher));28Assert.IsFalse(matcher.Equals(null));29Assert.IsFalse(matcher.Equals(""));30Assert.IsFalse(matcher.Equals(new Telerik.JustMock.Core.MatcherTree.AnyMatcher()));31var matcher = Telerik.JustMock.Core.MatcherTree.AnyMatcher.Instance;32Assert.IsTrue(matcher.Equals(matcher));33Assert.IsFalse(matcher.Equals(null));34Assert.IsFalse(matcher.Equals(""));
Equals
Using AI Code Generation
1var mock = Mock.Create<ISomeInterface>();2Mock.Arrange(() => mock.SomeMethod(Arg.AnyString)).Returns("some value");3var result = mock.SomeMethod("some value");4Assert.AreEqual("some value", result);5var mock = Mock.Create<ISomeInterface>();6Mock.Arrange(() => mock.SomeMethod(Arg.AnyString)).Returns("some value");7var result = mock.SomeMethod("some value");8Assert.AreEqual("some value", result);9Telerik.JustMock.Core.MatcherTree (in Telerik.JustMock.Core.dll) Version: 2019.2.619.1 (2019.2.619.1)
Equals
Using AI Code Generation
1var mock = Mock.Create<IFoo>();2Mock.Arrange(() => mock.Bar(Arg.AnyString)).Returns(1);3var result = mock.Bar("test");4Assert.AreEqual(1, result);5Assert.AreEqual(1, mock.Bar("test"));6Assert.AreEqual(1, mock.Bar("test2"));7var mock = Mock.Create<IFoo>();8Mock.Arrange(() => mock.Bar(Arg.AnyString)).Returns(1);9var result = mock.Bar("test");10Assert.AreEqual(1, result);11Assert.AreEqual(1, mock.Bar("test"));12Assert.AreEqual(1, mock.Bar("test2"));13var mock = Mock.Create<IFoo>();14Mock.Arrange(() => mock.Bar(Arg.AnyString)).Returns(1);15var result = mock.Bar("test");16Assert.AreEqual(1, result);17Assert.AreEqual(1, mock.Bar("test"));18Assert.AreEqual(1, mock.Bar("test2"));19var mock = Mock.Create<IFoo>();20Mock.Arrange(() => mock.Bar(Arg.AnyString)).Returns(1);21var result = mock.Bar("test");22Assert.AreEqual(1, result);23Assert.AreEqual(1, mock.Bar("test"));24Assert.AreEqual(1, mock.Bar("test2"));25var mock = Mock.Create<IFoo>();26Mock.Arrange(() => mock.Bar(Arg.AnyString)).Returns(1);27var result = mock.Bar("test");28Assert.AreEqual(1, result);29Assert.AreEqual(1, mock.Bar("test"));30Assert.AreEqual(1, mock.Bar("test2"));
Equals
Using AI Code Generation
1{2 {3 public void Method1(string s)4 {5 var mock = Mock.Create<TestClass>();6 Mock.Arrange(() => mock.Method1(Arg.AnyString)).OccursOnce();7 mock.Method1("a");8 Mock.Assert(mock);9 }10 }11 {12 public virtual void Method1(string s)13 {14 }15 }16}
Equals
Using AI Code Generation
1var mock = Mock.Create<IService>();2Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");3var result = mock.Get("World");4Assert.AreEqual("Hello", result);5var mock = Mock.Create<IService>();6Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");7var result = mock.Get("World");8Assert.AreEqual("Hello", result);9var mock = Mock.Create<IService>();10Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");11var result = mock.Get("World");12Assert.AreEqual("Hello", result);13var mock = Mock.Create<IService>();14Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");15var result = mock.Get("World");16Assert.AreEqual("Hello", result);17var mock = Mock.Create<IService>();18Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");19var result = mock.Get("World");20Assert.AreEqual("Hello", result);21var mock = Mock.Create<IService>();22Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");23var result = mock.Get("World");24Assert.AreEqual("Hello", result);25var mock = Mock.Create<IService>();26Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");27var result = mock.Get("World");28Assert.AreEqual("Hello", result);29var mock = Mock.Create<IService>();30Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");31var result = mock.Get("World");32Assert.AreEqual("Hello", result);33var mock = Mock.Create<IService>();34Mock.Arrange(() => mock.Get(Arg.AnyString)).Returns("Hello");35var result = mock.Get("World");36Assert.AreEqual("Hello", result);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!