diff --git a/MockMe.sln b/MockMe.sln index 3d47dff..9b6d1a3 100644 --- a/MockMe.sln +++ b/MockMe.sln @@ -36,7 +36,6 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "wiki", "wiki", "{4723EF4B-98A5-4F3D-BEB9-0632A3939D4D}" ProjectSection(SolutionItems) = preProject wiki\AdvancedUsage.md = wiki\AdvancedUsage.md - wiki\AvoidingCommonPitfalls.md = wiki\AvoidingCommonPitfalls.md wiki\HowDoesItWork.md = wiki\HowDoesItWork.md wiki\QuickStart.md = wiki\QuickStart.md EndProjectSection diff --git a/README.md b/README.md index 43bf7bc..ebbed56 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ ![MockMeFull](https://github.com/user-attachments/assets/43d8b58f-98b0-4469-95c3-7e5ca0683ffc) +___ + +[![Coverage Status](https://coveralls.io/repos/github/connorivy/MockMe/badge.svg?branch=main)](https://coveralls.io/github/connorivy/MockMe?branch=main) + ## What is it? MockMe is a library for mocking dependencies in your production code. Unlike other libraries that can only mock interfaces and virtual methods, MockMe can mock sealed classes and non-virtual methods. @@ -10,7 +14,7 @@ Download NuGet package, then the source generators and the "MockMe.Mock" type wi ```csharp -var mock = Mock.Me(); +var mock = Mock.Me(default(MyRepo)); mock.Setup.ExpensiveDatabaseCall().Returns(99); @@ -21,4 +25,4 @@ mock.Assert.ExpensiveDatabaseCall().WasCalled(); ``` -Check out the [Wiki](https://github.com/connorivy/MockMe/wiki) for more examples. +Check out the [Wiki](https://github.com/connorivy/MockMe/wiki/QuickStart) for more examples. diff --git a/src/MockMe.Abstractions/GenericMethodDefinitionAttribute.cs b/src/MockMe.Abstractions/GenericMethodDefinitionAttribute.cs index cf6d900..85d5a7f 100644 --- a/src/MockMe.Abstractions/GenericMethodDefinitionAttribute.cs +++ b/src/MockMe.Abstractions/GenericMethodDefinitionAttribute.cs @@ -1,7 +1,9 @@ using System; +using System.Diagnostics.CodeAnalysis; namespace MockMe.Abstractions; +[ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class GenericMethodDefinitionAttribute( string typeToReplaceAssemblyName, @@ -18,6 +20,4 @@ string sourceTypeMethodName public string SourceTypeAssemblyName { get; } = sourceTypeAssemblyName; public string SourceTypeFullName { get; } = sourceTypeFullName; public string SourceTypeMethodName { get; } = sourceTypeMethodName; - - public static string GetCoolMessage() => "This only comes from abstractions"; } diff --git a/src/MockMe.Generator/Extensions/MethodSymbolExtensions.cs b/src/MockMe.Generator/Extensions/MethodSymbolExtensions.cs index 6d5541f..8beb8f5 100644 --- a/src/MockMe.Generator/Extensions/MethodSymbolExtensions.cs +++ b/src/MockMe.Generator/Extensions/MethodSymbolExtensions.cs @@ -6,32 +6,6 @@ namespace MockMe.Generator.Extensions; public static class MethodSymbolExtensions { - /// - /// - /// - /// - /// - /// A single object type as a string that can hold all items that the method takes as parameters. - /// If a method only takes a string, then this method will return "string", - /// otherwise it will return "ValueTuple of T1, T2, ..., TN" - /// - public static string GetMethodArgumentsAsCollection(this IMethodSymbol method) - { - var types = method.Parameters.Select(p => p.Type.ToFullTypeString()).ToArray(); - if (types.Length == 0) - { - throw new InvalidOperationException( - "Cannot turn list of zero length in argument collection" - ); - } - if (types.Length == 1) - { - return types[0]; - } - - return $"({string.Join(", ", types)})"; - } - public static string GetParametersWithOriginalTypesAndModifiers(this IMethodSymbol method) => GetParametersWithTypesAndModifiers(method); @@ -144,40 +118,6 @@ public static string GetGenericParameterStringInBrackets(this IMethodSymbol meth return $"<{method.GetGenericParameterString()}>"; } - public static string GetHarmonyPatchAnnotation( - this IMethodSymbol methodSymbol, - string typeFullName - ) - { - // [HarmonyPatch(typeof(global::{ typeSymbol}), nameof(global::{ typeSymbol}.{ this.methodSymbol.Name}))] - string methodTypeArg = string.Empty; - string methodName = methodSymbol.Name; - if (methodSymbol.MethodKind == MethodKind.PropertyGet) - { - methodTypeArg = "global::HarmonyLib.MethodType.Getter"; - methodName = methodName.Substring(4); - } - else if (methodSymbol.MethodKind == MethodKind.PropertySet) - { - methodTypeArg = "global::HarmonyLib.MethodType.Setter"; - methodName = methodName.Substring(4); - } - - //if (methodSymbol.ReturnType.IsTask() || methodSymbol.ReturnType.IsValueTask()) - //{ - // methodTypeArg = "global::HarmonyLib.MethodType.Async"; - //} - - if (!string.IsNullOrEmpty(methodTypeArg)) - { - return $"[global::HarmonyLib.HarmonyPatch(typeof({typeFullName}), nameof({typeFullName}.{methodName}){methodTypeArg.AddPrefixIfNotEmpty(", ")})]"; - } - else - { - return $"[global::HarmonyLib.HarmonyPatch(typeof({typeFullName}), nameof({typeFullName}.{methodName}){string.Join(", ", methodSymbol.Parameters.Select(p => p.Type.ToFullTypeString().AddOnIfNotEmpty("typeof(", ")"))).AddPrefixIfNotEmpty(", ")})]"; - } - } - public static string GetPropertyName(this IMethodSymbol methodSymbol) { if (methodSymbol.MethodKind is MethodKind.PropertyGet or MethodKind.PropertySet) @@ -196,18 +136,4 @@ public static string GetUniqueMethodName(this IMethodSymbol methodSymbol) var uniqueMethodName = $"{methodName}_{string.Join("_", parameterTypes)}"; return uniqueMethodName; } - - public static string GetUniquePropertyNameIgnoringGetSet(this IMethodSymbol methodSymbol) - { - var methodName = methodSymbol.Name; - var parameterTypes = methodSymbol.Parameters.Select(p => p.Type.Name); - var uniqueMethodName = $"{methodName}_{string.Join("_", parameterTypes)}"; - - if (methodSymbol.MethodKind is MethodKind.PropertyGet or MethodKind.PropertySet) - { - return uniqueMethodName[4..]; - } - - return uniqueMethodName; - } } diff --git a/src/MockMe.Generator/MockStoreGenerator.cs b/src/MockMe.Generator/MockStoreGenerator.cs index 20c1633..cbd2475 100644 --- a/src/MockMe.Generator/MockStoreGenerator.cs +++ b/src/MockMe.Generator/MockStoreGenerator.cs @@ -1,14 +1,12 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; -using MockMe.Abstractions; using MockMe.Generator.Extensions; using MockMe.Generator.MockGenerators.TypeGenerators; @@ -64,12 +62,6 @@ internal static partial class {StoreClassName} Dictionary createMockSymbolToNameDict = []; foreach (var typeToMock in GetTypesToBeMocked(source.Left, source.Right)) { - string patchCall = ""; - //if (typeToMock.TypeKind != TypeKind.Interface) - //{ - // patchCall = "EnsurePatch();"; - //} - string genericConstraint; if (typeToMock.IsSealed) { @@ -115,10 +107,8 @@ out var typeToMockName sourceBuilder.AppendLine( @$" [global::System.CodeDom.Compiler.GeneratedCode(""MockMe"", ""{MockMeVersion}"")] - public static global::MockMe.Generated.{typeToMock.ContainingNamespace}.{typeToMockName}Mock{genericArgs} {StoreMethodName}(global::{typeToMock}? unusedInstance{(typeToMock.IsSealed ? "" : " = null")}) - {genericConstraint} + public static global::MockMe.Generated.{typeToMock.ContainingNamespace}.{typeToMockName}Mock{genericArgs} {StoreMethodName}(global::{typeToMock}? unusedInstance) {{ - {patchCall} return new(); }}" ); @@ -175,15 +165,16 @@ ImmutableArray methods method.Expression is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == StoreClassName - && memberAccess.Name is GenericNameSyntax genericName - && genericName.TypeArgumentList.Arguments.Count == 1 - && genericName.Identifier.Text == StoreMethodName + && method.ArgumentList.Arguments.Count == 1 + && method.ArgumentList.Arguments[0].Expression + is DefaultExpressionSyntax defaultExpression + //&& memberAccess.Name is GenericNameSyntax genericName + //&& genericName.TypeArgumentList.Arguments.Count == 1 + //&& genericName.Identifier.Text == StoreMethodName ) { var model = compilation.GetSemanticModel(method.SyntaxTree); - var genericArgSymbol = model - .GetTypeInfo(genericName.TypeArgumentList.Arguments[0]) - .Type; + var genericArgSymbol = model.GetTypeInfo(defaultExpression.Type).Type; if ( genericArgSymbol is not null @@ -212,26 +203,9 @@ namespace {NamespaceName} {{ internal static partial class {StoreClassName} {{ - public static Mock {StoreMethodName}(global::{NamespaceName}.DummyClass unusedInstance) - where T : global::{NamespaceName}.DummyClass - {{ - throw new NotImplementedException(); - }} - - private static bool isPatched; - private static readonly object LockObj = new(); - - private static void EnsurePatch() + public static object {StoreMethodName}(global::{NamespaceName}.DummyClass unusedInstance) {{ - lock (LockObj) - {{ - if (!isPatched) - {{ - var harmony = new global::HarmonyLib.Harmony(""com.mockme.patch""); - harmony.PatchAll(); - isPatched = true; - }} - }} + throw new global::System.NotImplementedException(); }} }} }} diff --git a/src/MockMe.PostBuild/Extensions/GenericMethodInfoExtensions.cs b/src/MockMe.PostBuild/Extensions/GenericMethodInfoExtensions.cs deleted file mode 100644 index 3e84c02..0000000 --- a/src/MockMe.PostBuild/Extensions/GenericMethodInfoExtensions.cs +++ /dev/null @@ -1,20 +0,0 @@ -using MockMe.Abstractions; -using Mono.Cecil; - -namespace MockMe.PostBuild.Extensions; - -internal static class GenericMethodInfoExtensions -{ - public static (TypeDefinition, MethodDefinition) GetMethodInfo( - this GenericMethodInfo methodInfo, - ModuleDefinition module - ) - { - TypeDefinition typeToReplace = module.GetType(methodInfo.TypeFullName); - MethodDefinition methodToReplace = typeToReplace.Methods.First(m => - m.Name == methodInfo.MethodName - ); - - return (typeToReplace, methodToReplace); - } -} diff --git a/src/MockMe.PostBuild/Extensions/TypeDefinitionExtensions.cs b/src/MockMe.PostBuild/Extensions/TypeDefinitionExtensions.cs deleted file mode 100644 index c5fcfa5..0000000 --- a/src/MockMe.PostBuild/Extensions/TypeDefinitionExtensions.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Mono.Cecil; - -namespace MockMe.PostBuild.Extensions; - -internal static class TypeDefinitionExtensions -{ - public static MethodReference GetMethod( - this TypeDefinition type, - string methodName, - params Type[] parameterTypes - ) - { - foreach (var method in type.Methods) - { - if (method.FullName != methodName || method.Parameters.Count != parameterTypes.Length) - { - continue; - } - - bool match = true; - for (int i = 0; i < parameterTypes.Length; i++) - { - var paramType = method.Parameters[i].ParameterType; - if ( - paramType.IsGenericParameter - || paramType.FullName != parameterTypes[i].FullName - ) - { - match = false; - break; - } - } - if (match) - { - return method; - } - } - - throw new InvalidOperationException(); - } -} diff --git a/src/MockMe/MockCallTracker.cs b/src/MockMe/MockCallTracker.cs index 94c6368..7d57587 100644 --- a/src/MockMe/MockCallTracker.cs +++ b/src/MockMe/MockCallTracker.cs @@ -1,5 +1,4 @@ using MockMe.Extensions; -using MockMe.Mocks.ClassMemberMocks; namespace MockMe; @@ -53,12 +52,7 @@ private static TReturn? FindAndCallApplicableMemberMock< continue; } - var localReturn = CallMemberMockBase< - TReturn, - TOriginalArgCollection, - TCallback, - TReturnCall - >( + var localReturn = CallMemberMockBase( argBag.Mock, argCollection, callbackAction, diff --git a/tests/MockMe.Tests.Overloads/ArgumentModifierTests.cs b/tests/MockMe.Tests.Overloads/ArgumentModifierTests.cs index 26a025f..07f4691 100644 --- a/tests/MockMe.Tests.Overloads/ArgumentModifierTests.cs +++ b/tests/MockMe.Tests.Overloads/ArgumentModifierTests.cs @@ -8,7 +8,7 @@ public class ArgumentModifierTests [Fact] public void OutKeyword_WhenConfiguredInReturnCall_ShouldSetTheCorrectValue() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); mock.Setup.OutArgument(out _) .Returns(args => @@ -28,7 +28,7 @@ public void OutKeyword_WhenConfiguredInReturnCall_ShouldSetTheCorrectValue() [Fact] public void OutKeyword_WhenConfiguredInCallbackCall_ShouldSetTheCorrectValue() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); mock.Setup.OutArgument(out _).Callback(args => args.arg = 55).Returns(99); @@ -43,7 +43,7 @@ public void OutKeyword_WhenConfiguredInCallbackCall_ShouldSetTheCorrectValue() [Fact] public void ParametersNotPassedByReference_ShouldNotHaveASetter() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); var outParamType = typeof(AllOverloadsMockSetup.OutArgument_OutInt32Collection); var regularParamType = typeof(AllOverloadsMockSetup.OutArgument_Int32Collection); diff --git a/tests/MockMe.Tests.Overloads/AsyncMethodOverloadTests.cs b/tests/MockMe.Tests.Overloads/AsyncMethodOverloadTests.cs index 9e03592..daf4b4d 100644 --- a/tests/MockMe.Tests.Overloads/AsyncMethodOverloadTests.cs +++ b/tests/MockMe.Tests.Overloads/AsyncMethodOverloadTests.cs @@ -28,7 +28,7 @@ public class AsyncMethodOverloadTests [InlineData(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] public async Task AsyncReturnOverload_CallbackAndAssertShouldWork(params int[] ints) { - var mock = Mock.Me(null); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; diff --git a/tests/MockMe.Tests.Overloads/AsyncOfTMethodOverloadsTests.cs b/tests/MockMe.Tests.Overloads/AsyncOfTMethodOverloadsTests.cs index 4f85ffe..a72a20e 100644 --- a/tests/MockMe.Tests.Overloads/AsyncOfTMethodOverloadsTests.cs +++ b/tests/MockMe.Tests.Overloads/AsyncOfTMethodOverloadsTests.cs @@ -28,7 +28,7 @@ public class AsyncOfTMethodOverloadsTests [InlineData(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] public async Task AsyncOfTReturnOverload_CallbackAndAssertShouldWork(params int[] ints) { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; diff --git a/tests/MockMe.Tests.Overloads/IndexerTests.cs b/tests/MockMe.Tests.Overloads/IndexerTests.cs index ac07290..24144d5 100644 --- a/tests/MockMe.Tests.Overloads/IndexerTests.cs +++ b/tests/MockMe.Tests.Overloads/IndexerTests.cs @@ -8,7 +8,7 @@ public class IndexerTests [Fact] public void IndexerGetForInt_ReturnsAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup[Arg.Any()].Get().Callback(() => numCalls++).Returns("hello indexer"); @@ -28,7 +28,7 @@ public void IndexerGetForInt_ReturnsAndCallbackShouldWork() [Fact] public void IndexerSetForInt_ReturnsAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup[Arg.Any()].Set(Arg.Any()).Callback(() => numCalls++); @@ -48,7 +48,7 @@ public void IndexerSetForInt_ReturnsAndCallbackShouldWork() [Fact] public void IndexerGetForString_ReturnsAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup[Arg.Any()].Get().Callback(() => numCalls++).Returns(99); @@ -66,7 +66,7 @@ public void IndexerGetForString_ReturnsAndCallbackShouldWork() [Fact] public void SetOnlyIndexer_AssertAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup[Arg.Any()].Set(Arg.Any()).Callback(() => numCalls++); diff --git a/tests/MockMe.Tests.Overloads/PropertyTests.cs b/tests/MockMe.Tests.Overloads/PropertyTests.cs index c49b6f3..6fbaf46 100644 --- a/tests/MockMe.Tests.Overloads/PropertyTests.cs +++ b/tests/MockMe.Tests.Overloads/PropertyTests.cs @@ -7,7 +7,7 @@ public class PropertyTests [Fact] public void GetInitProperty_ReturnsAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup.Prop_GetInit.Get().Returns(99).Callback(() => numCalls++); @@ -24,7 +24,7 @@ public void GetInitProperty_ReturnsAndCallbackShouldWork() [Fact] public void GetOnlyProperty_ReturnsAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup.Prop_GetOnly.Get().Returns(99).Callback(() => numCalls++); @@ -41,7 +41,7 @@ public void GetOnlyProperty_ReturnsAndCallbackShouldWork() [Fact] public void GetSetProperty_ReturnsAndCallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup.Prop_GetSet.Get().Returns(99).Callback(() => numCalls++); @@ -61,7 +61,7 @@ public void GetSetProperty_ReturnsAndCallbackShouldWork() [Fact] public void SetOnlyProperty_CallbackShouldWork() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; mock.Setup.Prop_SetOnly.Set(Arg.Any()).Callback(() => numCalls++); @@ -77,7 +77,7 @@ public void SetOnlyProperty_CallbackShouldWork() [Fact] public void GetInitProperty_HasNoSetter() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); var setSetter = mock.Setup.Prop_GetSet.GetType().GetMethod("Set"); var initSetter = mock.Setup.Prop_GetInit.GetType().GetMethod("Set"); @@ -89,7 +89,7 @@ public void GetInitProperty_HasNoSetter() [Fact] public void SetOnlyProperty_HasNoGetter() { - var mock = Mock.Me(default(AllOverloads)); + var mock = Mock.Me(default(AllOverloads)); var getGetter = mock.Setup.Prop_GetSet.GetType().GetMethod("Get"); var setOnlyGetter = mock.Setup.Prop_SetOnly.GetType().GetMethod("Get"); diff --git a/tests/MockMe.Tests.Overloads/SyncMethodOverloadsTests.cs b/tests/MockMe.Tests.Overloads/SyncMethodOverloadsTests.cs index eed490c..42175d9 100644 --- a/tests/MockMe.Tests.Overloads/SyncMethodOverloadsTests.cs +++ b/tests/MockMe.Tests.Overloads/SyncMethodOverloadsTests.cs @@ -27,7 +27,7 @@ public class SyncMethodOverloadsTests [InlineData(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] public void SyncReturnOverload_CallbackAndAssertShouldWork(params int[] ints) { - var mock = Mock.Me(default); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; diff --git a/tests/MockMe.Tests.Overloads/VoidMethodOverloadsTests.cs b/tests/MockMe.Tests.Overloads/VoidMethodOverloadsTests.cs index 8fb1b25..f91b5dd 100644 --- a/tests/MockMe.Tests.Overloads/VoidMethodOverloadsTests.cs +++ b/tests/MockMe.Tests.Overloads/VoidMethodOverloadsTests.cs @@ -27,7 +27,7 @@ public class VoidMethodOverloadsTests [InlineData(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)] public void VoidOverload_CallbackAndAssertShouldWork(params int[] ints) { - var mock = Mock.Me(null); + var mock = Mock.Me(default(AllOverloads)); int numCalls = 0; diff --git a/tests/MockMe.Tests.Runner/Program.cs b/tests/MockMe.Tests.Runner/Program.cs index a0b1e78..5858bcd 100644 --- a/tests/MockMe.Tests.Runner/Program.cs +++ b/tests/MockMe.Tests.Runner/Program.cs @@ -5,7 +5,8 @@ Console.WriteLine("Hello, World!"); var testsFolderPath = Path.Combine( - Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + ?? throw new InvalidOperationException("path must not be null"), "..", "..", "..", diff --git a/tests/MockMe.Tests/ArgTests.cs b/tests/MockMe.Tests/ArgTests.cs index 43cff1c..d589e34 100644 --- a/tests/MockMe.Tests/ArgTests.cs +++ b/tests/MockMe.Tests/ArgTests.cs @@ -10,7 +10,7 @@ public class ArgTests [Fact] public void ArgAny_ShouldCoverAnyArgument() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); Calculator calculator = calculatorMock; diff --git a/tests/MockMe.Tests/AssertionTests.cs b/tests/MockMe.Tests/AssertionTests.cs index 2d01f21..f5b07a4 100644 --- a/tests/MockMe.Tests/AssertionTests.cs +++ b/tests/MockMe.Tests/AssertionTests.cs @@ -11,7 +11,7 @@ public class AssertionTests [Fact] public void TestWasCalled_ForMethodWithNoArgsAndNoReturnVal() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); Assert.ThrowsAny(() => calculatorMock.Assert.TurnOff().WasCalled()); @@ -48,7 +48,7 @@ public void TestWasCalled_ForMethodWithNoArgsAndNoReturnVal() [Fact] public void SetCalculatorType_PropertySetterWasCalled() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); Assert.ThrowsAny( () => @@ -69,7 +69,7 @@ public void SetCalculatorType_PropertySetterWasCalled() [Fact] public void SetICalculatorType_PropertySetterWasCalled() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(ICalculator)); Assert.ThrowsAny( () => diff --git a/tests/MockMe.Tests/CallbackTests.cs b/tests/MockMe.Tests/CallbackTests.cs index fd84887..543002c 100644 --- a/tests/MockMe.Tests/CallbackTests.cs +++ b/tests/MockMe.Tests/CallbackTests.cs @@ -8,7 +8,7 @@ public class CallbackTests [Fact] public void Callback_IsCalled() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); int numTimesCalled = 0; calculatorMock.Setup.Add(Arg.Any(), Arg.Any()).Callback(() => numTimesCalled++); @@ -23,7 +23,7 @@ public void Callback_IsCalled() [Fact] public void Callback_IsCalledWithCorrectArgs() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); int multResult = 0; calculatorMock @@ -40,7 +40,7 @@ public void Callback_IsCalledWithCorrectArgs() [Fact] public void MultipleCallbacks_AreCalledInOrder() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); int? first = null; int? second = null; @@ -96,7 +96,7 @@ public void MultipleCallbacks_AreCalledInOrder() [Fact] public void CallbacksBeforeAndAfterReturn_AreCalledInOrder() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); bool callback1Called = false; bool returnCalled = false; diff --git a/tests/MockMe.Tests/GenericClassTests.cs b/tests/MockMe.Tests/GenericClassTests.cs index 9299005..45d6bbe 100644 --- a/tests/MockMe.Tests/GenericClassTests.cs +++ b/tests/MockMe.Tests/GenericClassTests.cs @@ -31,8 +31,8 @@ public class GenericClassTests [Fact] public void MultipleValueTypeOverloads_ShouldReturnConfiguredValues() { - var mockInt = Mock.Me>(); - var mockDouble = Mock.Me>(); + var mockInt = Mock.Me(default(ConnorsCoolGenericType)); + var mockDouble = Mock.Me(default(ConnorsCoolGenericType)); mockInt.Setup.GetRandomVal().Returns(99); mockDouble.Setup.GetRandomVal().Returns(99.99); @@ -50,8 +50,8 @@ public void MultipleValueTypeOverloads_ShouldReturnConfiguredValues() [Fact] public void MultipleCustomStructOverloads_ShouldReturnConfiguredValues() { - var mockCool = Mock.Me>(); - var mockEvil = Mock.Me>(); + var mockCool = Mock.Me(default(ConnorsCoolGenericType)); + var mockEvil = Mock.Me(default(ConnorsCoolGenericType)); mockCool.Setup.GetRandomVal().Returns(new ConnorsCoolReadonlyStruct()); mockEvil.Setup.GetRandomVal().Returns(new ConnorsEvilMutableStruct()); @@ -71,8 +71,8 @@ public void MultipleCustomStructOverloads_ShouldReturnConfiguredValues() [Fact] public void RefAndValueTypeOverloads_ShouldReturnConfiguredValues() { - var mockInt = Mock.Me>(); - var mockString = Mock.Me>(); + var mockInt = Mock.Me(default(ConnorsCoolGenericType)); + var mockString = Mock.Me(default(ConnorsCoolGenericType)); mockInt.Setup.GetRandomVal().Returns(99); mockString.Setup.GetRandomVal().Returns("returnVal"); @@ -90,8 +90,8 @@ public void RefAndValueTypeOverloads_ShouldReturnConfiguredValues() [Fact] public void MultipleReferenceTypeOverloads_ShouldReturnConfiguredValues() { - var mockObject = Mock.Me>(); - var mockString = Mock.Me>(); + var mockObject = Mock.Me(default(ConnorsCoolGenericType)); + var mockString = Mock.Me(default(ConnorsCoolGenericType)); object myObj = new(); @@ -111,7 +111,7 @@ public void MultipleReferenceTypeOverloads_ShouldReturnConfiguredValues() [Fact] public void PropertyOfGenericClassType_ShouldReturnConfiguredValues() { - var mockString = Mock.Me>(); + var mockString = Mock.Me(default(ConnorsCoolGenericType)); mockString.Setup.MyCoolProp.Get().Returns("returnVal"); string? setVal = null; diff --git a/tests/MockMe.Tests/GenericMethodTests.cs b/tests/MockMe.Tests/GenericMethodTests.cs index 5e74a4f..d238fef 100644 --- a/tests/MockMe.Tests/GenericMethodTests.cs +++ b/tests/MockMe.Tests/GenericMethodTests.cs @@ -9,11 +9,11 @@ public class GenericMethodTests [Fact] public void GenericMethod_ShouldReturnConfiguredValue() { - var mock = Mock.Me(); + var mock = Mock.Me(default(ComplexCalculator)); mock.Setup.ComputeHashForObjects(Arg.Any()).Returns(99); - ComplexCalculator calc = (ComplexCalculator)mock; + ComplexCalculator calc = mock; var result = calc.ComputeHashForObjects(new int[] { 1, 2, 3, 4, 5 }); Assert.Equal(99, result); @@ -22,7 +22,7 @@ public void GenericMethod_ShouldReturnConfiguredValue() [Fact] public void GenericMethodWithMultipleGenericArgs_ShouldReturnConfiguredValue() { - var mock = Mock.Me(); + var mock = Mock.Me(default(ClassWithGenericMethods)); mock.Setup.ThreeGenericTypes(Arg.Any(), Arg.Any(), Arg.Any()) .Returns("asdf"); diff --git a/tests/MockMe.Tests/InheritanceTests.cs b/tests/MockMe.Tests/InheritanceTests.cs index fc6d9d2..f4d27e0 100644 --- a/tests/MockMe.Tests/InheritanceTests.cs +++ b/tests/MockMe.Tests/InheritanceTests.cs @@ -44,7 +44,7 @@ public class InheritanceTests [Fact] public void ChildClassWhichCallsBase_ShouldStillWork_WhenMocked() { - var mock = Mock.Me(); + var mock = Mock.Me(default(ChildClass)); ChildClass notMocked = new(); @@ -54,7 +54,7 @@ public void ChildClassWhichCallsBase_ShouldStillWork_WhenMocked() [Fact] public void ChildClassWhichOverridesBase_ShouldStillWork_WhenMocked() { - var mock = Mock.Me(); + var mock = Mock.Me(default(ChildClass)); ChildClass notMocked = new(); diff --git a/tests/MockMe.Tests/InliningTests.cs b/tests/MockMe.Tests/InliningTests.cs index 85a0300..958f52d 100644 --- a/tests/MockMe.Tests/InliningTests.cs +++ b/tests/MockMe.Tests/InliningTests.cs @@ -1,9 +1,11 @@ +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using MockMe.Tests.ExampleClasses; using Xunit; namespace MockMe.Tests { + [ExcludeFromCodeCoverage] public class PotentiallyInlinedMethods { public int AddNormal(int x, int y) => x + y; @@ -15,6 +17,7 @@ public class PotentiallyInlinedMethods public int AddAggressiveInline(int x, int y) => x + y; } + [ExcludeFromCodeCoverage] public class InlineTestCaller { private readonly PotentiallyInlinedMethods potentiallyInlinedMethods; @@ -34,6 +37,7 @@ public int AddAggressiveInline(int x, int y) => public class InliningTests { + [ExcludeFromCodeCoverage] public class CalculatorManager { private readonly Calculator calculator; @@ -55,7 +59,7 @@ public CalculatorManager(Calculator calculator) [Fact] public void CalculatorAdd_ShouldReturnConfiguredValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(3, 5).Returns(99, 999, 9999); CalculatorManager calculatorManager = new(calculatorMock); @@ -67,7 +71,7 @@ public void CalculatorAdd_ShouldReturnConfiguredValue() [Fact] public void AddMethod_ShouldReturnConfiguredValue() { - var inlineMock = Mock.Me(); + var inlineMock = Mock.Me(default(PotentiallyInlinedMethods)); inlineMock.Setup.AddNoInline(Arg.Any(), Arg.Any()).Returns(99); inlineMock.Setup.AddNormal(Arg.Any(), Arg.Any()).Returns(999); diff --git a/tests/MockMe.Tests/ReturnsTests.cs b/tests/MockMe.Tests/ReturnsTests.cs index fb120ab..63f6f6d 100644 --- a/tests/MockMe.Tests/ReturnsTests.cs +++ b/tests/MockMe.Tests/ReturnsTests.cs @@ -10,7 +10,7 @@ public class ReturnsTests [Fact] public void CalculatorAdd_ShouldReturnConfiguredValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(1, 2).Returns(9999); @@ -20,7 +20,7 @@ public void CalculatorAdd_ShouldReturnConfiguredValue() [Fact] public void CalculatorAdd_WhenReturnIsFunc_ShouldCallFunc() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(1, 2).Returns(() => 9999); @@ -30,7 +30,7 @@ public void CalculatorAdd_WhenReturnIsFunc_ShouldCallFunc() [Fact] public void CalculatorAdd_WhenReturnIsFuncOfT_ShouldCallFuncOfT() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(10, 55).Returns(args => args.x * args.y); @@ -40,7 +40,7 @@ public void CalculatorAdd_WhenReturnIsFuncOfT_ShouldCallFuncOfT() [Fact] public void ICalculatorAdd_ShouldReturnConfiguredValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(ICalculator)); calculatorMock.Setup.Add(1, 2).Returns(9999); @@ -50,7 +50,7 @@ public void ICalculatorAdd_ShouldReturnConfiguredValue() [Fact] public void CalculatorAdd_WhenCalledByANonMock_ShouldCallOriginalCode() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(1, 2).Returns(9999); @@ -64,7 +64,7 @@ public void CalculatorAdd_WhenCalledByANonMock_ShouldCallOriginalCode() [Fact] public void CalculatorAdd_WhenReturnIsCalledManyTimes_ShouldReturnConfiguredValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(1, 2).Returns(9999); @@ -78,7 +78,7 @@ public void CalculatorAdd_WhenReturnIsCalledManyTimes_ShouldReturnConfiguredValu [Fact] public void CalculatorAdd_WhenReturnIsCalledManyTimesWithDifferentValues_ShouldReturnConfiguredValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.Add(1, 2).Returns(9, 99, 999, 9999, 99999); @@ -92,7 +92,7 @@ public void CalculatorAdd_WhenReturnIsCalledManyTimesWithDifferentValues_ShouldR [Fact] public void CalculatorType_ShouldReturnConfiguredPropertyValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(Calculator)); calculatorMock.Setup.CalculatorType.Get().Returns(CalculatorType.Graphing); @@ -102,7 +102,7 @@ public void CalculatorType_ShouldReturnConfiguredPropertyValue() [Fact] public void ICalculatorType_ShouldReturnConfiguredPropertyValue() { - var calculatorMock = Mock.Me(); + var calculatorMock = Mock.Me(default(ICalculator)); calculatorMock.Setup.CalculatorType.Get().Returns(CalculatorType.Graphing); @@ -112,7 +112,7 @@ public void ICalculatorType_ShouldReturnConfiguredPropertyValue() [Fact] public async Task CalculatorAddAsync_ShouldReturnConfiguredPropertyValue() { - var calculatorMock = Mock.Me(default(ComplexCalculator)); + var calculatorMock = Mock.Me(default(ComplexCalculator)); calculatorMock.Setup.MultiplyAsync(1, 1).ReturnsAsync(9); @@ -128,7 +128,7 @@ public async Task CalculatorAddAsync_ShouldReturnConfiguredPropertyValue() [Fact] public async Task CalculatorAddAsync_WhenReturnIsNotConfigured_ShouldReturnCompletedTask() { - var calculatorMock = Mock.Me(default(ComplexCalculator)); + var calculatorMock = Mock.Me(default(ComplexCalculator)); ComplexCalculator calc = calculatorMock; @@ -140,7 +140,7 @@ public async Task CalculatorAddAsync_WhenReturnIsNotConfigured_ShouldReturnCompl [Fact] public async Task CalculatorWaitAsync_WhenReturnIsNotConfigured_ShouldReturnCompletedTask() { - var calculatorMock = Mock.Me(default(ComplexCalculator)); + var calculatorMock = Mock.Me(default(ComplexCalculator)); ComplexCalculator calc = calculatorMock; diff --git a/tests/MockMe.Tests/ThrowsTests.cs b/tests/MockMe.Tests/ThrowsTests.cs index 2c26a4f..156a96f 100644 --- a/tests/MockMe.Tests/ThrowsTests.cs +++ b/tests/MockMe.Tests/ThrowsTests.cs @@ -9,7 +9,7 @@ public class ThrowsTests [Fact] public void Throws_ShouldThrowException() { - var mock = Mock.Me(); + var mock = Mock.Me(default(Calculator)); mock.Setup.Add(Arg.Any(), Arg.Any()).Throws(new InvalidCastException()); // throw random exception @@ -21,7 +21,7 @@ public void Throws_ShouldThrowException() [Fact] public void ReturnFollowedByThrows_ShouldReturnThenThrowException() { - var mock = Mock.Me(); + var mock = Mock.Me(default(Calculator)); mock.Setup.Add(Arg.Any(), Arg.Any()) .Returns(9, 99, 999) @@ -38,7 +38,7 @@ public void ReturnFollowedByThrows_ShouldReturnThenThrowException() [Fact] public void Throws_ShouldGiveAccurateAssertInfo() { - var mock = Mock.Me(); + var mock = Mock.Me(default(Calculator)); mock.Setup.Add(Arg.Any(), Arg.Any()).Throws(new InvalidCastException()); // throw random exception diff --git a/wiki/AdvancedUsage.md b/wiki/AdvancedUsage.md index afaeb7d..35d2bed 100644 --- a/wiki/AdvancedUsage.md +++ b/wiki/AdvancedUsage.md @@ -9,7 +9,7 @@ class MyCoolClass } } -var mock = Mock.Me(); +var mock = Mock.Me(default(MyCoolClass)); // the out parameter can be discarded, as it doesn't do anything here. // the only reason it is here is because dropping it could lead to conflicts with other method overloads diff --git a/wiki/QuickStart.md b/wiki/QuickStart.md index 8a691ae..027f81a 100644 --- a/wiki/QuickStart.md +++ b/wiki/QuickStart.md @@ -5,7 +5,7 @@ You can control the return value of public methods and properties by using the ' ```csharp -var mock = Mock.Me(); +var mock = Mock.Me(default(Calculator)); // specify that 'Add(1, 1)' should return 99 mock.Setup.Add(1, 1).Returns(99); @@ -43,7 +43,7 @@ calc["string indexer"]; // result is 9.999 ```csharp -var mock = Mock.Me(); +var mock = Mock.Me(default(Calculator)); // return no matter the arguments passed into the 'Add' method mock.Setup.Add(Arg.Any(), Arg.Any()).Returns(99); @@ -70,7 +70,7 @@ mock.Add(5, 5); // result is 555 ```csharp -var mock = Mock.Me(); +var mock = Mock.Me(default(Calculator)); int numCalls = 0; mock.Setup.Add(1, 1) @@ -100,7 +100,7 @@ mock.Setup.CalculatorType.Set(Arg.Any()).Callback(args => typeUsedBySetter = arg ```csharp -var mock = Mock.Me(); +var mock = Mock.Me(default(Calculator)); // called at least once mock.Assert.Add(1, 1).WasCalled();