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

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

MocksRepository.cs

Source:MocksRepository.cs Github

copy

Full Screen

...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;1070 }1071 if (value != null)1072 EnableInterception(value.GetType());1073 }1074 EnableInterception(declaringType);1075 PreserveRefOutValuesBehavior.Attach(methodMock);1076 ConstructorMockBehavior.Attach(methodMock);1077 MethodInfoMatcherTreeNode funcRoot;1078 if (!arrangementTreeRoots.TryGetValue(method, out funcRoot))1079 {1080 funcRoot = new MethodInfoMatcherTreeNode(method);1081 arrangementTreeRoots.Add(method, funcRoot);1082 }1083 funcRoot.AddChild(methodMock.CallPattern, methodMock, this.sharedContext.GetNextArrangeId());1084#if !PORTABLE1085 if (ProfilerInterceptor.IsReJitEnabled)1086 {1087 CallPattern.CheckMethodCompatibility(method);1088 CallPattern.CheckInstrumentationAvailability(method);1089 ProfilerInterceptor.RequestReJit(method);...

Full Screen

Full Screen

PreserveRefOutValuesBehavior.cs

Source:PreserveRefOutValuesBehavior.cs Github

copy

Full Screen

...17using System.Reflection;18using Telerik.JustMock.Core.MatcherTree;19namespace Telerik.JustMock.Core.Behaviors20{21 internal class PreserveRefOutValuesBehavior : IBehavior22 {23 private readonly Dictionary<int, object> values = new Dictionary<int, object>();24 public PreserveRefOutValuesBehavior(IMethodMock methodMock)25 {26 var argMatchers = methodMock.CallPattern.ArgumentMatchers;27 var method = methodMock.CallPattern.Method;28 var parameters = GetParameters(method);29 var offsetDueToExtensionMethod = method.IsExtensionMethod() ? 1 : 0;30 for (int i = 0; i < parameters.Length; ++i)31 {32 if (!parameters[i].ParameterType.IsByRef || argMatchers[i].ProtectRefOut)33 continue;34 var matcher = argMatchers[i] as IValueMatcher;35 if (matcher == null)36 continue;37 var value = matcher.Value;38 values.Add(i + offsetDueToExtensionMethod, value);39 }40 }41 public void Process(Invocation invocation)42 {43 foreach (var kvp in this.values)44 {45 invocation.Args[kvp.Key] = kvp.Value;46 }47 }48 public static void Attach(IMethodMock methodMock)49 {50 var behavior = new PreserveRefOutValuesBehavior(methodMock);51 var madeReplacements = ReplaceRefOutArgsWithAnyMatcher(methodMock.CallPattern);52 if (madeReplacements)53 methodMock.Behaviors.Add(behavior);54 }55 public static bool ReplaceRefOutArgsWithAnyMatcher(CallPattern callPattern)56 {57 bool madeReplacements = false;58 var parameters = GetParameters(callPattern.Method);59 for (int i = 0; i < parameters.Length; ++i)60 {61 if (parameters[i].ParameterType.IsByRef && !callPattern.ArgumentMatchers[i].ProtectRefOut)62 {63 callPattern.ArgumentMatchers[i] = new AnyMatcher();64 madeReplacements = true;...

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock.Core;2using Telerik.JustMock.Core.Behaviors;3using Telerik.JustMock.Helpers;4{5 {6 public static void Main(string[] args)7 {8 var mock = Mock.Create<IFoo>();9 int value = 0;10 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out value)).Returns(true).DoInstead((int i, out int v) => v = i + 1).PreserveRefOutValues();11 bool result = mock.DoSomething(1, out value);12 Console.WriteLine(result);13 Console.WriteLine(value);14 }15 }16 {17 bool DoSomething(int i, out int v);18 }19}

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock.Core.Behaviors;2using Telerik.JustMock;3public void TestMethod1()4{5 var mock = Mock.Create<IFoo>();6 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out Arg.Ref<int>.IsAny)).DoNothing().MustBeCalled();7 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out Arg.Ref<int>.IsAny)).DoNothing().MustBeCalled().SetBehavior(PreserveRefOutValuesBehavior.Instance);8 int value = 0;9 mock.DoSomething(1, out value);10 Assert.AreEqual(1, value);11}

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock;2using Telerik.JustMock.Core.Behaviors;3{4 {5 public int Method1(int x, out int y)6 {7 y = 0;8 return x;9 }10 }11 {12 public int Method1(int x, out int y)13 {14 y = 0;15 return x;16 }17 }18}19using Telerik.JustMock;20using Telerik.JustMock.Core.Behaviors;21{22 {23 public int Method1(int x, out int y)24 {25 y = 0;26 return x;27 }28 }29 {30 public int Method1(int x, out int y)31 {32 y = 0;33 return x;34 }35 }36}37using Telerik.JustMock;38using Telerik.JustMock.Core.Behaviors;39{40 {41 public int Method1(int x, out int y)42 {43 y = 0;44 return x;45 }46 }47 {48 public int Method1(int x, out int y)49 {50 y = 0;51 return x;52 }53 }54}55using Telerik.JustMock;56using Telerik.JustMock.Core.Behaviors;57{58 {59 public int Method1(int x, out int y)60 {61 y = 0;62 return x;63 }64 }65 {66 public int Method1(int x, out int y)67 {68 y = 0;69 return x;70 }71 }72}

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1{2 {3 public static void Main()4 {5 var preserveRefOutValuesBehavior = new PreserveRefOutValuesBehavior();6 var mock = Mock.Create<IFoo>(Behavior.CallOriginal, preserveRefOutValuesBehavior);7 var result = mock.GetResult(1, out var value);8 Mock.Assert(() => mock.GetResult(1, out value), Occurs.Once());9 }10 }11 {12 int GetResult(int value, out int value2);13 }14}15{16 {17 public static void Main()18 {19 var setRefValueBehavior = new SetRefValueBehavior();20 var mock = Mock.Create<IFoo>(Behavior.CallOriginal, setRefValueBehavior);21 var result = mock.GetResult(1, out var value);22 Mock.Assert(() => mock.GetResult(1, out value), Occurs.Once());23 }24 }25 {26 int GetResult(int value, out

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock.Core.Behaviors;2public void TestMethod1()3{4 var mock = Mock.Create<IFoo>();5 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out Arg.Ref(1).Value)).DoInstead((int i, ref int j) => j = 2).MustBeCalled();6 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out Arg.Ref(1).Value)).CallOriginal().WithBehavior(new PreserveRefOutValuesBehavior());7 int j;8 mock.DoSomething(1, out j);9 Assert.AreEqual(2, j);10}11using Telerik.JustMock.Core.Behaviors;12public void TestMethod1()13{14 var mock = Mock.Create<IFoo>();15 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out Arg.Ref(1).Value)).DoInstead((int i, ref int j) => j = 2).MustBeCalled();16 Mock.Arrange(() => mock.DoSomething(Arg.IsAny<int>(), out Arg.Ref(1).Value)).CallOriginal().WithBehavior(new PreserveRefOutValuesBehavior());17 int j;18 mock.DoSomething(1, out j);19 Assert.AreEqual(2, j);20}

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1public void TestMethod1()2{3 var mock = Mock.Create<TestClass>();4 var behavior = new PreserveRefOutValuesBehavior();5 Mock.Arrange(() => mock.Method(Arg.IsAny<int>(), Arg.IsAny<string>(), Arg.IsAny<bool>())).DoInstead((int i, string s, bool b) => { i = 1; s = "a"; b = true; }).DoInstead(behavior);6 mock.Method(0, "b", false);7 Assert.AreEqual(1, behavior.OutValues[0]);8 Assert.AreEqual("a", behavior.OutValues[1]);9 Assert.AreEqual(true, behavior.OutValues[2]);10}11{12 public List<object> OutValues { get; set; }13 public PreserveRefOutValuesBehavior()14 {15 this.OutValues = new List<object>();16 }17 public override void Process(Invocation invocation)18 {19 invocation.Proceed();20 foreach (var arg in invocation.Arguments)21 {22 if (arg is OutArgument)23 {24 OutValues.Add(((OutArgument)arg).Value);25 }26 }27 }28}

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1public void TestMethod1()2{3 var mock = Mock.Create<IFoo>();4 Mock.Arrange(() => mock.Bar(Arg.IsAny<int>(), out Arg.Ref<int>.IsAny))5 .DoInstead((int a, ref int b) => b = a + 1)6 .PreserveRefOutValuesBehavior();7 int value;8 mock.Bar(1, out value);9 Assert.AreEqual(2, value);10}11public void TestMethod1()12{13 var mock = Mock.Create<IFoo>();14 Mock.Arrange(() => mock.Bar(Arg.IsAny<int>(), out Arg.Ref<int>.IsAny))15 .DoInstead((int a, ref int b) => b = a + 1)16 .PreserveRefOutValuesBehavior();17 int value;18 mock.Bar(1, out value);19 Assert.AreEqual(2, value);20}21public void TestMethod1()22{23 var mock = Mock.Create<IFoo>();24 Mock.Arrange(() => mock.Bar(Arg.IsAny<int>(), out Arg.Ref<int>.IsAny))25 .DoInstead((int a, ref int b) => b = a + 1)26 .PreserveRefOutValuesBehavior();27 int value;28 mock.Bar(1, out value);29 Assert.AreEqual(2, value);30}31public void TestMethod1()32{33 var mock = Mock.Create<IFoo>();34 Mock.Arrange(() => mock.Bar(Arg.IsAny<int>(), out Arg.Ref<int>.IsAny))35 .DoInstead((int a, ref int b) => b = a + 1)36 .PreserveRefOutValuesBehavior();37 int value;38 mock.Bar(1, out value);39 Assert.AreEqual(2, value);40}41public void TestMethod1()42{

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock;2using Telerik.JustMock.Core;3using Telerik.JustMock.Helpers;4using Telerik.JustMock.Tests;5using Telerik.JustMock.Tests.Model;6{7 {8 public void Method1()9 {10 var mock = Mock.Create<ITestInterface>();11 Mock.Arrange(() => mock.Method1(Arg.AnyString, out Arg.Ref<string>.Ref("test").Value)).DoNothing();12 string outValue;13 mock.Method1("test", out outValue);14 Assert.AreEqual("test", outValue);15 }16 }17}18using Telerik.JustMock;19using Telerik.JustMock.Core;20using Telerik.JustMock.Helpers;21using Telerik.JustMock.Tests;22using Telerik.JustMock.Tests.Model;23{24 {25 public void Method1()26 {27 var mock = Mock.Create<ITestInterface>();28 Mock.Arrange(() => mock.Method1(Arg.AnyString, out Arg.Ref<string>.Ref("test").Value)).DoNothing();29 string outValue;30 mock.Method1("test", out outValue);31 Assert.AreEqual("test", outValue);32 }33 }34}35using Telerik.JustMock;36using Telerik.JustMock.Core;37using Telerik.JustMock.Helpers;38using Telerik.JustMock.Tests;39using Telerik.JustMock.Tests.Model;40{41 {42 public void Method1()43 {44 var mock = Mock.Create<ITestInterface>();45 Mock.Arrange(() => mock.Method1(Arg.AnyString, out Arg.Ref<string>.Ref("test").Value)).DoNothing();46 string outValue;47 mock.Method1("test", out outValue);48 Assert.AreEqual("test", outValue);49 }50 }51}52using Telerik.JustMock;53using Telerik.JustMock.Core;54using Telerik.JustMock.Helpers;55using Telerik.JustMock.Tests;56using Telerik.JustMock.Tests.Model;

Full Screen

Full Screen

PreserveRefOutValuesBehavior

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock;2using Telerik.JustMock.Core.Behaviors;3{4 {5 public string Method1()6 {7 return "Method1";8 }9 }10}11using Telerik.JustMock;12using Telerik.JustMock.Core.Behaviors;13{14 {15 public string Method2()16 {17 return "Method2";18 }19 }20}21using Telerik.JustMock;22using Telerik.JustMock.Core.Behaviors;23{24 {25 public string Method3()26 {27 return "Method3";28 }29 }30}31using Telerik.JustMock;32using Telerik.JustMock.Core.Behaviors;33{34 {35 public string Method4()36 {37 return "Method4";38 }39 }40}41using Telerik.JustMock;42using Telerik.JustMock.Core.Behaviors;43{44 {45 public string Method5()46 {47 return "Method5";48 }49 }50}51using Telerik.JustMock;52using Telerik.JustMock.Core.Behaviors;53{54 {55 public string Method6()56 {57 return "Method6";58 }59 }60}61using Telerik.JustMock;62using Telerik.JustMock.Core.Behaviors;63{64 {65 public string Method7()

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run JustMockLite automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful