IMethod MakeMethod(params object[] parameterTypesOrDefaultValues) { var context = new SimpleTypeResolveContext(compilation.MainModule); var m = new FakeMethod(compilation, SymbolKind.Method); m.Name = "Method"; var parameters = new List <IParameter>(); foreach (var typeOrDefaultValue in parameterTypesOrDefaultValues) { Type type = typeOrDefaultValue as Type; if (type != null) { parameters.Add(new DefaultParameter(compilation.FindType(type), string.Empty, owner: m)); } else if (Type.GetTypeCode(typeOrDefaultValue.GetType()) > TypeCode.Object) { parameters.Add(new DefaultParameter(compilation.FindType(typeOrDefaultValue.GetType()), string.Empty, owner: m, isOptional: true, defaultValue: typeOrDefaultValue)); } else { throw new ArgumentException(typeOrDefaultValue.ToString()); } } m.Parameters = parameters; return(m); }
public void ShouldThrowExceptionWhenInvocationDoesNotMeetAcceptanceConditionDueToThirdParameter() { var fakeMethod = FakeMethod.CreateFor <int, int, int, int>((p1, p2, p3) => p1 + p2 + p3) .Accept(n => n == 1, n => n == 2, n => n == 3); fakeMethod.Invoke(1, 2, 2); }
public void ShouldKeepTrackOfParametersForConsecutiveInvocations() { var first1 = new object(); var second1 = new object(); var third1 = new object(); var first2 = new object(); var second2 = new object(); var third2 = new object(); var first3 = new object(); var second3 = new object(); var third3 = new object(); var fakeMethod = FakeMethod.CreateFor <object, object, object>((o1, o2, o3) => { }); fakeMethod.Invoke(first1, first2, first3); fakeMethod.Invoke(second1, second2, second3); fakeMethod.Invoke(third1, third2, third3); Assert.AreSame(first1, fakeMethod.Invocations.ElementAt(0).FirstParameter); Assert.AreSame(first2, fakeMethod.Invocations.ElementAt(0).SecondParameter); Assert.AreSame(first3, fakeMethod.Invocations.ElementAt(0).ThirdParameter); Assert.AreSame(second1, fakeMethod.Invocations.ElementAt(1).FirstParameter); Assert.AreSame(second2, fakeMethod.Invocations.ElementAt(1).SecondParameter); Assert.AreSame(second3, fakeMethod.Invocations.ElementAt(1).ThirdParameter); Assert.AreSame(third1, fakeMethod.Invocations.ElementAt(2).FirstParameter); Assert.AreSame(third2, fakeMethod.Invocations.ElementAt(2).SecondParameter); Assert.AreSame(third3, fakeMethod.Invocations.ElementAt(2).ThirdParameter); }
public void ShouldThrowExceptionWhenInvocationDoesNotMeetAcceptedConditionDueToFirstParameter() { var fakeMethod = FakeMethod.CreateFor <int, int, int>((p1, p2) => p1 + p2) .Accept(n => n == 1, n => n == 2); fakeMethod.Invoke(2, 2); }
public void ShouldPassParameterToActionWhenFakeActionIsInvoked() { object o = new object(); var fakeMethod = FakeMethod.CreateFor <object>(p => { }); fakeMethod.Invoke(o); Assert.AreSame(o, fakeMethod.Invocations.First().Parameter); }
public void ShouldReturnValueFromFuncWhenInvoked() { var toReturn = new object(); var fakeMethod = FakeMethod.CreateFor <object, object>(p => toReturn); var returned = fakeMethod.Invoke(null); Assert.AreSame(toReturn, returned); }
public void ShouldReturnObjectReturnedByFuncWhenInvoked() { var toReturn = new object(); var fakeMethod = FakeMethod.CreateFor(() => toReturn); var returned = fakeMethod.Invoke(); Assert.AreSame(toReturn, returned); }
public void ShouldPassParameterToFuncWhenFakeFuncIsInvoked() { var o = new object(); var fakeMethod = FakeMethod.CreateFor <object, object>(p => null); fakeMethod.Invoke(o); Assert.AreSame(o, fakeMethod.Invocations.First().Parameter); }
public void ShouldInvokeProvidedActionWhenFakeActionIsInvoked() { bool actionCalled = false; Action action = () => { actionCalled = true; }; var fakeMethod = FakeMethod.CreateFor(action); fakeMethod.Invoke(); Assert.IsTrue(actionCalled); }
public void ShouldInvokeActionIfAcceptConditionIsMet() { bool invoked = false; var fakeMethod = FakeMethod.CreateFor <int>(p => { invoked = true; }).Accept(n => n == 2); fakeMethod.Invoke(2); Assert.IsTrue(invoked); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); Assert.AreEqual(2, fakeMethod.Invocations.First().Parameter); }
public void ShouldPassParameterToActionWhenFakeActionIsInvoked() { object param1 = new object(); object param2 = new object(); var fakeMethod = FakeMethod.CreateFor <object, object>((o1, o2) => { }); fakeMethod.Invoke(param1, param2); Assert.AreSame(param1, fakeMethod.Invocations.First().FirstParameter); Assert.AreSame(param2, fakeMethod.Invocations.First().SecondParameter); }
public void ShouldInvokeProvidedActionWhenFakeActionIsInvoked() { bool actionCalled = false; Action <object> action = o => { actionCalled = true; }; object ignored = null; var fakeMethod = FakeMethod.CreateFor(action); fakeMethod.Invoke(ignored); Assert.IsTrue(actionCalled); }
public void ShouldIncreaseNumberOfInvocationsWhenFakeFuncIsInvoked() { var fakeMethod = FakeMethod.CreateFor <object>(() => null); fakeMethod.Invoke(); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(); Assert.AreEqual(2, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(); Assert.AreEqual(3, fakeMethod.NumberOfInvocations); }
public void ShouldInvokeFuncWhenFakeFuncIsInvoked() { bool funcInvoked = false; var fakeMethod = FakeMethod.CreateFor <object>(() => { funcInvoked = true; return(null); }); fakeMethod.Invoke(); Assert.IsTrue(funcInvoked); }
public void ShouldInvokeActionIfParametersMeetAcceptanceCondition() { bool actionInvoked = false; var fakeMethod = FakeMethod.CreateFor <int, int>((p1, p2) => { actionInvoked = true; }).Accept(n => n == 1, n => n == 2); fakeMethod.Invoke(1, 2); Assert.IsTrue(actionInvoked); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); Assert.AreEqual(1, fakeMethod.Invocations.First().FirstParameter); Assert.AreEqual(2, fakeMethod.Invocations.First().SecondParameter); }
public void ShouldIncreaseNumberOfInvocationsEachTimeFakeActionIsInvoked() { var fakeMethod = FakeMethod.CreateFor(() => { }); fakeMethod.Invoke(); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(); Assert.AreEqual(2, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(); Assert.AreEqual(3, fakeMethod.NumberOfInvocations); }
public void ShouldIncreaseNumberOfInvocationsEachTimeFakeActionIsInvoked() { object ignored = null; var fakeMethod = FakeMethod.CreateFor <object>(o => { }); fakeMethod.Invoke(ignored); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(ignored); Assert.AreEqual(2, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(ignored); Assert.AreEqual(3, fakeMethod.NumberOfInvocations); }
/// <summary> /// Create a dummy IMethod from the specified MethodReference /// </summary> IMethod CreateFakeMethod(IType declaringType, string name, MethodSignature <IType> signature) { SymbolKind symbolKind = SymbolKind.Method; if (name == ".ctor" || name == ".cctor") { symbolKind = SymbolKind.Constructor; } var m = new FakeMethod(Compilation, symbolKind); m.DeclaringType = declaringType; m.Name = name; m.ReturnType = signature.ReturnType; m.IsStatic = !signature.Header.IsInstance; TypeParameterSubstitution substitution = null; if (signature.GenericParameterCount > 0) { var typeParameters = new List <ITypeParameter>(); for (int i = 0; i < signature.GenericParameterCount; i++) { typeParameters.Add(new DefaultTypeParameter(m, i)); } m.TypeParameters = typeParameters; substitution = new TypeParameterSubstitution(declaringType.TypeArguments, typeParameters); } else if (declaringType.TypeArguments.Count > 0) { substitution = declaringType.GetSubstitution(); } var parameters = new List <IParameter>(); for (int i = 0; i < signature.RequiredParameterCount; i++) { var type = signature.ParameterTypes[i]; if (substitution != null) { // replace the dummy method type parameters with the owned instances we just created type = type.AcceptVisitor(substitution); } parameters.Add(new DefaultParameter(type, "")); } m.Parameters = parameters; GuessFakeMethodAccessor(declaringType, name, signature, m, parameters); return(m); }
public void ShouldKeepTrackOfParametersForConsecutiveInvocations() { var first = new object(); var second = new object(); var third = new object(); var fakeMethod = FakeMethod.CreateFor <object, object>(p => null); fakeMethod.Invoke(first); fakeMethod.Invoke(second); fakeMethod.Invoke(third); Assert.AreSame(first, fakeMethod.Invocations.ElementAt(0).Parameter); Assert.AreSame(second, fakeMethod.Invocations.ElementAt(1).Parameter); Assert.AreSame(third, fakeMethod.Invocations.ElementAt(2).Parameter); }
public void ShouldIncreaseNumberOfInvocationsEachTimeFakeFuncIsInvoked() { Func <object, object> func = o => null; object ignored = null; var fakeMethod = FakeMethod.CreateFor(func); fakeMethod.Invoke(ignored); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(ignored); Assert.AreEqual(2, fakeMethod.NumberOfInvocations); fakeMethod.Invoke(ignored); Assert.AreEqual(3, fakeMethod.NumberOfInvocations); }
public void ShouldInvokeProvidedActionWhenFakeFuncIsInvoked() { bool funcCalled = false; Func <object, object> func = o => { funcCalled = true; return(null); }; object ignored = null; var fakeMethod = FakeMethod.CreateFor(func); fakeMethod.Invoke(ignored); Assert.IsTrue(funcCalled); }
private static ICommonMethod CreateCommonMethod(FakeMethod fakeMethod, string typeFullName, bool canBeNull = false) { if (canBeNull && fakeMethod == null) { return(null); } var methodName = fakeMethod.Name; var methodFullName = $"{typeFullName}::{methodName}({fakeMethod.Parameters?.Select(parameter => parameter.ParameterType.FullName).JoinToString(",")})"; var commonAttributes = CreateCommonAttributes(fakeMethod.Attributes); var commonParameters = CreateCommonParameters(fakeMethod.Parameters); var returnTypeReference = CreateTypeReference(fakeMethod.ReturnType); var monoCecilMethod = CreateMockFor <MethodDefinition>(); monoCecilMethod.Setup(method => method.Name).Returns(() => methodName); monoCecilMethod.Setup(method => method.FullName).Returns(() => methodFullName); monoCecilMethod.Setup(method => method.ReturnType).Returns(() => returnTypeReference); monoCecilMethod.Setup(method => method.CustomAttributes).Returns(() => new Collection <CustomAttribute>(commonAttributes.Select(attribute => attribute.MonoCecil).ToArray())); monoCecilMethod.Setup(method => method.Parameters).Returns(() => new Collection <ParameterDefinition>(commonParameters.Select(parameter => parameter.MonoCecil).ToArray())); var reflectionMethod = CreateMockFor <MethodInfo>(); reflectionMethod.Setup(constructor => constructor.GetCustomAttributes(It.IsAny <bool>())) .Returns(() => fakeMethod.Attributes.Select(attribute => (object)attribute).ToArray()); reflectionMethod.Setup(constructor => constructor.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>())) .Returns((Type type, bool b) => fakeMethod.Attributes.Select(attribute => (object)attribute).Where(attribute => attribute.GetType() == type).ToArray()); var commonMethod = CreateMockFor <ICommonMethod>(); commonMethod.Setup(method => method.Name).Returns(() => methodName); commonMethod.Setup(method => method.FullName).Returns(() => methodFullName); commonMethod.Setup(method => method.MonoCecil).Returns(() => monoCecilMethod.Object); commonMethod.Setup(method => method.Reflection).Returns(() => reflectionMethod.Object); commonMethod.Setup(method => method.Attributes).Returns(() => commonAttributes); commonMethod.Setup(method => method.Parameters).Returns(() => commonParameters); commonMethod.Setup(method => method.ReturnType).Returns(() => fakeMethod.ReturnType.Type); commonMethod.Setup(method => method.ParameterTypes).Returns(() => commonParameters.Select(parameter => parameter.Type).ToArray()); commonMethod.Setup(method => method.Load(It.IsAny <int>())).Returns(() => commonMethod.Object); commonMethod.Setup(method => method.TypeTypeToAttributes).Returns(() => commonAttributes.GroupBy(attribute => attribute.Type).ToDictionary(group => group.Key, group => group.ToArray())); commonMethod.Setup(method => method.TypeFullNameToAttributes).Returns(() => commonAttributes.GroupBy(attribute => attribute.FullName).ToDictionary(group => group.Key, group => group.ToArray())); return(commonMethod.Object); }
/// <summary> /// Selects constructors for the supplied type. /// </summary> /// <param name="type">The type.</param> /// <returns> /// Constructors for <paramref name="type"/>. /// </returns> /// <remarks> /// <para> /// This method returns a sequence of <see cref="StaticMethod"/> according to /// the public and protected constructors available on <paramref name="type"/>. /// </para> /// </remarks> public IEnumerable <IMethod> SelectMethods(Type type) { if (!type.IsFake()) { return(Enumerable.Empty <IMethod>()); } var fakeType = type.GetFakedType(); if (fakeType.IsInterface) { return(new[] { new ConstructorMethod(type.GetDefaultConstructor()) }); } return(from ci in fakeType.GetPublicAndProtectedConstructors() let parameters = ci.GetParameters() orderby parameters.Length ascending select FakeMethod.Create(fakeType, parameters)); }
public void ShouldInvokeFuncIfParametersMeetAcceptanceCondition() { bool actionInvoked = false; var fakeMethod = FakeMethod.CreateFor <int, int, int, int>( (p1, p2, p3) => { actionInvoked = true; return(p1 + p2 + p3); }).Accept(n => n == 1, n => n == 2, n => n == 3); Assert.AreEqual(6, fakeMethod.Invoke(1, 2, 3)); Assert.IsTrue(actionInvoked); Assert.AreEqual(1, fakeMethod.NumberOfInvocations); Assert.AreEqual(1, fakeMethod.Invocations.First().FirstParameter); Assert.AreEqual(2, fakeMethod.Invocations.First().SecondParameter); Assert.AreEqual(3, fakeMethod.Invocations.First().ThirdParameter); }
public static IMethod CreateStaticCtor(ITypeDefinition ce) { var cctor = new FakeMethod(SymbolKind.Constructor) { Name = ".cctor", IsStatic = true, DeclaringTypeDefinition = ce, Region = ce.Region, BodyRegion = ce.BodyRegion, DeclaringType = ce, }; //var cctor = (IMethod)new DefaultUnresolvedMethod //{ // Name = ".cctor", // IsStatic = true, // EntityType = EntityType.Constructor, //}.CreateResolved(ce.ParentAssembly.Compilation.TypeResolveContext.WithCurrentTypeDefinition(ce)); return(cctor); }
/// <summary> /// Selects constructors for the supplied type. /// </summary> /// <param name="type">The type.</param> /// <returns> /// Constructors for <paramref name="type"/>. /// </returns> /// <remarks> /// <para> /// This method returns a sequence of <see cref="StaticMethod"/> according to /// the public and protected constructors available on <paramref name="type"/>. /// </para> /// </remarks> public IEnumerable <IMethod> SelectMethods(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (!type.IsFake()) { return(Enumerable.Empty <IMethod>()); } var fakeType = type.GetFakedType(); if (fakeType.GetTypeInfo().IsInterface || DelegateSpecification.IsSatisfiedBy(fakeType)) { return(new[] { new ConstructorMethod(type.GetDefaultConstructor()) }); } return(from ci in fakeType.GetPublicAndProtectedConstructors() let parameters = ci.GetParameters() orderby parameters.Length ascending select FakeMethod.Create(fakeType, parameters)); }
private static CommonMethod CreateCommonMethod(Mock <CommonType> commonType, FakeMethod fakeMethod) { if (fakeMethod == null) { return(null); } var methodName = fakeMethod.Name; var methodFullName = $"{commonType.Object.FullName}.{methodName}"; var commonParameters = CreateCommonParameters(fakeMethod.Parameters); var commonAttributes = CreateCommonAttributes(fakeMethod.Attributes); var monoCecilMethod = new Mock <MonoCecilMethod>(null); monoCecilMethod.Setup(method => method.Name).Returns(() => methodName); monoCecilMethod.Setup(method => method.FullName).Returns(() => methodFullName); monoCecilMethod.Setup(method => method.Parameters).Returns(() => commonParameters.Select(field => field.MonoCecilParameter)); monoCecilMethod.Setup(method => method.Attributes).Returns(() => commonAttributes.Select(field => field.MonoCecilAttribute)); monoCecilMethod.Setup(method => method.GetParameterByIndex(It.IsAny <int>())).Returns((int index) => commonParameters[index].MonoCecilParameter); var monoCecilMethodBody = new Mock <MonoCecilMethodBody>(null); var monoCecilInstructions = new Mock <MonoCecilInstructions>(null); monoCecilMethodBody.Setup(body => body.Instructions).Returns(() => monoCecilInstructions.Object); monoCecilMethod.Setup(method => method.Body).Returns(() => monoCecilMethodBody.Object); var reflectionMethod = new Mock <ReflectionMethod>(null); reflectionMethod.Setup(method => method.Name).Returns(() => methodName); reflectionMethod.Setup(method => method.FullName).Returns(() => methodFullName); reflectionMethod.Setup(method => method.Parameters).Returns(() => commonParameters.Select(field => field.ReflectionParameter)); reflectionMethod.Setup(method => method.Attributes).Returns(() => commonAttributes.Select(field => field.ReflectionAttribute)); reflectionMethod.Setup(method => method.GetParameterByIndex(It.IsAny <int>())).Returns((int index) => commonParameters[index].ReflectionParameter); return(new Mock <CommonMethod>(commonAttributes, monoCecilMethod.Object, reflectionMethod.Object).Object); }
public FakeCommonTypeBuilder AddMethod(FakeMethod method) { methods.Add(method); return(this); }
public static IMethod CreateStaticCtor(ITypeDefinition ce) { var cctor = new FakeMethod(SymbolKind.Constructor) { Name = ".cctor", IsStatic = true, DeclaringTypeDefinition = ce, Region = ce.Region, BodyRegion = ce.BodyRegion, DeclaringType = ce, }; //var cctor = (IMethod)new DefaultUnresolvedMethod //{ // Name = ".cctor", // IsStatic = true, // EntityType = EntityType.Constructor, //}.CreateResolved(ce.ParentAssembly.Compilation.TypeResolveContext.WithCurrentTypeDefinition(ce)); return cctor; }
public void ShouldThrowExceptionWhenInvocationDoesNotMeetAcceptedConditionValues() { var fakeMethod = FakeMethod.CreateFor <int, int>(p => p).Accept(n => n == 2); fakeMethod.Invoke(3); }
private void GuessFakeMethodAccessor(IType declaringType, string name, MethodSignature <IType> signature, FakeMethod m, List <IParameter> parameters) { if (signature.GenericParameterCount > 0) { return; } var guessedGetter = name.StartsWith("get_", StringComparison.Ordinal); var guessedSetter = name.StartsWith("set_", StringComparison.Ordinal); if (guessedGetter || guessedSetter) { var propertyName = name.Substring(4); var fakeProperty = new FakeProperty(Compilation) { Name = propertyName, DeclaringType = declaringType, IsStatic = m.IsStatic, }; if (guessedGetter) { if (signature.ReturnType.Kind == TypeKind.Void) { return; } m.AccessorKind = MethodSemanticsAttributes.Getter; m.AccessorOwner = fakeProperty; fakeProperty.Getter = m; fakeProperty.ReturnType = signature.ReturnType; fakeProperty.IsIndexer = parameters.Count > 0; fakeProperty.Parameters = parameters; return; } if (guessedSetter) { if (parameters.Count < 1 || signature.ReturnType.Kind != TypeKind.Void) { return; } m.AccessorKind = MethodSemanticsAttributes.Setter; m.AccessorOwner = fakeProperty; fakeProperty.Getter = m; fakeProperty.ReturnType = parameters.Last().Type; fakeProperty.IsIndexer = parameters.Count > 1; fakeProperty.Parameters = parameters.SkipLast(1).ToArray(); return; } } const string addPrefix = "add_"; const string removePrefix = "remove_"; const string raisePrefix = "raise_"; var guessedAdd = name.StartsWith(addPrefix, StringComparison.Ordinal); var guessedRemove = name.StartsWith(removePrefix, StringComparison.Ordinal); var guessedRaise = name.StartsWith(raisePrefix, StringComparison.Ordinal); if (guessedAdd || guessedRemove || guessedRaise) { var fakeEvent = new FakeEvent(Compilation) { DeclaringType = declaringType, IsStatic = m.IsStatic, }; if (guessedAdd) { if (parameters.Count != 1) { return; } m.AccessorKind = MethodSemanticsAttributes.Adder; m.AccessorOwner = fakeEvent; fakeEvent.Name = name.Substring(addPrefix.Length); fakeEvent.AddAccessor = m; fakeEvent.ReturnType = parameters.Single().Type; return; } if (guessedRemove) { if (parameters.Count != 1) { return; } m.AccessorKind = MethodSemanticsAttributes.Remover; m.AccessorOwner = fakeEvent; fakeEvent.Name = name.Substring(removePrefix.Length); fakeEvent.RemoveAccessor = m; fakeEvent.ReturnType = parameters.Single().Type; return; } if (guessedRaise) { fakeEvent.Name = name.Substring(raisePrefix.Length); fakeEvent.InvokeAccessor = m; m.AccessorKind = MethodSemanticsAttributes.Raiser; m.AccessorOwner = fakeEvent; return; } } }