From c10105700ace5f293a7d5a5c23e57c6f97b32146 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 17:55:22 +0200 Subject: [PATCH 01/30] Simplify the AsMustBeUsedWithInterfaceAnalyzer unit tests --- .../AsMustBeUsedWithInterfaceAnalyzerTest.cs | 139 ++++++++---------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 27 ++++ 2 files changed, 85 insertions(+), 81 deletions(-) create mode 100644 tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs diff --git a/tests/Moq.Analyzers.Tests/Analyzers/AsMustBeUsedWithInterfaceAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/AsMustBeUsedWithInterfaceAnalyzerTest.cs index e6ac324..e8d32aa 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/AsMustBeUsedWithInterfaceAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/AsMustBeUsedWithInterfaceAnalyzerTest.cs @@ -10,10 +10,47 @@ namespace PosInformatique.Moq.Analyzers.Tests public class AsMustBeUsedWithInterfaceAnalyzerTest { - [Fact] - public async Task AsMethod_WithInterface() + public static TheoryData ValidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.As(); + """, + + // No As() method call. + """ + var mock1 = new Mock(); + mock1.Setup(m => m.Method()); + """, + + // Ignored by ExtractAsMethodType() because it is not a MemberAccessExpressionSyntax. + """ + var action = new System.Action(() => { }); + action(); + """, + + // Ignored by ExtractAsMethodType() because it is not an As() symbol. + """ + var c = new C(); + c.GenericMethodNotAs(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.As<{|PosInfoMoq2007:C|}>(); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -22,119 +59,59 @@ public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.As(); + {{code}} } } public class C { + public virtual void Method() { } + + public void GenericMethodNotAs() { } } public interface I { } - }"; + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task AsMethod_WithClass() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.As<[|C2|]>(); - } - } - - public class C - { - } - - public class C2 - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoAsMethod() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(m => m.Method()); - - var action = new System.Action(() => { }); - action(); // Ignored by the ExtractAsMethodType() method because not a MemberAccessExpressionSyntax. - - var otherClass = new OtherClass(); - otherClass.GenericMethodNotAs(); // Ignored by the ExtractAsMethodType() method because it not As() symbol. + {{code}} } } public class C { public virtual void Method() { } - } - - public class OtherClass - { + public void GenericMethodNotAs() { } } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.As(); - } - } - + public interface I { } } - namespace OtherNamespace - { - public class Mock - { - public void As() { } - } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs new file mode 100644 index 0000000..67d3652 --- /dev/null +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -0,0 +1,27 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) P.O.S Informatique. All rights reserved. +// +//----------------------------------------------------------------------- + +namespace PosInformatique.Moq.Analyzers.Tests +{ + public static class MoqAnalyzersTests + { + public const string FakeMoqLibrary = + """ + namespace FakeMoqLibrary + { + using System; + using System.Linq.Expressions; + + public class Mock + { + public void As() { } + + public void Setup(Expression> expression) { } + } + } + """; + } +} From 8c08cf10074eca5b309cf17a952e4c712545ef2d Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 18:20:23 +0200 Subject: [PATCH 02/30] Refactoring unit tests for SetupSetAnalyzerTest --- .../Analyzers/SetupSetAnalyzerTest.cs | 101 ++++++++---------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 6 ++ .../MoqCSharpAnalyzerVerifier.cs | 1 + 3 files changed, 54 insertions(+), 54 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/SetupSetAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/SetupSetAnalyzerTest.cs index f8868cb..6d5c5ea 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/SetupSetAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/SetupSetAnalyzerTest.cs @@ -10,25 +10,50 @@ namespace PosInformatique.Moq.Analyzers.Tests public class SetupSetAnalyzerTest { - [Fact] - public async Task SetupSetWithGenericArgument_NoDiagnosticReported() + public static TheoryData ValidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.SetupSet(i => i.TestProperty = 1234); + """, + + // Ignored because obsolete by Moq. + """ + var mock1 = new Mock(); + mock1.SetupSet(i => i.TestProperty); + """, + + // Invocation should be ignored. + """ + var s = "The string"; + s.ToString(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.{|PosInfoMoq1005:SetupSet|}(i => i.TestProperty = 1234); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.SetupSet(i => i.TestProperty = 1234); - mock1.SetupSet(i => i.TestProperty); // Ignored because Obsolete by Moq - - var s = ""The string""; - s.ToString(); // Invocation should be ignored + {{code}} } } @@ -36,29 +61,28 @@ public interface I { int TestProperty { get; set; } } - }"; + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task SetupSetWithNoGenericArgument_DiagnosticReported() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - using System; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.[|SetupSet|](i => i.TestProperty = 1234); - - var s = ""The string""; - s.ToString(); // Invocation should be ignored + {{code}} } } @@ -66,41 +90,10 @@ public interface I { int TestProperty { get; set; } } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.SetupSet(i => i.Property = 1234); - } - } - - public interface I - { - int Property { get; set; } - } } - namespace OtherNamespace - { - public class Mock - { - public void SetupSet(System.Action _) { } - } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 67d3652..d6d0a16 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -20,6 +20,12 @@ public class Mock public void As() { } public void Setup(Expression> expression) { } + + public void SetupSet(Action action) { } + + public void SetupSet(Action action) { } + + public void SetupSet(Func action) { } } } """; diff --git a/tests/Moq.Analyzers.Tests/MoqCSharpAnalyzerVerifier.cs b/tests/Moq.Analyzers.Tests/MoqCSharpAnalyzerVerifier.cs index ac169eb..68f23b9 100644 --- a/tests/Moq.Analyzers.Tests/MoqCSharpAnalyzerVerifier.cs +++ b/tests/Moq.Analyzers.Tests/MoqCSharpAnalyzerVerifier.cs @@ -29,6 +29,7 @@ public static async Task VerifyAnalyzerWithNoMoqLibraryAsync(string source) { var context = new CSharpAnalyzerTest(); context.ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20; + context.TestState.MarkupHandling = MarkupMode.Ignore; context.TestCode = source; From dc70fce1d8a342de7deedd8c7c58e7c3ca151409 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 18:30:02 +0200 Subject: [PATCH 03/30] Refactoring of the MockOfAnalyzerTest --- .../Analyzers/MockOfAnalyzerTest.cs | 748 +++++------------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 16 + 2 files changed, 218 insertions(+), 546 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/MockOfAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/MockOfAnalyzerTest.cs index 2f2e199..a0a516d 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/MockOfAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/MockOfAnalyzerTest.cs @@ -10,596 +10,252 @@ namespace PosInformatique.Moq.Analyzers.Tests public class MockOfAnalyzerTest { - [Fact] - public async Task NoSealedClass_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(); - } - } - - public class StandardClass - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoSealedClass_WithMultipleConstructors_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(); - } - } - - public class StandardClass - { - public StandardClass() - { - } - - public StandardClass(int a) - { - } - - public StandardClass(string b) - { - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoSealedClass_WithExpression_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(sc => sc.Property == 1234); - } - } - - public class StandardClass - { - public int Property { get; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoSealedClass_WithExpression_WithMultipleConstructors_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(sc => sc.Property == 1234); - } - } - - public class StandardClass - { - public StandardClass() - { - } - - public StandardClass(int a) - { - } - - public StandardClass(string b) - { - } - - public int Property { get; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Interface_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(); - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Interface_WithExpression_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(sc => sc.Property == 1234); - } - } - - public interface I - { - int Property { get; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData("MockBehavior.Strict")] - public async Task AbstractClass_NoDiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(" + mockBehavior + @"); - } - } - - public abstract class AbstractClass - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData("MockBehavior.Strict")] - public async Task AbstractClass_WithMultipleConstructors_NoDiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(" + mockBehavior + @"); - } - } - - public abstract class AbstractClass - { - public AbstractClass() - { - } - - public AbstractClass(int a) - { - } - - public AbstractClass(string b) - { - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData(", MockBehavior.Strict")] - public async Task AbstractClass_WithExpression_NoDiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(sc => sc.Property == 1234" + mockBehavior + @"); - } - } - - public abstract class AbstractClass - { - public int Property { get; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData(", MockBehavior.Strict")] - public async Task AbstractClass_WithExpression_WithMultipleConstructors_NoDiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(sc => sc.Property == 1234" + mockBehavior + @"); - } - } - - public abstract class AbstractClass - { - public int Property { get; } - - public AbstractClass() - { - } - - public AbstractClass(int a) - { - } - - public AbstractClass(string b) - { - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMockOfUsage_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - string.Format(""Ignored""); // Ignored by the analysis. - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task SealedClass_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of<{|PosInfoMoq2009:SealedClass|}>(); - } - } - - public sealed class SealedClass - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task SealedClass_WithExpression_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of<{|PosInfoMoq2009:SealedClass|]>(sc => sc.Property == 1234); - } - } - - public sealed class SealedClass - { - public int Property { get; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData("MockBehavior.Strict")] - public async Task Struct_DiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of<{|PosInfoMoq2009:string|]>(" + mockBehavior + @"); - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } + private const string TestTypes = + """ + public class StandardClass + { + public int Property { get; } + } - [Theory] - [InlineData("")] - [InlineData(", MockBehavior.Strict")] - public async Task Struct_WithExpression_DiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of<{|PosInfoMoq2009:string|]>(sc => sc.Length == 1234" + mockBehavior + @"); - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } + public class StandardClassWithMultipleConstructors + { + public StandardClassWithMultipleConstructors() { } - [Theory] - [InlineData("")] - [InlineData(", MockBehavior.Strict")] - public async Task Struct_WithExpressionAndTypeInLambdaParameter_DiagnosticReported(string mockBehavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + public StandardClassWithMultipleConstructors(int a) { } + + public StandardClassWithMultipleConstructors(string b) { } - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(({|PosInfoMoq2009:string|] sc) => sc.Length == 1234" + mockBehavior + @"); - } - } - }"; + public int Property { get; } + } + + public interface I + { + int Property { get; } + } - await Verifier.VerifyAnalyzerAsync(source); - } + public abstract class AbstractClass + { + public int Property { get; } + } + + public abstract class AbstractClassWithMultipleConstructors + { + public AbstractClassWithMultipleConstructors() { } + + public AbstractClassWithMultipleConstructors(int a) { } + + public AbstractClassWithMultipleConstructors(string b) { } + + public int Property { get; } + } + + public sealed class SealedClass + { + public int Property { get; } + } + + public class NoParameterlessConstructorClass + { + public NoParameterlessConstructorClass(int a) { } + } + + public abstract class AbstractNoParameterlessConstructorClass + { + public AbstractNoParameterlessConstructorClass(int a) { } + } + + public class PrivateParameterlessConstructorClass + { + private PrivateParameterlessConstructorClass() { } + } + + public abstract class AbstractPrivateParameterlessConstructorClass + { + private AbstractPrivateParameterlessConstructorClass() { } + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = Mock.Of(); + """, + + """ + var mock = Mock.Of(); + """, + + """ + var mock = Mock.Of(sc => sc.Property == 1234); + """, + + """ + var mock = Mock.Of(sc => sc.Property == 1234); + """, + + """ + var mock = Mock.Of(); + """, + + """ + var mock = Mock.Of(sc => sc.Property == 1234); + """, + + """ + var mock = Mock.Of(); + """, + + """ + var mock = Mock.Of(MockBehavior.Strict); + """, + + """ + var mock = Mock.Of(); + """, + + """ + var mock = Mock.Of(MockBehavior.Strict); + """, - [Theory] - [InlineData("")] - [InlineData("abstract")] - public async Task NoParameterLessConstructor_DiagnosticReported(string classModifiers) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + """ + var mock = Mock.Of(sc => sc.Property == 1234); + """, - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of<{|PosInfoMoq2010:MockClass|}>(); - } - } + """ + var mock = Mock.Of(sc => sc.Property == 1234, MockBehavior.Strict); + """, + + """ + var mock = Mock.Of(sc => sc.Property == 1234); + """, + + """ + var mock = Mock.Of(sc => sc.Property == 1234, MockBehavior.Strict); + """, + + // Ignored by the analysis because it is not a Mock.Of() call. + """ + string.Format("Ignored"); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = Mock.Of<{|PosInfoMoq2009:SealedClass|}>(); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2009:SealedClass|}>(sc => sc.Property == 1234); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2009:string|}>(); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2009:string|}>(MockBehavior.Strict); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2009:string|}>(sc => sc.Length == 1234); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2009:string|}>(sc => sc.Length == 1234, MockBehavior.Strict); + """, + + """ + var mock = Mock.Of(({|PosInfoMoq2009:string|} sc) => sc.Length == 1234); + """, + + """ + var mock = Mock.Of(({|PosInfoMoq2009:string|} sc) => sc.Length == 1234, MockBehavior.Strict); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2010:NoParameterlessConstructorClass|}>(); + """, + + """ + var mock = Mock.Of<{|PosInfoMoq2010:AbstractNoParameterlessConstructorClass|}>(); + """, - public " + classModifiers + @" class MockClass - { - public MockClass(int a) { } - } - }"; + """ + var mock = Mock.Of(({|PosInfoMoq2010:NoParameterlessConstructorClass|} m) => true); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = Mock.Of(({|PosInfoMoq2010:AbstractNoParameterlessConstructorClass|} m) => true); + """, - [Theory] - [InlineData("")] - [InlineData("abstract")] - public async Task NoParameterLessConstructor_WithExpression_DiagnosticReported(string classModifiers) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + """ + var mock = Mock.Of<{|PosInfoMoq2010:PrivateParameterlessConstructorClass|}>(); + """, - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(({|PosInfoMoq2010:MockClass|} m) => true); - } - } + """ + var mock = Mock.Of<{|PosInfoMoq2010:AbstractPrivateParameterlessConstructorClass|}>(); + """, - public " + classModifiers + @" class MockClass - { - public MockClass(int a) { } - } - }"; + """ + var mock = Mock.Of(({|PosInfoMoq2010:PrivateParameterlessConstructorClass|} m) => true); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = Mock.Of(({|PosInfoMoq2010:AbstractPrivateParameterlessConstructorClass|} m) => true); + """, + ]; [Theory] - [InlineData("")] - [InlineData("abstract")] - public async Task PrivateParameterLessConstructor_DiagnosticReported(string classModifiers) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { public void TestMethod() { - var mock = Mock.Of<{|PosInfoMoq2010:MockClass|}>(); + {{code}} } } - public " + classModifiers + @" class MockClass - { - private MockClass() { } - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } [Theory] - [InlineData("")] - [InlineData("abstract")] - public async Task PrivateParameterLessConstructor_WithExpression_DiagnosticReported(string classModifiers) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - using System; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock = Mock.Of(({|PosInfoMoq2010:MockClass|} m) => true); + {{code}} } } - public " + classModifiers + @" class MockClass - { - private MockClass() { } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - var mock = Mock.Of(); - } - } - - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public static class Mock - { - public static T Of() { return default; } - } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index d6d0a16..92c2c25 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -15,6 +15,22 @@ namespace FakeMoqLibrary using System; using System.Linq.Expressions; + public enum MockBehavior + { + Strict, + } + + public static class Mock + { + public static T Of() { return default; } + + public static T Of(MockBehavior behavior) { return default; } + + public static T Of(Expression> predicate) { return default; } + + public static T Of(Expression> predicate, MockBehavior behavior) { return default; } + } + public class Mock { public void As() { } From bf32a6e4ac5aaf5d7fbd9c9b0a34a091ccf10175 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 18:35:17 +0200 Subject: [PATCH 04/30] Refactoring of the VerifyStaticMethodsRequiresMockParametersAnalyzerTest unit test --- ...thodsRequiresMockParametersAnalyzerTest.cs | 119 ++++++++---------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 8 +- 2 files changed, 61 insertions(+), 66 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/VerifyStaticMethodsRequiresMockParametersAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/VerifyStaticMethodsRequiresMockParametersAnalyzerTest.cs index db15b17..aa664e2 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/VerifyStaticMethodsRequiresMockParametersAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/VerifyStaticMethodsRequiresMockParametersAnalyzerTest.cs @@ -6,31 +6,62 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class VerifyStaticMethodsRequiresMockParametersAnalyzerTest { - [Fact] - public async Task StaticVerifyAndVerifyAllWithParameters_NoDiagnosticReported() + public static TheoryData ValidTestCases => + [ + """ + var mock1 = new Mock(); + Mock.Verify(mock1); + """, + + """ + var mock1 = new Mock(); + Mock.VerifyAll(mock1); + """, + + """ + var mock1 = new Mock(); + var mock2 = new Mock(); + Mock.Verify(mock1, mock2); + """, + + """ + var mock1 = new Mock(); + var mock2 = new Mock(); + Mock.VerifyAll(mock1, mock2); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + Mock.{|PosInfoMoq1008:Verify()|}; + """, + + """ + Mock.{|PosInfoMoq1008:VerifyAll()|}; + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - var mock2 = new Mock(); - - Mock.Verify(mock1); - Mock.VerifyAll(mock1); - Mock.Verify(mock1, mock2); - Mock.VerifyAll(mock1, mock2); + {{code}} } } @@ -38,26 +69,28 @@ public interface I { int TestMethod(); } - }"; + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task StaticVerifyAndVerifyAllWithNoParameters_DiagnosticReported() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - using System; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - Mock.{|#0:Verify()|#0}; - Mock.{|#1:VerifyAll()|#1}; + {{code}} } } @@ -65,52 +98,10 @@ public interface I { int TestMethod(); } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(VerifyStaticMethodsRequiresMockParametersAnalyzer.Rule) - .WithLocation(0) - .WithArguments("Verify"), - new DiagnosticResult(VerifyStaticMethodsRequiresMockParametersAnalyzer.Rule) - .WithLocation(1) - .WithArguments("VerifyAll"), - ]); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - } - } - - public interface I - { - void Method(); - } } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - - public void Verify(System.Action _) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 92c2c25..9c0e395 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -20,7 +20,7 @@ public enum MockBehavior Strict, } - public static class Mock + public abstract class Mock { public static T Of() { return default; } @@ -29,9 +29,13 @@ public static class Mock public static T Of(Expression> predicate) { return default; } public static T Of(Expression> predicate, MockBehavior behavior) { return default; } + + public static void Verify(params Mock[] mocks) { } + + public static void VerifyAll(params Mock[] mocks) { } } - public class Mock + public class Mock : Mock { public void As() { } From 3dc35d8b330d34e48ccbeb6584a7f701842c88a6 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 18:39:36 +0200 Subject: [PATCH 05/30] Refactoring of the VerifyMustHaveTimesParameterAnalyzerTest unit test --- ...erifyMustHaveTimesParameterAnalyzerTest.cs | 296 +++++++++--------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 36 +++ 2 files changed, 183 insertions(+), 149 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustHaveTimesParameterAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustHaveTimesParameterAnalyzerTest.cs index c924f96..82af1e9 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustHaveTimesParameterAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustHaveTimesParameterAnalyzerTest.cs @@ -6,19 +6,147 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class VerifyMustHaveTimesParameterAnalyzerTest { - [Fact] - public async Task TimesExplicitelySet_Verify_NoDiagnosticReported() + public static TheoryData ValidTestCases => + [ + """ + mock.Verify(); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.AtLeast(15)); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Exactly(1)); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Never); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Never()); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Once); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Once()); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.AtLeast(15), "Failed message ignored"); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Exactly(1), "Failed message ignored"); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Never, "Failed message ignored"); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Never(), "Failed message ignored"); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Once, "Failed message ignored"); + """, + + """ + mock.Verify(i => i.TestMethod(), Times.Once(), "Failed message ignored"); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.AtLeast(15)); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Exactly(1)); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Never); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Never()); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Once); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Once()); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.AtLeast(15), "Failed message ignored"); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Exactly(1), "Failed message ignored"); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Never, "Failed message ignored"); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Never(), "Failed message ignored"); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Once, "Failed message ignored"); + """, + + """ + mock.Setup(i => i.TestMethod()).Verifiable(Times.Once(), "Failed message ignored"); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + mock.{|PosInfoMoq1007:Verify|}(i => i.TestMethod()); + """, + + """ + mock.{|PosInfoMoq1007:Verify|}(i => i.TestMethod(), "Failed message ignored"); + """, + + """ + mock.Setup(m => m.TestMethod()).{|PosInfoMoq1007:Verifiable|}(); + """, + + """ + mock.Setup(m => m.TestMethod()).{|PosInfoMoq1007:Verifiable|}("Failed message ignored"); + """, + + """ + var strictMock = new Mock(MockBehavior.Strict); + strictMock.{|PosInfoMoq1007:Verify|}(i => i.Method()); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { @@ -26,119 +154,32 @@ public void TestMethod() { var mock = new Mock(); - mock.Verify(); - - mock.Verify(i => i.TestMethod(), Times.AtLeast(15)); - mock.Verify(i => i.TestMethod(), Times.Exactly(1)); - mock.Verify(i => i.TestMethod(), Times.Never); - mock.Verify(i => i.TestMethod(), Times.Never()); - mock.Verify(i => i.TestMethod(), Times.Once); - mock.Verify(i => i.TestMethod(), Times.Once()); - - mock.Verify(i => i.TestMethod(), Times.AtLeast(15), ""Failed message ignored""); - mock.Verify(i => i.TestMethod(), Times.Exactly(1), ""Failed message ignored""); - mock.Verify(i => i.TestMethod(), Times.Never, ""Failed message ignored""); - mock.Verify(i => i.TestMethod(), Times.Never(), ""Failed message ignored""); - mock.Verify(i => i.TestMethod(), Times.Once, ""Failed message ignored""); - mock.Verify(i => i.TestMethod(), Times.Once(), ""Failed message ignored""); + {{code}} } } public interface I { int TestMethod(); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task TimesExplicitelySet_Verifiable_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(); - - mock.Setup(i => i.TestMethod()).Verifiable(Times.AtLeast(15)); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Exactly(1)); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Never); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Never()); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Once); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Once()); - - mock.Setup(i => i.TestMethod()).Verifiable(Times.AtLeast(15), ""Failed message ignored""); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Exactly(1), ""Failed message ignored""); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Never, ""Failed message ignored""); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Never(), ""Failed message ignored""); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Once, ""Failed message ignored""); - mock.Setup(i => i.TestMethod()).Verifiable(Times.Once(), ""Failed message ignored""); - } - } - public interface I - { - int TestMethod(); + void Method(); } - }"; + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task TimesExplicitelyNotSet_Verify_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(); - - mock.{|#0:Verify|#0}(i => i.TestMethod()); - mock.{|#1:Verify|#1}(i => i.TestMethod(), ""Failed message ignored""); - } - } - - public interface I - { - int TestMethod(); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(VerifyMustHaveTimesParameterAnalyzer.Rule) - .WithLocation(0) - .WithArguments("Verify"), - new DiagnosticResult(VerifyMustHaveTimesParameterAnalyzer.Rule) - .WithLocation(1) - .WithArguments("Verify"), - ]); - } - - [Fact] - public async Task TimesExplicitelyNotSet_DiagnosticReported() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - using System; + using FakeMoqLibrary; public class TestClass { @@ -146,63 +187,20 @@ public void TestMethod() { var mock = new Mock(); - mock.Setup(m => m.TestMethod()).{|#0:Verifiable|#0}(); - mock.Setup(m => m.TestMethod()).{|#1:Verifiable|#1}(""Failed message ignored""); + {{code}} } } public interface I { int TestMethod(); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(VerifyMustHaveTimesParameterAnalyzer.Rule) - .WithLocation(0) - .WithArguments("Verifiable"), - new DiagnosticResult(VerifyMustHaveTimesParameterAnalyzer.Rule) - .WithLocation(1) - .WithArguments("Verifiable"), - ]); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Verify(i => i.Method()); - } - } - public interface I - { void Method(); } } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - - public void Verify(System.Action _) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 9c0e395..124a1a6 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -20,6 +20,28 @@ public enum MockBehavior Strict, } + public struct Times + { + public static Times AtLeast(int callCount) { return default; } + + public static Times Exactly(int callCount) { return default; } + + public static Times Never() { return default; } + + public static Times Once() { return default; } + } + + public class SetupResult + { + public void Verifiable() { } + + public void Verifiable(string failMessage) { } + + public void Verifiable(Times times, string failMessage = null) { } + + public void Verifiable(Func times, string failMessage = null) { } + } + public abstract class Mock { public static T Of() { return default; } @@ -37,15 +59,29 @@ public static void VerifyAll(params Mock[] mocks) { } public class Mock : Mock { + public Mock() { } + + public Mock(MockBehavior behavior) { } + public void As() { } public void Setup(Expression> expression) { } + public SetupResult Setup(Expression> expression) { return default; } + public void SetupSet(Action action) { } public void SetupSet(Action action) { } public void SetupSet(Func action) { } + + public void Verify() { } + + public void Verify(Expression> expression, string failMessage = null) { } + + public void Verify(Expression> expression, Times times, string failMessage = null) { } + + public void Verify(Expression> expression, Func times, string failMessage = null) { } } } """; From 13a601bdd5f59077ef6184d84c49f9ab40fe35d6 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 21:44:11 +0200 Subject: [PATCH 06/30] Refactoring of the ConstructorArgumentsAnalyzerTest unit test --- .../ConstructorArgumentsAnalyzerTest.cs | 995 +++++------------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 6 + 2 files changed, 282 insertions(+), 719 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/ConstructorArgumentsAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/ConstructorArgumentsAnalyzerTest.cs index 628618f..a830494 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/ConstructorArgumentsAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/ConstructorArgumentsAnalyzerTest.cs @@ -6,644 +6,365 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class ConstructorArgumentsAnalyzerTest { - [Fact] - public async Task NoMock() - { - var source = @" - namespace ConsoleApplication1 - { - public class TestClass - { - public void TestMethod() - { - var obj = new object(); - } - } + private const string TestTypes = + """ + public delegate void D(); - public class C - { - } - }"; + public interface I { } - await Verifier.VerifyAnalyzerAsync(source); - } + public interface InterfaceWithoutConstructor { } - [Fact] - public async Task Interface_WithNotMockableType() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public class WithoutDeclaredConstructor { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - } - } + public abstract class AbstractWithoutDeclaredConstructor { } - public delegate void I(); - }"; + public class WithParameterlessConstructor + { + public WithParameterlessConstructor() { } + } - await Verifier.VerifyAnalyzerAsync(source); - } + public class WithPrivateParameterlessConstructor + { + private WithPrivateParameterlessConstructor() { } + } - [Fact] - public async Task Interface_NoMock() - { - var source = @" - namespace ConsoleApplication1 - { - public class TestClass - { - public void TestMethod() - { - var obj = new object(); - } - } + public class MatchingConstructors + { + public MatchingConstructors(int a) { } - public interface I - { - } - }"; + public MatchingConstructors(int a, string b) { } - await Verifier.VerifyAnalyzerAsync(source); - } + public MatchingConstructors(int a, object b) { } - [Fact] - public async Task Interface_WithNoArgument() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public MatchingConstructors(int a, int[] b, int c) { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - } - } + public MatchingConstructors(int a, object b, int c, System.IDisposable d) { } - public interface I - { - } - }"; + public MatchingConstructors(string[] array) { } + } - await Verifier.VerifyAnalyzerAsync(source); - } + public class WithPrivateConstructors + { + private WithPrivateConstructors(int a) { } - [Fact] - public async Task Interface_WithoutBehaviorStrict() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + private WithPrivateConstructors(int a, string b) { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock({|#0:1|}, {|#1:2|}); - } - } + private WithPrivateConstructors(int a, object b) { } - public interface I - { - } - }"; + private WithPrivateConstructors(int a, int[] b, int c) { } - await Verifier.VerifyAnalyzerAsync( - source, - new DiagnosticResult(ConstructorArgumentsAnalyzer.ConstructorArgumentsCanBePassedToInterfaceRule) - .WithLocation(0).WithArguments("1") - .WithLocation(1).WithArguments("2")); - } + private WithPrivateConstructors(int a, object b, int c, System.IDisposable d) { } + } - [Fact] - public async Task Interface_WithBehaviorStrict() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public class StrictMatchingConstructors + { + public StrictMatchingConstructors(int a) { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict, {|#0:1|}, {|#1:2|}); - } - } + public StrictMatchingConstructors(int a, string b) { } - public interface I - { - } - }"; + public StrictMatchingConstructors(int a, object c) { } - await Verifier.VerifyAnalyzerAsync( - source, - new DiagnosticResult(ConstructorArgumentsAnalyzer.ConstructorArgumentsCanBePassedToInterfaceRule) - .WithLocation(0).WithArguments("1") - .WithLocation(1).WithArguments("2")); - } + public StrictMatchingConstructors(int a, object b, int c, System.IDisposable d) { } - [Fact] - public async Task Arguments_Empty() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public StrictMatchingConstructors(string[] array) { } + } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - } - } + public class MismatchingConstructors + { + public MismatchingConstructors(int a) { } - public class C - { - public C() - { - } - } - }"; + public MismatchingConstructors(int a, string b) { } - await Verifier.VerifyAnalyzerAsync(source); - } + public MismatchingConstructors(int a, object c) { } - [Fact] - public async Task Arguments_Empty_WithPrivateConstructor() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public MismatchingConstructors(int a, object b, int c, System.IDisposable d) { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock{|PosInfoMoq2011:()|}; - } - } + public MismatchingConstructors(string[] array, int b) { } + } - public class C - { - private C() - { - } - } - }"; + public class StrictMismatchingConstructors + { + public StrictMismatchingConstructors(int a) { } - await Verifier.VerifyAnalyzerAsync(source); - } + public StrictMismatchingConstructors(int a, string b) { } - [Theory] - [InlineData("1")] - [InlineData("1, \"B\"")] - [InlineData("1, null")] - [InlineData("default, \"B\"")] - [InlineData("(int)default, default")] - [InlineData("default, null, 1234")] - [InlineData("1, \"An object\", 3, null")] - [InlineData("1, \"An object\", 3, new System.IO.MemoryStream()")] - [InlineData("[new string[] { \"A\", \"B\" }]")] - [InlineData("new object[] { new string[] { \"A\", \"B\" } }")] - [InlineData("[1]")] - [InlineData("[1, \"A\"]")] - public async Task Arguments_Match(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public StrictMismatchingConstructors(int a, object c) { } - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(" + parameters + @"); - } - } + public StrictMismatchingConstructors(string[] array, int b) { } + } - public class C - { - public C(int a) - { - } + public class WithOptionalParameters + { + public WithOptionalParameters(int a = 0, int b = 1, int c = 2, int d = 3) { } + } - public C(int a, string b) - { - } + public class WithRequiredArguments : I + { + public WithRequiredArguments(int a) { } - public C(int a, object b) - { - } + public WithRequiredArguments(int a, string b) { } - public C(int a, int[] b, int c) - { - } + public WithRequiredArguments(int a, object c) { } + } + """; - public C(int a, object b, int c, System.IDisposable d) - { - } + public static TheoryData ValidTestCases => + [ + """ + var obj = new object(); + """, - public C(string[] array) - { - } - } - }"; + """ + var mock = new Mock(); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(); + """, - [Theory] - [InlineData("1, \"B\"")] - [InlineData("1, null")] - [InlineData("default, \"B\"")] - [InlineData("(int)default, default")] - [InlineData("default, null, 1234")] - [InlineData("1, \"An object\", 3, null")] - [InlineData("1, \"An object\", 3, new System.IO.MemoryStream()")] - public async Task Arguments_Match_WithPrivateConstructor(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock(); + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock({|PosInfoMoq2011:" + parameters + @"|}); - } - } + """ + var mock = new Mock(1); + """, - public class C - { - private C(int a) - { - } + """ + var mock = new Mock(1, "B"); + """, - private C(int a, string b) - { - } + """ + var mock = new Mock(1, null); + """, - private C(int a, object b) - { - } + """ + var mock = new Mock(default, "B"); + """, - private C(int a, int[] b, int c) - { - } + """ + var mock = new Mock((int)default, default); + """, - private C(int a, object b, int c, System.IDisposable d) - { - } - } - }"; + """ + var mock = new Mock(default, null, 1234); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(1, "An object", 3, null); + """, - [Theory] - [InlineData("class")] - [InlineData("abstract class")] - [InlineData("interface")] - public async Task Arguments_Match_WithNoConstructor(string type) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock(1, "An object", 3, new System.IO.MemoryStream()); + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(); - } - } + """ + var mock = new Mock([new string[] { "A", "B" }]); + """, - public " + type + @" ClassWithNoConstructor { } - }"; + """ + var mock = new Mock(new object[] { new string[] { "A", "B" } }); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock([1]); + """, - [Theory] - [InlineData("1, \"B\"")] - [InlineData("1, \"An object\", 3, null")] - [InlineData("1, \"An object\", 3, new System.IO.MemoryStream()")] - [InlineData("[1]")] - [InlineData("[1, \"A\"]")] - public async Task Arguments_Match_WithMockBehavior(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock([1, "A"]); + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(MockBehavior.Strict, " + parameters + @"); - } - } + """ + var mock = new Mock(); + """, - public class C - { - public C(int a) - { - } + """ + var mock = new Mock(); + """, - public C(int a, string b) - { - } + """ + var mock = new Mock(); + """, - public C(int a, object c) - { - } + """ + var mock = new Mock(MockBehavior.Strict, 1, "B"); + """, - public C(int a, object b, int c, System.IDisposable d) - { - } + """ + var mock = new Mock(MockBehavior.Strict, 1, "An object", 3, null); + """, + + """ + var mock = new Mock(MockBehavior.Strict, 1, "An object", 3, new System.IO.MemoryStream()); + """, - public C(string[] array) - { - } - } - }"; + """ + var mock = new Mock(MockBehavior.Strict, [1]); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(MockBehavior.Strict, [1, "A"]); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + """, - [Theory] - [InlineData("class")] - [InlineData("abstract class")] - [InlineData("interface")] - public async Task Arguments_Match_WithMockBehavior_WithNoConstructor(string type) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock(MockBehavior.Strict); + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(MockBehavior.Strict); - } - } + """ + var mock = new Mock(() => new WithRequiredArguments(10)); + """, - public " + type + @" ClassWithNoConstructor { } - }"; + """ + var mock = new Mock(() => new WithRequiredArguments(10), MockBehavior.Strict); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = new Mock({|PosInfoMoq2004:1|}, 2); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2004:1|}, 2); + """, - [Theory] - [InlineData("1, 2, 3")] - [InlineData("null")] - [InlineData("\"The string\", 2")] - [InlineData("1, 2, 3, \"The string\"")] - [InlineData("new int[] { 1, 2 }, 1000")] - [InlineData("new object[] { \"A\", \"B\" }, 1000")] - public async Task Arguments_NotMatch(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock{|PosInfoMoq2011:()|}; + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock({|PosInfoMoq2005:" + parameters + @"|}); - } - } + """ + var mock = new Mock({|PosInfoMoq2011:1, "B"|}); + """, - public class C - { - public C(int a) - { - } + """ + var mock = new Mock({|PosInfoMoq2011:1, null|}); + """, - public C(int a, string b) - { - } + """ + var mock = new Mock({|PosInfoMoq2011:default, "B"|}); + """, + + """ + var mock = new Mock({|PosInfoMoq2011:(int)default, default|}); + """, - public C(int a, object c) - { - } + """ + var mock = new Mock({|PosInfoMoq2011:default, null, 1234|}); + """, - public C(int a, object b, int c, System.IDisposable d) - { - } + """ + var mock = new Mock({|PosInfoMoq2011:1, "An object", 3, null|}); + """, - public C(string[] array, int b) - { - } - } - }"; + """ + var mock = new Mock({|PosInfoMoq2011:1, "An object", 3, new System.IO.MemoryStream()|}); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock({|PosInfoMoq2005:1, 2, 3|}); + """, - [Theory] - [InlineData("[]")] - public async Task Arguments_NotMatch_EmptyArray(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock({|PosInfoMoq2005:null|}); + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock{|PosInfoMoq2005:(" + parameters + @")|}; - } - } + """ + var mock = new Mock({|PosInfoMoq2005:"The string", 2|}); + """, - public class C - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { - } + """ + var mock = new Mock({|PosInfoMoq2005:1, 2, 3, "The string"|}); + """, - public C(string[] array, int b) - { - } - } - }"; + """ + var mock = new Mock({|PosInfoMoq2005:new int[] { 1, 2 }, 1000|}); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock({|PosInfoMoq2005:new object[] { "A", "B" }, 1000|}); + """, - [Fact] - public async Task Arguments_WithDefaultParameters() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock{|PosInfoMoq2005:([])|}; + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock{|PosInfoMoq2005:()|}; - } - } + """ + var mock = new Mock{|PosInfoMoq2005:()|}; + """, - public class C - { - public C(int a = 0, int b = 1, int c = 2, int d = 3) - { - } - } - }"; + """ + var mock = new Mock({|PosInfoMoq2005:1, 2|}); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:1, 2, 3|}); + """, - [Fact] - public async Task Arguments_NotMatch_WithNoConstructor() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:null|}); + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock({|PosInfoMoq2005:1, 2|}); - } - } + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:"The string", 2|}); + """, - public class ClassWithNoConstructor { } - }"; + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:1, 2, 3, "The string"|}); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:new int[] { 1, 2 }, 1000|}); + """, - [Theory] - [InlineData("1, 2, 3")] - [InlineData("null")] - [InlineData("\"The string\", 2")] - [InlineData("1, 2, 3, \"The string\"")] - [InlineData("new int[] { 1, 2 }, 1000")] - public async Task Arguments_NotMatch_WithMockBehavior(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """ + var mock = new Mock{|PosInfoMoq2005:(MockBehavior.Strict, [])|}; + """, - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:" + parameters + @"|}); - } - } + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:1, 2|}); + """, - public class C - { - public C(int a) - { - } + """ + var mock = new Mock{|PosInfoMoq2005:()|}; + """, - public C(int a, string b) - { - } + """ + var mock = new Mock{|PosInfoMoq2005:(MockBehavior.Strict)|}; + """, - public C(int a, object c) - { - } + """ + var mock = new Mock<{|PosInfoMoq2016:I|}>(() => new WithRequiredArguments(10)); + """, - public C(string[] array, int b) - { - } - } - }"; + """ + var mock = new Mock<{|PosInfoMoq2016:I|}>(() => new WithRequiredArguments(10), MockBehavior.Strict); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:1, 2, 3|}); + """, + ]; [Theory] - [InlineData("[]")] - public async Task Arguments_NotMatch_WithMockBehavior_EmptyArray(string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock = new Mock{|PosInfoMoq2005:(MockBehavior.Strict, " + parameters + @")|}; - } - } - - public class C - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { - } - - public C(string[] array, int b) - { - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Arguments_NotMatch_WithMockBehavior_WithNoConstructor() + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -652,205 +373,41 @@ public class TestClass { public void TestMethod() { - var mock = new Mock(MockBehavior.Strict, {|PosInfoMoq2005:1, 2|}); + {{code}} } } - - public class ClassWithNoConstructor { } - }"; - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Arguments_CountNotMatch() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock{|PosInfoMoq2005:()|}; - } - } - - public class C - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Arguments_CountNotMatch_MockBehavior() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock{|PosInfoMoq2005:(MockBehavior.Strict)|}; - } - } - - public class C - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { - } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData(", MockBehavior.Strict")] - public async Task Arguments_WithFactory(string behavior) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(() => new C(10)" + behavior + @"); - } - } - - public class C - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { - } - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } [Theory] - [InlineData("")] - [InlineData(", MockBehavior.Strict")] - public async Task Arguments_WithFactory_NotClass(string behavior) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock<{|PosInfoMoq2016:I|}>(() => new C(10)" + behavior + @"); - } - } - - public interface I - { - } - - public class C : I - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { + {{code}} } } - }"; - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict, 1, 2, 3); - } - } - - public class C - { - public C(int a) - { - } - - public C(int a, string b) - { - } - - public C(int a, object c) - { - } - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _, int a, int b, int c) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 124a1a6..0a46742 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -63,6 +63,12 @@ public Mock() { } public Mock(MockBehavior behavior) { } + public Mock(params object[] args) { } + + public Mock(MockBehavior behavior, params object[] args) { } + + public Mock(Expression> newExpression, MockBehavior behavior = default) { } + public void As() { } public void Setup(Expression> expression) { } From 72101841e890b8d7e6e7d09e9d527f3b57ddae3b Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 21:49:10 +0200 Subject: [PATCH 07/30] Refactoring the ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest unit test --- ...tMatchMockedMethodArgumentsAnalyzerTest.cs | 225 ++++++++++-------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 10 + 2 files changed, 133 insertions(+), 102 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest.cs index 411bd40..3214c25 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest.cs @@ -6,142 +6,163 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class ItArgumentsMustMatchMockedMethodArgumentsAnalyzerTest { - [Fact] - public async Task Match_NoDiagnosticReported() + private const string TestTypes = + """ + public interface I + { + void NoParametersMethod(); + + void TestMethod(); + + void TestMethod(int? a, int b, string c); + + void TestMethod(int? a, int b, string c, int d); + + void TestMethodWithBaseClass(BaseClass a); + } + + public class C + { + public static int OtherMethod() => default; + } + + public abstract class BaseClass + { + public int Property { get; set; } + } + + public class InheritedClass : BaseClass + { + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.Setup(m => m.NoParametersMethod()); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethod(It.IsAny(), 1, "Ignored", C.OtherMethod())); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethod(It.Is(p => p == 10), 1, "Ignored", C.OtherMethod())); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethod(It.Is(10, EqualityComparer.Default), 1, "Ignored", C.OtherMethod())); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethodWithBaseClass(null)); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethodWithBaseClass(It.IsAny())); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethodWithBaseClass(It.IsAny())); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethodWithBaseClass(It.Is(c => c.Property == 10))); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethodWithBaseClass(It.Is(c => c.Property == 10))); + """, + + """ + var mock1 = new Mock(MockBehavior.Strict); + mock1.Setup(m => m.TestMethod()); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethod({|PosInfoMoq1006:It.IsAny()|}, 1, "Ignored")); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethod({|PosInfoMoq1006:It.Is(p => p == 10)|}, 1, "Ignored")); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.TestMethod({|PosInfoMoq1006:It.Is(10, EqualityComparer.Default)|}, 1, "Ignored")); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; using System.Collections.Generic; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - - mock1.Setup(m => m.NoParametersMethod()); - mock1.Setup(m => m.TestMethod(It.IsAny(), 1, ""Ignored"", C.OtherMethod())); - mock1.Setup(m => m.TestMethod(It.Is(p => p == 10), 1, ""Ignored"", C.OtherMethod())); - mock1.Setup(m => m.TestMethod(It.Is(10, EqualityComparer.Default), 1, ""Ignored"", C.OtherMethod())); - - mock1.Setup(m => m.TestMethodWithBaseClass(null)); - mock1.Setup(m => m.TestMethodWithBaseClass(It.IsAny())); - mock1.Setup(m => m.TestMethodWithBaseClass(It.IsAny())); - mock1.Setup(m => m.TestMethodWithBaseClass(It.Is(c => c.Property == 10))); - mock1.Setup(m => m.TestMethodWithBaseClass(It.Is(c => c.Property == 10))); - } - } - - public interface I - { - void NoParametersMethod(); - - void TestMethod(int? a, int b, string c, int d); - - void TestMethodWithBaseClass(BaseClass a); - } - - public class C - { - public static int OtherMethod() => default; - } - - public abstract class BaseClass - { - public int Property { get; set; } + {{code}} + } } - public class InheritedClass : BaseClass - { - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NotMatch_DiagnosticReported() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - using System; + using FakeMoqLibrary; using System.Collections.Generic; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Setup(m => m.TestMethod({|#0:It.IsAny()|#0}, 1, ""Ignored"")); - mock1.Setup(m => m.TestMethod({|#1:It.Is(p => p == 10)|#1}, 1, ""Ignored"")); - mock1.Setup(m => m.TestMethod({|#2:It.Is(10, EqualityComparer.Default)|#2}, 1, ""Ignored"")); - } - } - - public interface I - { - void TestMethod(int? a, int b, string c); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(ItArgumentsMustMatchMockedMethodArgumentsAnalyzer.Rule) - .WithLocation(0), - new DiagnosticResult(ItArgumentsMustMatchMockedMethodArgumentsAnalyzer.Rule) - .WithLocation(1), - new DiagnosticResult(ItArgumentsMustMatchMockedMethodArgumentsAnalyzer.Rule) - .WithLocation(2), - ]); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(m => m.TestMethod()); + {{code}} } } - public interface I - { - void TestMethod(); - } + {{TestTypes}} } - namespace OtherNamespace - { - using System; - - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup(Action act) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 0a46742..c6e3610 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -13,8 +13,18 @@ public static class MoqAnalyzersTests namespace FakeMoqLibrary { using System; + using System.Collections.Generic; using System.Linq.Expressions; + public static class It + { + public static TValue IsAny() { return default; } + + public static TValue Is(Expression> match) { return default; } + + public static TValue Is(TValue value, IEqualityComparer comparer) { return default; } + } + public enum MockBehavior { Strict, From 84c6fb074ce0757b3a14728e8193cf8dc6203fca Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 21:55:56 +0200 Subject: [PATCH 08/30] Refactoring SetupProtectedMustBeUsedWithProtectedOrInternalMembersAnalyzerTest --- ...hProtectedOrInternalMembersAnalyzerTest.cs | 485 +++++++++--------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 15 + 2 files changed, 270 insertions(+), 230 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/SetupProtectedMustBeUsedWithProtectedOrInternalMembersAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/SetupProtectedMustBeUsedWithProtectedOrInternalMembersAnalyzerTest.cs index bbd918c..435bd01 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/SetupProtectedMustBeUsedWithProtectedOrInternalMembersAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/SetupProtectedMustBeUsedWithProtectedOrInternalMembersAnalyzerTest.cs @@ -10,313 +10,338 @@ namespace PosInformatique.Moq.Analyzers.Tests public class SetupProtectedMustBeUsedWithProtectedOrInternalMembersAnalyzerTest { - [Fact] - public async Task NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using Moq.Protected; - using System; + private const string TestTypes = + """ + public abstract class C : BaseClass + { + // Virtual + protected virtual void ProtectedVirtualMethod() { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Protected().Setup(""ProtectedVirtualMethod""); - mock1.Protected().Setup(""ProtectedInternalVirtualMethod""); - mock1.Protected().Setup(""InternalVirtualMethod""); - mock1.Protected().Setup(""ProtectedAbstractMethod""); - mock1.Protected().Setup(""ProtectedInternalAbstractMethod""); - mock1.Protected().Setup(""InternalAbstractMethod""); - mock1.Protected().Setup(""ProtectedMethod""); - mock1.Protected().Setup(""ProtectedOverrideMethod""); - mock1.Protected().Setup(""ProtectedInternalOverrideMethod""); - mock1.Protected().Setup(""ProtectedInternalMethod""); - mock1.Protected().Setup(""InternalMethod""); - mock1.Protected().Setup(""InternalOverrideMethod""); - - mock1.Protected().Setup(""ProtectedVirtualMethodReturnValue""); - mock1.Protected().Setup(""ProtectedInternalVirtualMethodReturnValue""); - mock1.Protected().Setup(""InternalVirtualMethodReturnValue""); - mock1.Protected().Setup(""ProtectedAbstractMethodReturnValue""); - mock1.Protected().Setup(""ProtectedInternalAbstractMethodReturnValue""); - mock1.Protected().Setup(""InternalAbstractMethodReturnValue""); - mock1.Protected().Setup(""ProtectedOverrideMethodReturnValue""); - mock1.Protected().Setup(""ProtectedInternalOverrideMethodReturnValue""); - mock1.Protected().Setup(""InternalOverrideMethodReturnValue""); - mock1.Protected().Setup(""InternalMethodReturnValue""); - } - } + protected virtual int ProtectedVirtualMethodReturnValue() { return 10; } - public abstract class C : BaseClass - { - // Virtual - protected virtual void ProtectedVirtualMethod() { } + protected internal virtual void ProtectedInternalVirtualMethod() { } - protected virtual int ProtectedVirtualMethodReturnValue() { return 10;} + protected internal virtual int ProtectedInternalVirtualMethodReturnValue() { return 10; } - protected internal virtual void ProtectedInternalVirtualMethod() { } + internal virtual void InternalVirtualMethod() { } - protected internal virtual int ProtectedInternalVirtualMethodReturnValue() { return 10; } + internal virtual int InternalVirtualMethodReturnValue() { return 10; } - internal virtual void InternalVirtualMethod() { } + // Abstract + protected abstract void ProtectedAbstractMethod(); - internal virtual int InternalVirtualMethodReturnValue() { return 10; } + protected abstract int ProtectedAbstractMethodReturnValue(); - // Abstract - protected abstract void ProtectedAbstractMethod(); + protected internal abstract void ProtectedInternalAbstractMethod(); - protected abstract int ProtectedAbstractMethodReturnValue(); + protected internal abstract int ProtectedInternalAbstractMethodReturnValue(); - protected internal abstract void ProtectedInternalAbstractMethod(); + internal abstract void InternalAbstractMethod(); - protected internal abstract int ProtectedInternalAbstractMethodReturnValue(); + internal abstract int InternalAbstractMethodReturnValue(); - internal abstract void InternalAbstractMethod(); + // Override + protected override void ProtectedOverrideMethod() { } - internal abstract int InternalAbstractMethodReturnValue(); + protected override int ProtectedOverrideMethodReturnValue() { return 10; } - // Override - protected override void ProtectedOverrideMethod() { } + protected internal override void ProtectedInternalOverrideMethod() { } - protected override int ProtectedOverrideMethodReturnValue() { return 10; } + protected internal override int ProtectedInternalOverrideMethodReturnValue() { return 10; } - protected internal override void ProtectedInternalOverrideMethod() { } + internal override void InternalOverrideMethod() { } - protected internal override int ProtectedInternalOverrideMethodReturnValue() { return 10; } + internal override int InternalOverrideMethodReturnValue() { return 10; } - internal override void InternalOverrideMethod() { } + public virtual void TestMethodPublic() { } - internal override int InternalOverrideMethodReturnValue() { return 10; } - } - - public abstract class BaseClass - { - protected virtual void ProtectedOverrideMethod() { } + protected override sealed void TestMethod() { } - protected virtual int ProtectedOverrideMethodReturnValue() { return 10; } + protected void NonOverridableProtectedMethod() { } - protected virtual void ProtectedMethod() { } + protected internal void NonOverridableProtectedInternalMethod() { } - protected internal virtual void ProtectedInternalOverrideMethod() { } + internal void NonOverridableInternalMethod() { } - protected internal virtual int ProtectedInternalOverrideMethodReturnValue() { return 10; } + protected virtual int TestMethodProtectedReturnValue() { return 0; } - protected internal virtual void ProtectedInternalMethod() { } + protected virtual void TestMethodProtected() { } + } - internal virtual void InternalOverrideMethod() { } + public abstract class BaseClass + { + protected virtual void ProtectedOverrideMethod() { } - internal virtual int InternalOverrideMethodReturnValue() { return 10; } + protected virtual int ProtectedOverrideMethodReturnValue() { return 10; } - internal virtual void InternalMethod() { } + protected virtual void ProtectedMethod() { } - internal virtual int InternalMethodReturnValue() { return 10; } - } - }"; + protected internal virtual void ProtectedInternalOverrideMethod() { } - await Verifier.VerifyAnalyzerAsync(source); - } + protected internal virtual int ProtectedInternalOverrideMethodReturnValue() { return 10; } - [Fact] - public async Task PublicMethod_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using Moq.Protected; - using System; + protected internal virtual void ProtectedInternalMethod() { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Protected().Setup({|PosInfoMoq2006:""TestMethodPublic""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""TestMethodPublic""|}); - } - } + internal virtual void InternalOverrideMethod() { } - public class C - { - public virtual void TestMethodPublic() { } - } - }"; + internal virtual int InternalOverrideMethodReturnValue() { return 10; } - await Verifier.VerifyAnalyzerAsync(source); - } + internal virtual void InternalMethod() { } - [Fact] - public async Task SealedMethod_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using Moq.Protected; - using System; + internal virtual int InternalMethodReturnValue() { return 10; } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Protected().Setup({|PosInfoMoq2006:""TestMethod""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""TestMethod""|}); - } - } + protected abstract void TestMethod(); + } - public class C : BaseClass - { - protected override sealed void TestMethod() { } - } + public interface I + { + void TestMethodPublic(); + } + """; - public abstract class BaseClass - { - protected abstract void TestMethod(); - } - }"; + public static TheoryData ValidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedVirtualMethod"); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalVirtualMethod"); + """, - [Fact] - public async Task Interface_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using Moq.Protected; - using System; + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalVirtualMethod"); + """, - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Protected().Setup({|PosInfoMoq2006:""TestMethodPublic""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""TestMethodPublic""|}); - } - } + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedAbstractMethod"); + """, - public interface I - { - void TestMethodPublic(); - } - }"; + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalAbstractMethod"); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalAbstractMethod"); + """, - [Fact] - public async Task NonOverridableMethod_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using Moq.Protected; - using System; + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedMethod"); + """, - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Protected().Setup({|PosInfoMoq2006:""NonOverridableProtectedMethod""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""NonOverridableProtectedInternalMethod""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""NonOverridableInternalMethod""|}); - - mock1.Protected().Setup({|PosInfoMoq2006:""NonOverridableProtectedMethod""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""NonOverridableProtectedInternalMethod""|}); - mock1.Protected().Setup({|PosInfoMoq2006:""NonOverridableInternalMethod""|}); - } - } + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedOverrideMethod"); + """, - public class C - { - protected void NonOverridableProtectedMethod() { } - protected internal void NonOverridableProtectedInternalMethod() { } - internal void NonOverridableInternalMethod() { } - } - }"; + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalOverrideMethod"); + """, - await Verifier.VerifyAnalyzerAsync(source); - } + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalMethod"); + """, - [Fact] - public async Task ReturnMethodTypeNotMatching_DiagnosticReported() + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalMethod"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalOverrideMethod"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedVirtualMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalVirtualMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalVirtualMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedAbstractMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalAbstractMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalAbstractMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedOverrideMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("ProtectedInternalOverrideMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalOverrideMethodReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup("InternalMethodReturnValue"); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"TestMethodPublic"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"TestMethodPublic"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"TestMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"TestMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"TestMethodPublic"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"TestMethodPublic"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"NonOverridableProtectedMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"NonOverridableProtectedInternalMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"NonOverridableInternalMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"NonOverridableProtectedMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"NonOverridableProtectedInternalMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup({|PosInfoMoq2006:"NonOverridableInternalMethod"|}); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup<{|PosInfoMoq2015:long|}>("TestMethodProtectedReturnValue"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().Setup<{|PosInfoMoq2015:long|}>("TestMethodProtected"); + """, + + """ + var mock1 = new Mock(); + mock1.Protected().{|PosInfoMoq2015:Setup|}("TestMethodProtectedReturnValue"); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; using Moq.Protected; - using System; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Protected().Setup<{|PosInfoMoq2015:long|}>(""TestMethodProtectedReturnValue""); - mock1.Protected().Setup<{|PosInfoMoq2015:long|}>(""TestMethodProtected""); - mock1.Protected().{|PosInfoMoq2015:Setup|}(""TestMethodProtectedReturnValue""); + {{code}} } } - public class C - { - protected virtual int TestMethodProtectedReturnValue() { return 0; } - - protected virtual void TestMethodProtected() { } - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; + using FakeMoqLibrary.Protected; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Protected().Setup(""NonOverridableProtectedMethod""); + {{code}} } } - public class C - { - protected virtual void NonOverridableProtectedMethod() { } - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock() { } - - public IProtected Protected() { return null; } - } - - public interface IProtected - { - void Setup(string _); - } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index c6e3610..9aef08e 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -100,6 +100,21 @@ public void Verify(Expression> expression, Times times, string failMes public void Verify(Expression> expression, Func times, string failMessage = null) { } } } + + namespace FakeMoqLibrary.Protected + { + public static class ProtectedExtension + { + public static IProtectedMock Protected(this Mock mock) where T : class { return default; } + } + + public interface IProtectedMock where T : class + { + void Setup(string methodName, params object[] args); + + void Setup(string methodName, params object[] args); + } + } """; } } From a43ec19ad414d67a13cb847a582830bd5ae32293 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:03:06 +0200 Subject: [PATCH 09/30] Refactoring of the SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest unit test --- ...edOnlyForOverridableMembersAnalyzerTest.cs | 556 ++++++++---------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 4 + 2 files changed, 261 insertions(+), 299 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs index 413aacc..83a8437 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs @@ -10,359 +10,317 @@ namespace PosInformatique.Moq.Analyzers.Tests public class SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest { - [Fact] - public async Task Overridable_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod()); - mock1.Setup(i => i.TestProperty); - mock1.SetupSequence(i => i.TestMethod()); - mock1.SetupSequence(i => i.TestProperty); - mock1.SetupSet(i => i.TestProperty = ""Foobard""); - mock1.SetupSet(i => i.TestProperty = ""Foobard""); - mock1.Setup(i => i.InnerObject.VirtualMethod()); - mock1.Setup(i => i.InnerObject.VirtualProperty); - mock1.SetupSequence(i => i.InnerObject.VirtualMethod()); - mock1.SetupSequence(i => i.InnerObject.VirtualProperty); - mock1.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock1.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock1.Setup(i => i.InnerObject.AbstractMethod()); - mock1.Setup(i => i.InnerObject.AbstractProperty); - mock1.SetupSequence(i => i.InnerObject.AbstractMethod()); - mock1.SetupSequence(i => i.InnerObject.AbstractProperty); - mock1.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock1.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - - var mock2 = new Mock(); - mock2.Setup(i => i.VirtualMethod()); - mock2.Setup(i => i.VirtualProperty); - mock2.SetupSequence(i => i.VirtualMethod()); - mock2.SetupSequence(i => i.VirtualProperty); - mock2.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock2.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock2.Setup(i => i.InnerObject.VirtualMethod()); - mock2.Setup(i => i.InnerObject.VirtualProperty); - mock2.SetupSequence(i => i.InnerObject.VirtualMethod()); - mock2.SetupSequence(i => i.InnerObject.VirtualProperty); - mock2.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock2.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock2.Setup(i => i.InnerObject.AbstractMethod()); - mock2.Setup(i => i.InnerObject.AbstractProperty); - mock2.SetupSequence(i => i.InnerObject.AbstractMethod()); - mock2.SetupSequence(i => i.InnerObject.AbstractProperty); - mock2.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock2.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - - var mock3 = new Mock(); - mock3.Setup(i => i.VirtualMethod()); - mock3.Setup(i => i.VirtualProperty); - mock3.SetupSequence(i => i.VirtualMethod()); - mock3.SetupSequence(i => i.VirtualProperty); - mock3.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock3.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock3.Setup(i => i.AbstractMethod()); - mock3.Setup(i => i.AbstractProperty); - mock3.SetupSequence(i => i.AbstractMethod()); - mock3.SetupSequence(i => i.AbstractProperty); - mock3.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock3.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock3.Setup(i => i.InnerObject.VirtualMethod()); - mock3.Setup(i => i.InnerObject.VirtualProperty); - mock3.SetupSequence(i => i.InnerObject.VirtualMethod()); - mock3.SetupSequence(i => i.InnerObject.VirtualProperty); - mock3.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock3.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock3.Setup(i => i.InnerObject.AbstractMethod()); - mock3.Setup(i => i.InnerObject.AbstractProperty); - mock3.SetupSequence(i => i.InnerObject.AbstractMethod()); - mock3.SetupSequence(i => i.InnerObject.AbstractProperty); - mock3.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock3.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - - var mock4 = new Mock(); - mock4.Setup(i => i.VirtualMethod()); - mock4.Setup(i => i.VirtualProperty); - mock4.SetupSequence(i => i.VirtualMethod()); - mock4.SetupSequence(i => i.VirtualProperty); - mock4.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock4.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock4.Setup(i => i.AbstractMethod()); - mock4.Setup(i => i.AbstractProperty); - mock4.SetupSequence(i => i.AbstractMethod()); - mock4.SetupSequence(i => i.AbstractProperty); - mock4.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock4.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock4.Setup(i => i.InnerObject.VirtualMethod()); - mock4.Setup(i => i.InnerObject.VirtualProperty); - mock4.SetupSequence(i => i.InnerObject.VirtualMethod()); - mock4.SetupSequence(i => i.InnerObject.VirtualProperty); - mock4.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock4.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock4.Setup(i => i.InnerObject.AbstractMethod()); - mock4.Setup(i => i.InnerObject.AbstractProperty); - mock4.SetupSequence(i => i.InnerObject.AbstractMethod()); - mock4.SetupSequence(i => i.InnerObject.AbstractProperty); - mock4.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock4.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - - var mock5 = new Mock(); - mock5.Setup(i => i.VirtualMethod()); - mock5.Setup(i => i.VirtualProperty); - mock5.SetupSequence(i => i.VirtualMethod()); - mock5.SetupSequence(i => i.VirtualProperty); - mock5.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock5.SetupSet(i => i.VirtualProperty = ""Foobard""); - mock5.Setup(i => i.AbstractMethod()); - mock5.Setup(i => i.AbstractProperty); - mock5.SetupSequence(i => i.AbstractMethod()); - mock5.SetupSequence(i => i.AbstractProperty); - mock5.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock5.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock5.Setup(i => i.InnerObject.VirtualMethod()); - mock5.Setup(i => i.InnerObject.VirtualProperty); - mock5.SetupSequence(i => i.InnerObject.VirtualMethod()); - mock5.SetupSequence(i => i.InnerObject.VirtualProperty); - mock5.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock5.SetupSet(i => i.InnerObject.VirtualProperty = ""Foobard""); - mock5.Setup(i => i.InnerObject.AbstractMethod()); - mock5.Setup(i => i.InnerObject.AbstractProperty); - mock5.SetupSequence(i => i.InnerObject.AbstractMethod()); - mock5.SetupSequence(i => i.InnerObject.AbstractProperty); - mock5.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - mock5.SetupSet(i => i.InnerObject.AbstractProperty = ""Foobard""); - } - } + private const string TestTypes = + """ + public interface I + { + int TestMethod(); - public interface I - { - int TestMethod(); + void Method(); - string TestProperty { get; set; } + string TestProperty { get; set; } - InnerObject InnerObject { get; } - } + InnerObject InnerObject { get; } + } - public class StandardClass - { - public virtual void VirtualMethod() { } + public class StandardClass + { + public virtual void VirtualMethod() { } - public virtual string VirtualProperty { get => null; set { } } + public virtual string VirtualProperty { get => null; set { } } - public virtual InnerObject InnerObject { get => null; set { } } - } + public virtual InnerObject InnerObject { get => null; set { } } - public abstract class AbstractClass - { - public virtual void VirtualMethod() { } + public void Method() { } - public virtual string VirtualProperty { get => null; set { } } + public string Property { get => null; set { } } - public abstract void AbstractMethod(); + public static void StaticMethod() { } - public abstract string AbstractProperty { get; set; } + public InnerObject NonOverridableInnerObject => null; - public abstract InnerObject InnerObject { get; } - } + public AbstractInnerObject AbstractInnerObject => null; - public class InheritedFromAbstractClass : AbstractClass - { - public override void AbstractMethod() { } + public SealedInnerObject SealedInnerObject => null; + } - public override string AbstractProperty { get => null; set { } } + public abstract class AbstractClass + { + public virtual void VirtualMethod() { } - public override void VirtualMethod() { } + public virtual string VirtualProperty { get => null; set { } } - public override string VirtualProperty { get => null; set { } } + public abstract void AbstractMethod(); - public override InnerObject InnerObject => null; - } + public abstract string AbstractProperty { get; set; } - public class InheritedFromAbstractClassDontOverrideVirtual : AbstractClass - { - public override void AbstractMethod() { } + public abstract InnerObject InnerObject { get; } - public override string AbstractProperty { get => null; set { } } + public void Method() { } - public override InnerObject InnerObject => null; - } + public string Property { get => null; set { } } + } - public abstract class InnerObject - { - public virtual void VirtualMethod() { } + public class InheritedFromAbstractClass : AbstractClass + { + public override void AbstractMethod() { } - public virtual string VirtualProperty { get => null; set { } } + public override string AbstractProperty { get => null; set { } } - public abstract void AbstractMethod(); + public override void VirtualMethod() { } - public abstract string AbstractProperty { get; set; } - } - }"; + public override string VirtualProperty { get => null; set { } } - await Verifier.VerifyAnalyzerAsync(source); - } + public override InnerObject InnerObject => null; + } - [Fact] - public async Task NoOverridable_DiagnosticReported() + public class InheritedFromAbstractClassDontOverrideVirtual : AbstractClass + { + public override void AbstractMethod() { } + + public override string AbstractProperty { get => null; set { } } + + public override InnerObject InnerObject => null; + } + + public abstract class InnerObject + { + public virtual void VirtualMethod() { } + + public virtual string VirtualProperty { get => null; set { } } + + public abstract void AbstractMethod(); + + public abstract string AbstractProperty { get; set; } + } + + public abstract class AbstractInnerObject + { + public void Method() { } + + public string Property { get => null; set { } } + + public abstract void VirtualMethod(); + + public abstract string VirtualProperty { get; set; } + } + + public sealed class SealedInnerObject : AbstractInnerObject + { + public override void VirtualMethod() { } + + public override string VirtualProperty { get => null; set { } } + } + + public static class ExtensionsClass + { + public static void ExtensionMethod(this I _) { } + } + """; + + public static TheoryData ValidTestCases => + [ + """new Mock().Setup(i => i.TestMethod());""", + """new Mock().Setup(i => i.TestProperty);""", + """new Mock().SetupSequence(i => i.TestMethod());""", + """new Mock().SetupSequence(i => i.TestProperty);""", + """new Mock().SetupSet(i => i.TestProperty = "Foobard");""", + """new Mock().SetupSet(i => i.TestProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.VirtualMethod());""", + """new Mock().Setup(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.AbstractMethod());""", + """new Mock().Setup(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + + """new Mock().Setup(i => i.VirtualMethod());""", + """new Mock().Setup(i => i.VirtualProperty);""", + """new Mock().SetupSequence(i => i.VirtualMethod());""", + """new Mock().SetupSequence(i => i.VirtualProperty);""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.VirtualMethod());""", + """new Mock().Setup(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.AbstractMethod());""", + """new Mock().Setup(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + + """new Mock().Setup(i => i.VirtualMethod());""", + """new Mock().Setup(i => i.VirtualProperty);""", + """new Mock().SetupSequence(i => i.VirtualMethod());""", + """new Mock().SetupSequence(i => i.VirtualProperty);""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.AbstractMethod());""", + """new Mock().Setup(i => i.AbstractProperty);""", + """new Mock().SetupSequence(i => i.AbstractMethod());""", + """new Mock().SetupSequence(i => i.AbstractProperty);""", + """new Mock().Setup(i => i.InnerObject.VirtualMethod());""", + """new Mock().Setup(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.AbstractMethod());""", + """new Mock().Setup(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + + """new Mock().Setup(i => i.VirtualMethod());""", + """new Mock().Setup(i => i.VirtualProperty);""", + """new Mock().SetupSequence(i => i.VirtualMethod());""", + """new Mock().SetupSequence(i => i.VirtualProperty);""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.AbstractMethod());""", + """new Mock().Setup(i => i.AbstractProperty);""", + """new Mock().SetupSequence(i => i.AbstractMethod());""", + """new Mock().SetupSequence(i => i.AbstractProperty);""", + """new Mock().Setup(i => i.InnerObject.VirtualMethod());""", + """new Mock().Setup(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.AbstractMethod());""", + """new Mock().Setup(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + + """new Mock().Setup(i => i.VirtualMethod());""", + """new Mock().Setup(i => i.VirtualProperty);""", + """new Mock().SetupSequence(i => i.VirtualMethod());""", + """new Mock().SetupSequence(i => i.VirtualProperty);""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.AbstractMethod());""", + """new Mock().Setup(i => i.AbstractProperty);""", + """new Mock().SetupSequence(i => i.AbstractMethod());""", + """new Mock().SetupSequence(i => i.AbstractProperty);""", + """new Mock().Setup(i => i.InnerObject.VirtualMethod());""", + """new Mock().Setup(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.VirtualProperty);""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.VirtualProperty = "Foobard");""", + """new Mock().Setup(i => i.InnerObject.AbstractMethod());""", + """new Mock().Setup(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractMethod());""", + """new Mock().SetupSequence(i => i.InnerObject.AbstractProperty);""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + """new Mock().SetupSet(i => i.InnerObject.AbstractProperty = "Foobard");""", + + """new Mock(MockBehavior.Strict).Setup(i => i.Method());""", + ]; + + public static TheoryData InvalidTestCases => + [ + """new Mock().Setup(i => i.{|PosInfoMoq2001:Method|}());""", + """new Mock().Setup(i => i.{|PosInfoMoq2001:Property|});""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:Method|}());""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:Property|});""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:Property|} = "1234");""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:Property|} = "1234");""", + """new Mock().Setup(i => i.{|PosInfoMoq2001:NonOverridableInnerObject|}.VirtualMethod());""", + """new Mock().Setup(i => i.{|PosInfoMoq2001:NonOverridableInnerObject|}.VirtualProperty);""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:NonOverridableInnerObject|}.VirtualMethod());""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:NonOverridableInnerObject|}.VirtualProperty);""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:NonOverridableInnerObject|}.VirtualProperty = "1234");""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:NonOverridableInnerObject|}.VirtualProperty = "1234");""", + """new Mock().Setup(i => i.AbstractInnerObject.{|PosInfoMoq2001:Method|}());""", + """new Mock().Setup(i => i.AbstractInnerObject.{|PosInfoMoq2001:Property|});""", + """new Mock().SetupSequence(i => i.AbstractInnerObject.{|PosInfoMoq2001:Method|}());""", + """new Mock().SetupSequence(i => i.AbstractInnerObject.{|PosInfoMoq2001:Property|});""", + """new Mock().SetupSet(i => i.AbstractInnerObject.{|PosInfoMoq2001:Property|} = "1234");""", + """new Mock().SetupSet(i => i.AbstractInnerObject.{|PosInfoMoq2001:Property|} = "1234");""", + """new Mock().Setup(i => i.{|PosInfoMoq2001:SealedInnerObject|}.VirtualMethod());""", + """new Mock().Setup(i => i.{|PosInfoMoq2001:SealedInnerObject|}.VirtualProperty);""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:SealedInnerObject|}.VirtualMethod());""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:SealedInnerObject|}.VirtualProperty);""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:SealedInnerObject|}.VirtualProperty = "1234");""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:SealedInnerObject|}.VirtualProperty = "1234");""", + + """new Mock().Setup(i => StandardClass.{|PosInfoMoq2001:StaticMethod|}());""", + """new Mock().SetupSequence(i => StandardClass.{|PosInfoMoq2001:StaticMethod|}());""", + + """new Mock().Setup(i => i.{|PosInfoMoq2001:Method|}());""", + """new Mock().Setup(i => i.{|PosInfoMoq2001:Property|});""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:Method|}());""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:Property|});""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:Property|} = "1234");""", + """new Mock().SetupSet(i => i.{|PosInfoMoq2001:Property|} = "1234");""", + + """new Mock().Setup(i => i.{|PosInfoMoq2001:ExtensionMethod|}());""", + """new Mock().SetupSequence(i => i.{|PosInfoMoq2001:ExtensionMethod|}());""", + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Setup(i => i.[|Method|]()); - mock1.Setup(i => i.[|Property|]); - mock1.SetupSequence(i => i.[|Method|]()); - mock1.SetupSequence(i => i.[|Property|]); - mock1.SetupSet(i => i.[|Property|] = ""1234""); - mock1.SetupSet(i => i.[|Property|] = ""1234""); - mock1.Setup(i => i.[|InnerObject|].VirtualMethod()); - mock1.Setup(i => i.[|InnerObject|].VirtualProperty); - mock1.SetupSequence(i => i.[|InnerObject|].VirtualMethod()); - mock1.SetupSequence(i => i.[|InnerObject|].VirtualProperty); - mock1.SetupSet(i => i.[|InnerObject|].VirtualProperty = ""1234""); - mock1.SetupSet(i => i.[|InnerObject|].VirtualProperty = ""1234""); - mock1.Setup(i => i.AbstractInnerObject.[|Method|]()); - mock1.Setup(i => i.AbstractInnerObject.[|Property|]); - mock1.SetupSequence(i => i.AbstractInnerObject.[|Method|]()); - mock1.SetupSequence(i => i.AbstractInnerObject.[|Property|]); - mock1.SetupSet(i => i.AbstractInnerObject.[|Property|] = ""1234""); - mock1.SetupSet(i => i.AbstractInnerObject.[|Property|] = ""1234""); - mock1.Setup(i => i.[|SealedInnerObject|].VirtualMethod()); - mock1.Setup(i => i.[|SealedInnerObject|].VirtualProperty); - mock1.SetupSequence(i => i.[|SealedInnerObject|].VirtualMethod()); - mock1.SetupSequence(i => i.[|SealedInnerObject|].VirtualProperty); - mock1.SetupSet(i => i.[|SealedInnerObject|].VirtualProperty = ""1234""); - mock1.SetupSet(i => i.[|SealedInnerObject|].VirtualProperty = ""1234""); - - var mock2 = new Mock(); - mock2.Setup(i => StandardClass.[|StaticMethod|]()); - mock2.SetupSequence(i => StandardClass.[|StaticMethod|]()); - - var mock3 = new Mock(); - mock3.Setup(i => i.[|Method|]()); - mock3.Setup(i => i.[|Property|]); - mock3.SetupSequence(i => i.[|Method|]()); - mock3.SetupSequence(i => i.[|Property|]); - mock3.SetupSet(i => i.[|Property|] = ""1234""); - mock3.SetupSet(i => i.[|Property|] = ""1234""); - - var mock4 = new Mock(); - mock4.Setup(i => i.[|ExtensionMethod|]()); - mock4.SetupSequence(i => i.[|ExtensionMethod|]()); + {{code}} } } - public class StandardClass - { - public void Method() { } - - public string Property { get => null; set { } } - - public static void StaticMethod() { } - - public InnerObject InnerObject => null; - - public AbstractInnerObject AbstractInnerObject => null; - - public SealedInnerObject SealedInnerObject => null; - } - - public abstract class AbstractClass - { - public void Method() { } - - public string Property { get => null; set { } } - } - - public interface I - { - int TestMethod(); - } - - public static class ExtensionsClass - { - public static void ExtensionMethod(this I _) { } - } - - public class InnerObject - { - public virtual void VirtualMethod() { } - - public virtual string VirtualProperty { get => null; set { } } - } - - public abstract class AbstractInnerObject - { - public void Method() { } - - public string Property { get => null; set { } } - - public abstract void VirtualMethod(); - - public abstract string VirtualProperty { get; set; } - } - - public sealed class SealedInnerObject : AbstractInnerObject - { - public override void VirtualMethod() { } - - public override string VirtualProperty { get => null; set { } } - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(i => i.Method()); + {{code}} } } - public interface I - { - void Method(); - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup(System.Action _) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 9aef08e..63c9dbc 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -85,6 +85,10 @@ public void Setup(Expression> expression) { } public SetupResult Setup(Expression> expression) { return default; } + public void SetupSequence(Expression> expression) { } + + public void SetupSequence(Expression> expression) { } + public void SetupSet(Action action) { } public void SetupSet(Action action) { } From edec6c01bf6bb1106d2af57510b06596a1ad0250 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:07:16 +0200 Subject: [PATCH 10/30] Refactoring of the SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest unit test --- ...uldSpecifyOptionalArgumentsAnalyzerTest.cs | 280 ++++++++++-------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 23 +- 2 files changed, 173 insertions(+), 130 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest.cs index 37e3d80..aae6732 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest.cs @@ -10,102 +10,147 @@ namespace PosInformatique.Moq.Analyzers.Tests public class SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest { - [Theory] - [InlineData("")] - [InlineData(".InSequence(sequence)")] - public async Task SetupMethodOptionalArguments_NoDiagnosticReported(string sequence) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var sequence = new MockSequence(); - - var mock1 = new Mock(); - - mock1" + sequence + @".Setup(m => m.TestMethod()) - .Callback(() => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(""A"")) - .Callback((string x) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(""A"", 10)) - .Callback((string x, int y) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethodWithDefaultParameters(""A"", 10, 20, ""B"")) - .Callback((string x, int y, int z, string w) => { }) - .Throws(new Exception()); - } - } - - public interface I - { - void TestMethod(); + private const string TestTypes = + """ + public interface I + { + void TestMethod(); - void TestMethod(string a); + void TestMethod(string a); - void TestMethod(string a, int b); + void TestMethod(string a, int b); - void TestMethodWithDefaultParameters(string a, int b, int c = 42, string d = ""default""); - } - }"; + void TestMethodWithDefaultParameters(string a, int b, int c = 42, string d = "default"); + } - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("")] - [InlineData(".InSequence(sequence)")] - public async Task SetupMethodOptionalArguments_MissingArguments_DiagnosticReported(string sequence) - { - var source = @" - namespace ConsoleApplication1 + public static class MoqExtensions + { + public static ISetup MySetup(this Mock mock, Expression> exp) + where T : class { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var sequence = new MockSequence(); - - var mock1 = new Mock(); - - mock1" + sequence + @".Setup(m => m.{|PosInfoMoq1011:TestMethodWithDefaultParameters|}(""A"", 10)) - .Callback(() => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.{|PosInfoMoq1011:TestMethodWithDefaultParameters|}(""A"", 10, 20)) - .Callback(() => { }) - .Throws(new Exception()); - } - } - - public interface I - { - void TestMethod(); - - void TestMethod(string a); - - void TestMethod(string a, int b); - - void TestMethodWithDefaultParameters(string a, int b, int c = 42, string d = ""D""); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } + return mock.Setup(exp); + } + } + + public interface IRepository + { + void Get(string s); + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod()) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod("A")) + .Callback((string x) => { }) + .Throws(new Exception()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod("A", 10)) + .Callback((string x, int y) => { }) + .Throws(new Exception()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethodWithDefaultParameters("A", 10, 20, "B")) + .Callback((string x, int y, int z, string w) => { }) + .Throws(new Exception()); + """, + + """ + var sequence = new MockSequence(); + var mock = new Mock(); + mock.InSequence(sequence).Setup(m => m.TestMethod()) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + var sequence = new MockSequence(); + var mock = new Mock(); + mock.InSequence(sequence).Setup(m => m.TestMethod("A")) + .Callback((string x) => { }) + .Throws(new Exception()); + """, + + """ + var sequence = new MockSequence(); + var mock = new Mock(); + mock.InSequence(sequence).Setup(m => m.TestMethod("A", 10)) + .Callback((string x, int y) => { }) + .Throws(new Exception()); + """, + + """ + var sequence = new MockSequence(); + var mock = new Mock(); + mock.InSequence(sequence).Setup(m => m.TestMethodWithDefaultParameters("A", 10, 20, "B")) + .Callback((string x, int y, int z, string w) => { }) + .Throws(new Exception()); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + mock.MySetup(i => i.Get("Foobar")); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + mock.Setup(m => m.TestMethod()); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(m => m.{|PosInfoMoq1011:TestMethodWithDefaultParameters|}("A", 10)) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.{|PosInfoMoq1011:TestMethodWithDefaultParameters|}("A", 10, 20)) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + var sequence = new MockSequence(); + var mock = new Mock(); + mock.InSequence(sequence).Setup(m => m.{|PosInfoMoq1011:TestMethodWithDefaultParameters|}("A", 10)) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + var sequence = new MockSequence(); + var mock = new Mock(); + mock.InSequence(sequence).Setup(m => m.{|PosInfoMoq1011:TestMethodWithDefaultParameters|}("A", 10, 20)) + .Callback(() => { }) + .Throws(new Exception()); + """, + ]; - [Fact] - public async Task CustomSetupMethod_NoDiagnosticReported() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -117,67 +162,44 @@ public class TestClass { public void TestMethod() { - var m = new Mock(MockBehavior.Strict); - - m.MySetup(i => i.Get(""Foobar"")); + {{code}} } } - public static class MoqExtensions - { - public static ISetup MySetup(this Mock mock, Expression> exp) - where T : class - { - return mock.Setup(exp); - } - } - - public interface IRepository - { - void Get(string s); - } + {{TestTypes}} } - "; + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; + using FakeMoqLibrary.Language.Flow; + using System; + using System.Linq.Expressions; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(m => m.TestMethod()); + {{code}} } } - public interface I - { - void TestMethod(); - } + {{TestTypes}} } - namespace OtherNamespace - { - using System; - - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup(Action act) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 63c9dbc..d0374b7 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -43,6 +43,16 @@ public struct Times public class SetupResult { + public SetupResult Callback(Action callback) { return this; } + + public SetupResult Callback(Action callback) { return this; } + + public SetupResult Callback(Action callback) { return this; } + + public SetupResult Callback(Action callback) { return this; } + + public void Throws(Exception exception) { } + public void Verifiable() { } public void Verifiable(string failMessage) { } @@ -52,6 +62,10 @@ public void Verifiable(Times times, string failMessage = null) { } public void Verifiable(Func times, string failMessage = null) { } } + public class SetupResult : SetupResult, Language.Flow.ISetup { } + + public class MockSequence { } + public abstract class Mock { public static T Of() { return default; } @@ -81,7 +95,9 @@ public Mock(Expression> newExpression, MockBehavior behavior = default) public void As() { } - public void Setup(Expression> expression) { } + public Mock InSequence(MockSequence sequence) { return this; } + + public SetupResult Setup(Expression> expression) { return default; } public SetupResult Setup(Expression> expression) { return default; } @@ -105,6 +121,11 @@ public void Verify(Expression> expression, Func times, string f } } + namespace FakeMoqLibrary.Language.Flow + { + public interface ISetup { } + } + namespace FakeMoqLibrary.Protected { public static class ProtectedExtension From 544f1a3e4ff7db5aaa1176f5b52198f50d0035ce Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:29:21 +0200 Subject: [PATCH 11/30] Refactoring RaiseMethodsAnalyzerTest unit test --- .../Analyzers/RaiseMethodsAnalyzerTest.cs | 643 ++++++++++-------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 7 + 2 files changed, 348 insertions(+), 302 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/RaiseMethodsAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/RaiseMethodsAnalyzerTest.cs index 655fc1a..a254eb3 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/RaiseMethodsAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/RaiseMethodsAnalyzerTest.cs @@ -6,320 +6,376 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class RaiseMethodsAnalyzerTest { - [Theory] - [InlineData("Raise", "void")] - [InlineData("RaiseAsync", "Task")] - [InlineData("RaiseAsync", "Task")] - public async Task Raise_WithParams_NoDiagnosticReported(string method, string eventReturnType) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - using System.Threading.Tasks; + private const string TestTypes = + """ + public interface I + { + event CustomEventHandler TheEvent; - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); + event AsyncEventHandler AsyncEvent; - mock1." + method + @"(m => m.TheEvent += null, ""OK"", 1, null); - mock1." + method + @"(m => m.TheEvent += null, ""OK"", 1, 10); - mock1." + method + @"(m => m.TheEvent += null, ""OK"", 1, new object()); + event AsyncResultEventHandler AsyncResultEvent; - mock1." + method + @"(m => m.TheEvent -= null, ""OK"", 1, null); - mock1." + method + @"(m => m.TheEvent -= null, ""OK"", 1, 10); - mock1." + method + @"(m => m.TheEvent -= null, ""OK"", 1, new object()); - } - } + event ExtendedEventHandler ExtendedEvent; - public interface I - { - event CustomEventHandler TheEvent; - } + event ExtendedAsyncEventHandler ExtendedAsyncEvent; - public delegate " + eventReturnType + @" CustomEventHandler(string a, int b, object c); - }"; + event ExtendedAsyncResultEventHandler ExtendedAsyncResultEvent; - await Verifier.VerifyAnalyzerAsync(source); - } + event EventHandler EventWithArgs; - [Fact] - public async Task Raise_WithEventArgs_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + event EventHandler EventWithSenderAndString; - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); + int Property { get; set; } + } - mock1.Raise(m => m.TheEvent += null, new CustomEventArgs()); - mock1.Raise(m => m.TheEvent += null, null, new CustomEventArgs()); - mock1.Raise(m => m.TheEvent += null, 10, new CustomEventArgs()); - mock1.Raise(m => m.TheEvent += null, new object(), new CustomEventArgs()); + public delegate void CustomEventHandler(string a, int b, object c); - mock1.Raise(m => m.TheEvent -= null, new CustomEventArgs()); - mock1.Raise(m => m.TheEvent -= null, null, new CustomEventArgs()); - mock1.Raise(m => m.TheEvent -= null, 10, new CustomEventArgs()); - mock1.Raise(m => m.TheEvent -= null, new object(), new CustomEventArgs()); - } - } + public delegate Task AsyncEventHandler(string a, int b, object c); - public interface I - { - event EventHandler TheEvent; - } + public delegate Task AsyncResultEventHandler(string a, int b, object c); - public class CustomEventArgs : EventArgs - { - } - }"; + public delegate void ExtendedEventHandler(string a, int b, object c, int d, string e, int f); - await Verifier.VerifyAnalyzerAsync(source); - } + public delegate Task ExtendedAsyncEventHandler(string a, int b, object c, int d, string e, int f); - [Theory] - [InlineData("Raise", "void")] - [InlineData("RaiseAsync", "Task")] - [InlineData("RaiseAsync", "Task")] - public async Task Raise_WithParams_MissingArgument_DiagnosticReported(string method, string eventReturnType) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - using System.Threading.Tasks; + public delegate Task ExtendedAsyncResultEventHandler(string a, int b, object c, int d, string e, int f); - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); + public class CustomEventArgs : EventArgs { } + """; - mock1.{|#0:" + method + @"|#0}(m => m.TheEvent += null); - mock1.{|#1:" + method + @"|#1}(m => m.TheEvent += null, 1); - mock1.{|#2:" + method + @"|#2}(m => m.TheEvent += null, 1, 2, ""3"", 4, 5, 6); - } - } + public static TheoryData ValidTestCases => + [ + """mock.Raise(m => m.TheEvent += null, "OK", 1, null);""", - public interface I - { - event CustomEventHandler TheEvent; - } + """mock.Raise(m => m.TheEvent += null, "OK", 1, 10);""", - public delegate " + eventReturnType + @" CustomEventHandler(string a, int b, object c); - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(0) - .WithArguments("The event 'TheEvent' expects 3 argument(s) but 0 were provided."), - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(1) - .WithArguments("The event 'TheEvent' expects 3 argument(s) but 1 were provided."), - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(2) - .WithArguments("The event 'TheEvent' expects 3 argument(s) but 6 were provided."), - ]); - } + """mock.Raise(m => m.TheEvent += null, "OK", 1, new object());""", - [Theory] - [InlineData("Raise", "void")] - [InlineData("RaiseAsync", "Task")] - [InlineData("RaiseAsync", "Task")] - public async Task Raise_WithParams_WrongType_DiagnosticReported(string method, string eventReturnType) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - using System.Threading.Tasks; + """mock.Raise(m => m.TheEvent -= null, "OK", 1, null);""", - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); + """mock.Raise(m => m.TheEvent -= null, "OK", 1, 10);""", - mock1." + method + @"(m => m.TheEvent += null, {|#0:1|#0}, 2, ""OK"", {|#1:""Wrong""|#1}, null, {|#2:null|#2}); - } - } + """mock.Raise(m => m.TheEvent -= null, "OK", 1, new object());""", - public interface I - { - event CustomEventHandler TheEvent; - } + """mock.RaiseAsync(m => m.AsyncEvent += null, "OK", 1, null);""", - public delegate " + eventReturnType + @" CustomEventHandler(string a, int b, object c, int d, string e, int f); - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(0) - .WithArguments("The parameter 'a' of the event 'TheEvent' expects a value of type 'String' but a value of type 'Int32' was provided."), - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(1) - .WithArguments("The parameter 'd' of the event 'TheEvent' expects a value of type 'Int32' but a value of type 'String' was provided."), - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(2) - .WithArguments("The parameter 'f' of the event 'TheEvent' expects a value of type 'Int32' but a value 'null' was provided."), - ]); - } + """mock.RaiseAsync(m => m.AsyncEvent += null, "OK", 1, 10);""", - [Fact] - public async Task Raise_WithEventArgs_WrongType_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + """mock.RaiseAsync(m => m.AsyncEvent += null, "OK", 1, new object());""", - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); + """mock.RaiseAsync(m => m.AsyncEvent -= null, "OK", 1, null);""", - mock1.Raise(m => m.TheEvent += null, {|#0:new EventArgs()|#0}); - } - } + """mock.RaiseAsync(m => m.AsyncEvent -= null, "OK", 1, 10);""", - public interface I - { - event EventHandler TheEvent; - } + """mock.RaiseAsync(m => m.AsyncEvent -= null, "OK", 1, new object());""", - public class CustomEventArgs : EventArgs - { - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(RaiseMethodsAnalyzer.ParametersMustMatchSignature) - .WithLocation(0) - .WithArguments("The parameter 'e' of the event 'TheEvent' expects a value of type 'CustomEventArgs' but a value of type 'EventArgs' was provided."), - ]); - } + """mock.RaiseAsync(m => m.AsyncResultEvent += null, "OK", 1, null);""", - [Theory] - [InlineData("Raise", "void", "\"OK\", 1, null")] - [InlineData("Raise", "void", "\"OK\", 1, 10")] - [InlineData("Raise", "void", "\"OK\", 1, new object()")] - [InlineData("RaiseAsync", "Task", "\"OK\", 1, null")] - [InlineData("RaiseAsync", "Task", "\"OK\", 1, 10")] - [InlineData("RaiseAsync", "Task", "\"OK\", 1, new object()")] - [InlineData("RaiseAsync", "Task", "\"OK\", 1, null")] - [InlineData("RaiseAsync", "Task", "\"OK\", 1, 10")] - [InlineData("RaiseAsync", "Task", "\"OK\", 1, new object()")] - public async Task Raise_WrongLambdaExpression_DiagnosticReported(string method, string eventReturnType, string parameters) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - using System.Threading.Tasks; + """mock.RaiseAsync(m => m.AsyncResultEvent += null, "OK", 1, 10);""", - public class TestClass - { - public void TestMethod() - { - var act = (I i) => i.TheEvent += null; - var tmp = 0; - - var mock1 = new Mock(MockBehavior.Strict); - - mock1." + method + @"({|PosInfoMoq2018:null|}); - mock1." + method + @"({|PosInfoMoq2018:null|}, " + parameters + @"); - mock1." + method + @"({|PosInfoMoq2018:m => m.ToString()|}, "" + parameters + @""); - mock1." + method + @"({|PosInfoMoq2018:act|}, "" + parameters + @""); - mock1." + method + @"({|PosInfoMoq2018:m => new object()|}, "" + parameters + @""); - mock1." + method + @"({|PosInfoMoq2018:m => tmp = 10|}, "" + parameters + @""); - mock1." + method + @"({|PosInfoMoq2018:m => m.Property = 10|}, "" + parameters + @""); - } - } + """mock.RaiseAsync(m => m.AsyncResultEvent += null, "OK", 1, new object());""", - public interface I - { - event CustomEventHandler TheEvent; + """mock.RaiseAsync(m => m.AsyncResultEvent -= null, "OK", 1, null);""", - int Property { get; set; } - } + """mock.RaiseAsync(m => m.AsyncResultEvent -= null, "OK", 1, 10);""", - public delegate " + eventReturnType + @" CustomEventHandler(string a, int b, object c); - }"; + """mock.RaiseAsync(m => m.AsyncResultEvent -= null, "OK", 1, new object());""", - await Verifier.VerifyAnalyzerAsync(source); - } + """mock.Raise(m => m.EventWithArgs += null, new CustomEventArgs());""", - [Theory] - [InlineData("Raise", "void")] - [InlineData("RaiseAsync", "Task")] - [InlineData("RaiseAsync", "Task")] - public async Task Raise_WithNotNullDelegate_NoDiagnosticReported(string method, string eventReturnType) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - using System.Threading.Tasks; + """mock.Raise(m => m.EventWithArgs += null, null, new CustomEventArgs());""", - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); + """mock.Raise(m => m.EventWithArgs += null, 10, new CustomEventArgs());""", - mock1." + method + @"(m => m.TheEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, ""OK"", 1, null); - mock1." + method + @"(m => m.TheEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, ""OK"", 1, 10); - mock1." + method + @"(m => m.TheEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, ""OK"", 1, new object()); + """mock.Raise(m => m.EventWithArgs += null, new object(), new CustomEventArgs());""", - mock1." + method + @"(m => m.TheEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, ""OK"", 1, null); - mock1." + method + @"(m => m.TheEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, ""OK"", 1, 10); - mock1." + method + @"(m => m.TheEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, ""OK"", 1, new object()); - } + """mock.Raise(m => m.EventWithArgs -= null, new CustomEventArgs());""", - public static " + eventReturnType + @" MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } - } + """mock.Raise(m => m.EventWithArgs -= null, null, new CustomEventArgs());""", - public interface I - { - event CustomEventHandler TheEvent; - } + """mock.Raise(m => m.EventWithArgs -= null, 10, new CustomEventArgs());""", - public delegate " + eventReturnType + @" CustomEventHandler(string a, int b, object c); - }"; + """mock.Raise(m => m.EventWithArgs -= null, new object(), new CustomEventArgs());""", + ]; - await Verifier.VerifyAnalyzerAsync(source); - } + public static TheoryData InvalidTestCases => + [ + """mock.{|PosInfoMoq2017:Raise|}(m => m.TheEvent += null);""", + + """mock.{|PosInfoMoq2017:Raise|}(m => m.TheEvent += null, 1);""", + + """mock.{|PosInfoMoq2017:Raise|}(m => m.TheEvent += null, 1, 2, "3", 4, 5, 6);""", + + """mock.Raise(m => m.ExtendedEvent += null, {|PosInfoMoq2017:1|}, 2, "OK", {|PosInfoMoq2017:"Wrong"|}, null, {|PosInfoMoq2017:null|});""", + + """mock.Raise({|PosInfoMoq2018:null|});""", + + """mock.Raise({|PosInfoMoq2018:null|}, "OK", 1, null);""", + + """mock.Raise({|PosInfoMoq2018:null|}, "OK", 1, 10);""", + + """mock.Raise({|PosInfoMoq2018:null|}, "OK", 1, new object());""", + + """mock.Raise({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, null);""", + + """mock.Raise({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, 10);""", + + """mock.Raise({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, new object());""", + + """ + var act = (I i) => i.TheEvent += null; + mock.Raise({|PosInfoMoq2018:act|}, "OK", 1, null); + """, + + """ + var act = (I i) => i.TheEvent += null; + mock.Raise({|PosInfoMoq2018:act|}, "OK", 1, 10); + """, + + """ + var act = (I i) => i.TheEvent += null; + mock.Raise({|PosInfoMoq2018:act|}, "OK", 1, new object()); + """, + + """mock.Raise({|PosInfoMoq2018:m => new object()|}, "OK", 1, null);""", + + """mock.Raise({|PosInfoMoq2018:m => new object()|}, "OK", 1, 10);""", + + """mock.Raise({|PosInfoMoq2018:m => new object()|}, "OK", 1, new object());""", + + """ + var tmp = 0; + mock.Raise({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, null); + """, + + """ + var tmp = 0; + mock.Raise({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, 10); + """, + + """ + var tmp = 0; + mock.Raise({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, new object()); + """, + + """mock.Raise({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, null);""", + + """mock.Raise({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, 10);""", + + """mock.Raise({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, new object());""", + + """ + mock.Raise(m => m.TheEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, null); + static void MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """ + mock.Raise(m => m.TheEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, 10); + static void MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """ + mock.Raise(m => m.TheEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, new object()); + static void MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """mock.Raise(m => m.TheEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, null);""", + + """mock.Raise(m => m.TheEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, 10);""", + + """mock.Raise(m => m.TheEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, new object());""", + + """mock.{|PosInfoMoq2017:RaiseAsync|}(m => m.AsyncEvent += null);""", + + """mock.{|PosInfoMoq2017:RaiseAsync|}(m => m.AsyncEvent += null, 1);""", + + """mock.{|PosInfoMoq2017:RaiseAsync|}(m => m.AsyncEvent += null, 1, 2, "3", 4, 5, 6);""", + + """mock.RaiseAsync(m => m.ExtendedAsyncEvent += null, {|PosInfoMoq2017:1|}, 2, "OK", {|PosInfoMoq2017:"Wrong"|}, null, {|PosInfoMoq2017:null|});""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|});""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|}, "OK", 1, new object());""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, new object());""", + + """ + var act = (I i) => i.AsyncEvent += null; + mock.RaiseAsync({|PosInfoMoq2018:act|}, "OK", 1, null); + """, + + """ + var act = (I i) => i.AsyncEvent += null; + mock.RaiseAsync({|PosInfoMoq2018:act|}, "OK", 1, 10); + """, + + """ + var act = (I i) => i.AsyncEvent += null; + mock.RaiseAsync({|PosInfoMoq2018:act|}, "OK", 1, new object()); + """, + + """mock.RaiseAsync({|PosInfoMoq2018:m => new object()|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => new object()|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => new object()|}, "OK", 1, new object());""", + + """ + var tmp = 0; + mock.RaiseAsync({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, null); + """, + + """ + var tmp = 0; + mock.RaiseAsync({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, 10); + """, + + """ + var tmp = 0; + mock.RaiseAsync({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, new object()); + """, + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, new object());""", - [Fact] - public async Task RaiseAsync_WithNoAsynchronousEvent_NoDiagnosticReported() + """ + mock.RaiseAsync(m => m.AsyncEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, null); + static Task MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """ + mock.RaiseAsync(m => m.AsyncEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, 10); + static Task MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """ + mock.RaiseAsync(m => m.AsyncEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, new object()); + static Task MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """mock.RaiseAsync(m => m.AsyncEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, null);""", + + """mock.RaiseAsync(m => m.AsyncEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, 10);""", + + """mock.RaiseAsync(m => m.AsyncEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, new object());""", + + """mock.{|PosInfoMoq2017:RaiseAsync|}(m => m.AsyncResultEvent += null);""", + + """mock.{|PosInfoMoq2017:RaiseAsync|}(m => m.AsyncResultEvent += null, 1);""", + + """mock.{|PosInfoMoq2017:RaiseAsync|}(m => m.AsyncResultEvent += null, 1, 2, "3", 4, 5, 6);""", + + """mock.RaiseAsync(m => m.ExtendedAsyncResultEvent += null, {|PosInfoMoq2017:1|}, 2, "OK", {|PosInfoMoq2017:"Wrong"|}, null, {|PosInfoMoq2017:null|});""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|});""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:null|}, "OK", 1, new object());""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.ToString()|}, "OK", 1, new object());""", + + """ + var act = (I i) => i.AsyncResultEvent += null; + mock.RaiseAsync({|PosInfoMoq2018:act|}, "OK", 1, null); + """, + + """ + var act = (I i) => i.AsyncResultEvent += null; + mock.RaiseAsync({|PosInfoMoq2018:act|}, "OK", 1, 10); + """, + + """ + var act = (I i) => i.AsyncResultEvent += null; + mock.RaiseAsync({|PosInfoMoq2018:act|}, "OK", 1, new object()); + """, + + """mock.RaiseAsync({|PosInfoMoq2018:m => new object()|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => new object()|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => new object()|}, "OK", 1, new object());""", + + """ + var tmp = 0; + mock.RaiseAsync({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, null); + """, + + """ + var tmp = 0; + mock.RaiseAsync({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, 10); + """, + + """ + var tmp = 0; + mock.RaiseAsync({|PosInfoMoq2018:m => tmp = 10|}, "OK", 1, new object()); + """, + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, null);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, 10);""", + + """mock.RaiseAsync({|PosInfoMoq2018:m => m.Property = 10|}, "OK", 1, new object());""", + + """ + mock.RaiseAsync(m => m.AsyncResultEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, null); + static Task MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """ + mock.RaiseAsync(m => m.AsyncResultEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, 10); + static Task MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """ + mock.RaiseAsync(m => m.AsyncResultEvent += {|PosInfoMoq1010:MethodMatchEventSignature|}, "OK", 1, new object()); + static Task MethodMatchEventSignature(string a, int b, object c) { throw new NotSupportedException(); } + """, + + """mock.RaiseAsync(m => m.AsyncResultEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, null);""", + + """mock.RaiseAsync(m => m.AsyncResultEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, 10);""", + + """mock.RaiseAsync(m => m.AsyncResultEvent += {|PosInfoMoq1010:(a, b, c) => throw new NotSupportedException()|}, "OK", 1, new object());""", + + """mock.Raise(m => m.EventWithArgs += null, {|PosInfoMoq2017:new EventArgs()|});""", + + """mock.{|PosInfoMoq2019:RaiseAsync|}(m => m.TheEvent += null, "OK", 1, new object());""", + + """mock.Raise(m => m.EventWithSenderAndString += null, {|PosInfoMoq2017:new EventArgs()|});""", + + """mock.{|PosInfoMoq2017:Raise|}(m => m.EventWithSenderAndString += null, 1, 2, 3, 4);""", + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -330,62 +386,45 @@ public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - - mock1.{|PosInfoMoq2019:RaiseAsync|}(m => m.TheEvent += null, ""OK"", 1, new object()); - } - } - - public interface I - { - event CustomEventHandler TheEvent; + var mock = new Mock(MockBehavior.Strict); + {{code}} + } } - public delegate void CustomEventHandler(string a, int b, object c); - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { + using FakeMoqLibrary; using System; - using OtherNamespace; + using System.Threading.Tasks; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Raise(m => m.EventWithSenderAndString += null, new EventArgs()); - mock1.Raise(m => m.EventWithSenderAndString += null, 1, 2, 3, 4); + var mock = new Mock(MockBehavior.Strict); + {{code}} } } - public interface I - { - event EventHandler EventWithSenderAndString; - } + {{TestTypes}} } - namespace OtherNamespace - { - using System; - - public class Mock - { - public Mock(MockBehavior _) { } - - public void Raise(Action act, EventArgs e) { } - public void Raise(Action act, params object[] args) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index d0374b7..c53d130 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -15,6 +15,7 @@ namespace FakeMoqLibrary using System; using System.Collections.Generic; using System.Linq.Expressions; + using System.Threading.Tasks; public static class It { @@ -111,6 +112,12 @@ public void SetupSet(Action action) { } public void SetupSet(Func action) { } + public void Raise(Action eventExpression, EventArgs args) { } + + public void Raise(Action eventExpression, params object[] args) { } + + public Task RaiseAsync(Action eventExpression, params object[] args) { return default; } + public void Verify() { } public void Verify(Expression> expression, string failMessage = null) { } From 1a1407dc250c97eec4351976ddbd75d2897bd9ac Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:35:53 +0200 Subject: [PATCH 12/30] Refactoring VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest unit tests --- ...edOnlyForOverridableMembersAnalyzerTest.cs | 493 +++++++++++------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 2 + 2 files changed, 296 insertions(+), 199 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs index 3b33587..0ee0c32 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs @@ -10,269 +10,364 @@ namespace PosInformatique.Moq.Analyzers.Tests public class VerifyMustBeUsedOnlyForOverridableMembersAnalyzerTest { - [Theory] - [InlineData("")] - [InlineData(", \"The message\"")] - public async Task Overridable_NoDiagnosticReported(string secondArgument) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + private const string TestTypes = + """ + public interface I + { + int TestMethod(); - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Verify(i => i.TestMethod()" + secondArgument + @"); - mock1.Verify(i => i.TestProperty" + secondArgument + @"); - mock1.Verify(i => i.InnerObject.VirtualMethod()" + secondArgument + @"); - mock1.Verify(i => i.InnerObject.VirtualProperty" + secondArgument + @"); - mock1.Verify(i => i.InnerObject.AbstractMethod()" + secondArgument + @"); - mock1.Verify(i => i.InnerObject.AbstractProperty" + secondArgument + @"); - - var mock2 = new Mock(); - mock2.Verify(i => i.VirtualMethod()" + secondArgument + @"); - mock2.Verify(i => i.VirtualProperty" + secondArgument + @"); - mock2.Verify(i => i.InnerObject.VirtualMethod()" + secondArgument + @"); - mock2.Verify(i => i.InnerObject.VirtualProperty" + secondArgument + @"); - mock2.Verify(i => i.InnerObject.AbstractMethod()" + secondArgument + @"); - mock2.Verify(i => i.InnerObject.AbstractProperty" + secondArgument + @"); - - var mock3 = new Mock(); - mock3.Verify(i => i.VirtualMethod()" + secondArgument + @"); - mock3.Verify(i => i.VirtualProperty" + secondArgument + @"); - mock3.Verify(i => i.AbstractMethod()" + secondArgument + @"); - mock3.Verify(i => i.AbstractProperty" + secondArgument + @"); - mock3.Verify(i => i.InnerObject.VirtualMethod()" + secondArgument + @"); - mock3.Verify(i => i.InnerObject.VirtualProperty" + secondArgument + @"); - mock3.Verify(i => i.InnerObject.AbstractMethod()" + secondArgument + @"); - mock3.Verify(i => i.InnerObject.AbstractProperty" + secondArgument + @"); - - var mock4 = new Mock(); - mock4.Verify(i => i.VirtualMethod()" + secondArgument + @"); - mock4.Verify(i => i.VirtualProperty" + secondArgument + @"); - mock4.Verify(i => i.AbstractMethod()" + secondArgument + @"); - mock4.Verify(i => i.AbstractProperty" + secondArgument + @"); - mock4.Verify(i => i.InnerObject.VirtualMethod()" + secondArgument + @"); - mock4.Verify(i => i.InnerObject.VirtualProperty" + secondArgument + @"); - mock4.Verify(i => i.InnerObject.AbstractMethod()" + secondArgument + @"); - mock4.Verify(i => i.InnerObject.AbstractProperty" + secondArgument + @"); - - var mock5 = new Mock(); - mock5.Verify(i => i.VirtualMethod()" + secondArgument + @"); - mock5.Verify(i => i.VirtualProperty" + secondArgument + @"); - mock5.Verify(i => i.AbstractMethod()" + secondArgument + @"); - mock5.Verify(i => i.AbstractProperty" + secondArgument + @"); - mock5.Verify(i => i.InnerObject.VirtualMethod()" + secondArgument + @"); - mock5.Verify(i => i.InnerObject.VirtualProperty" + secondArgument + @"); - mock5.Verify(i => i.InnerObject.AbstractMethod()" + secondArgument + @"); - mock5.Verify(i => i.InnerObject.AbstractProperty" + secondArgument + @"); - } - } + void Method(); - public interface I - { - int TestMethod(); + string TestProperty { get; } - string TestProperty { get; } + InnerObject InnerObject { get; } + } - InnerObject InnerObject { get; } - } + public class StandardClass + { + public virtual void VirtualMethod() { } - public class StandardClass - { - public virtual void VirtualMethod() { } + public virtual string VirtualProperty => null; - public virtual string VirtualProperty => null; + public virtual InnerObject InnerObject => null; - public virtual InnerObject InnerObject { get => null; } - } + public void Method() { } - public abstract class AbstractClass - { - public virtual void VirtualMethod() { } + public string Property => null; - public virtual string VirtualProperty => null; + public static void StaticMethod() { } - public abstract void AbstractMethod(); + public InnerObject NonOverridableInnerObject => null; - public abstract string AbstractProperty { get; } + public AbstractInnerObject AbstractInnerObject => null; - public abstract InnerObject InnerObject { get; } - } + public SealedInnerObject SealedInnerObject => null; + } - public class InheritedFromAbstractClass : AbstractClass - { - public override void AbstractMethod() { } + public abstract class AbstractClass + { + public virtual void VirtualMethod() { } - public override string AbstractProperty => null; + public virtual string VirtualProperty => null; - public override void VirtualMethod() { } + public abstract void AbstractMethod(); - public override string VirtualProperty => null; + public abstract string AbstractProperty { get; } - public override InnerObject InnerObject => null; - } + public abstract InnerObject InnerObject { get; } - public class InheritedFromAbstractClassDontOverrideVirtual : AbstractClass - { - public override void AbstractMethod() { } + public void Method() { } - public override string AbstractProperty => null; + public string Property => null; + } - public override InnerObject InnerObject => null; - } + public class InheritedFromAbstractClass : AbstractClass + { + public override void AbstractMethod() { } - public abstract class InnerObject - { - public virtual void VirtualMethod() { } + public override string AbstractProperty => null; - public virtual string VirtualProperty => null; + public override void VirtualMethod() { } - public abstract void AbstractMethod(); + public override string VirtualProperty => null; - public abstract string AbstractProperty { get; } - } - }"; + public override InnerObject InnerObject => null; + } - await Verifier.VerifyAnalyzerAsync(source); - } + public class InheritedFromAbstractClassDontOverrideVirtual : AbstractClass + { + public override void AbstractMethod() { } - [Theory] - [InlineData("")] - [InlineData(", \"The message\"")] - public async Task NoOverridable_DiagnosticReported(string secondArgument) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + public override string AbstractProperty => null; - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Verify(i => i.[|Method|]()" + secondArgument + @"); - mock1.Verify(i => i.[|Property|]" + secondArgument + @"); - mock1.Verify(i => i.[|InnerObject|].VirtualMethod()" + secondArgument + @"); - mock1.Verify(i => i.[|InnerObject|].VirtualProperty" + secondArgument + @"); - mock1.Verify(i => i.AbstractInnerObject.[|Method|]()" + secondArgument + @"); - mock1.Verify(i => i.AbstractInnerObject.[|Property|]" + secondArgument + @"); - mock1.Verify(i => i.[|SealedInnerObject|].VirtualMethod()" + secondArgument + @"); - mock1.Verify(i => i.[|SealedInnerObject|].VirtualProperty" + secondArgument + @"); - - var mock2 = new Mock(); - mock2.Verify(i => StandardClass.[|StaticMethod|]()" + secondArgument + @"); - - var mock3 = new Mock(); - mock3.Verify(i => i.[|Method|]()" + secondArgument + @"); - mock3.Verify(i => i.[|Property|]" + secondArgument + @"); - - var mock4 = new Mock(); - mock4.Verify(i => i.[|ExtensionMethod|]()" + secondArgument + @"); - } - } + public override InnerObject InnerObject => null; + } - public class StandardClass - { - public void Method() { } + public abstract class InnerObject + { + public virtual void VirtualMethod() { } - public string Property => null; + public virtual string VirtualProperty => null; - public static void StaticMethod() { } + public abstract void AbstractMethod(); - public InnerObject InnerObject => null; + public abstract string AbstractProperty { get; } + } - public AbstractInnerObject AbstractInnerObject => null; + public abstract class AbstractInnerObject + { + public void Method() { } - public SealedInnerObject SealedInnerObject => null; - } + public string Property => null; - public abstract class AbstractClass - { - public void Method() { } + public abstract void VirtualMethod(); - public string Property => null; - } + public abstract string VirtualProperty { get; } + } - public interface I - { - int TestMethod(); - } + public sealed class SealedInnerObject : AbstractInnerObject + { + public override void VirtualMethod() { } - public static class ExtensionsClass - { - public static void ExtensionMethod(this I _) { } - } + public override string VirtualProperty => null; + } - public class InnerObject - { - public virtual void VirtualMethod() { } + public static class ExtensionsClass + { + public static void ExtensionMethod(this I _) { } + } + """; - public virtual string VirtualProperty => null; - } + public static TheoryData ValidTestCases => + [ + """new Mock().Verify(i => i.TestMethod());""", - public abstract class AbstractInnerObject - { - public void Method() { } + """new Mock().Verify(i => i.TestMethod(), "The message");""", - public string Property { get => null; } + """new Mock().Verify(i => i.TestProperty);""", - public abstract void VirtualMethod(); + """new Mock().Verify(i => i.TestProperty, "The message");""", - public abstract string VirtualProperty { get; } - } + """new Mock().Verify(i => i.InnerObject.VirtualMethod());""", - public sealed class SealedInnerObject : AbstractInnerObject - { - public override void VirtualMethod() { } + """new Mock().Verify(i => i.InnerObject.VirtualMethod(), "The message");""", - public override string VirtualProperty => null; - } - }"; + """new Mock().Verify(i => i.InnerObject.VirtualProperty);""", - await Verifier.VerifyAnalyzerAsync(source); - } + """new Mock().Verify(i => i.InnerObject.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod());""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty);""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.VirtualMethod());""", + + """new Mock().Verify(i => i.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.VirtualProperty);""", + + """new Mock().Verify(i => i.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod());""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty);""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod());""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty);""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.VirtualMethod());""", + + """new Mock().Verify(i => i.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.VirtualProperty);""", + + """new Mock().Verify(i => i.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.AbstractMethod());""", + + """new Mock().Verify(i => i.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.AbstractProperty);""", + + """new Mock().Verify(i => i.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod());""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty);""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty, "The message");""", - [Fact] - public async Task NoMoqLibrary() + """new Mock().Verify(i => i.InnerObject.AbstractMethod());""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty);""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.VirtualMethod());""", + + """new Mock().Verify(i => i.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.VirtualProperty);""", + + """new Mock().Verify(i => i.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.AbstractMethod());""", + + """new Mock().Verify(i => i.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.AbstractProperty);""", + + """new Mock().Verify(i => i.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod());""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty);""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod());""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty);""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.VirtualMethod());""", + + """new Mock().Verify(i => i.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.VirtualProperty);""", + + """new Mock().Verify(i => i.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.AbstractMethod());""", + + """new Mock().Verify(i => i.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.AbstractProperty);""", + + """new Mock().Verify(i => i.AbstractProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod());""", + + """new Mock().Verify(i => i.InnerObject.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty);""", + + """new Mock().Verify(i => i.InnerObject.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod());""", + + """new Mock().Verify(i => i.InnerObject.AbstractMethod(), "The message");""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty);""", + + """new Mock().Verify(i => i.InnerObject.AbstractProperty, "The message");""", + + """new Mock(MockBehavior.Strict).Verify(i => i.Method());""", + ]; + + public static TheoryData InvalidTestCases => + [ + """new Mock().Verify(i => i.{|PosInfoMoq2008:Method|}());""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Method|}(), "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Property|});""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Property|}, "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:NonOverridableInnerObject|}.VirtualMethod());""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:NonOverridableInnerObject|}.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:NonOverridableInnerObject|}.VirtualProperty);""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:NonOverridableInnerObject|}.VirtualProperty, "The message");""", + + """new Mock().Verify(i => i.AbstractInnerObject.{|PosInfoMoq2008:Method|}());""", + + """new Mock().Verify(i => i.AbstractInnerObject.{|PosInfoMoq2008:Method|}(), "The message");""", + + """new Mock().Verify(i => i.AbstractInnerObject.{|PosInfoMoq2008:Property|});""", + + """new Mock().Verify(i => i.AbstractInnerObject.{|PosInfoMoq2008:Property|}, "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:SealedInnerObject|}.VirtualMethod());""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:SealedInnerObject|}.VirtualMethod(), "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:SealedInnerObject|}.VirtualProperty);""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:SealedInnerObject|}.VirtualProperty, "The message");""", + + """new Mock().Verify(i => StandardClass.{|PosInfoMoq2008:StaticMethod|}());""", + + """new Mock().Verify(i => StandardClass.{|PosInfoMoq2008:StaticMethod|}(), "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Method|}());""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Method|}(), "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Property|});""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:Property|}, "The message");""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:ExtensionMethod|}());""", + + """new Mock().Verify(i => i.{|PosInfoMoq2008:ExtensionMethod|}(), "The message");""", + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using Moq; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Verify(i => i.Method()); + {{code}} } } - public interface I - { - void Method(); - } + {{TestTypes}} } + """; - namespace OtherNamespace + await Verifier.VerifyAnalyzerAsync(source); + } + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) + { + var source = + $$""" + namespace ConsoleApplication1 { - public class Mock - { - public Mock(MockBehavior _) { } + using FakeMoqLibrary; - public void Verify(System.Action _) { } + public class TestClass + { + public void TestMethod() + { + {{code}} + } } - public enum MockBehavior { Strict, Loose } - }"; + {{TestTypes}} + } + + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index c53d130..6ef6733 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -122,6 +122,8 @@ public void Verify() { } public void Verify(Expression> expression, string failMessage = null) { } + public void Verify(Expression> expression, string failMessage = null) { } + public void Verify(Expression> expression, Times times, string failMessage = null) { } public void Verify(Expression> expression, Func times, string failMessage = null) { } From b786315473719eb029c50873cd26bb7b1b25cda3 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:40:32 +0200 Subject: [PATCH 13/30] Refactoring the MockInstanceShouldBeStrictBehaviorAnalyzerTest unit test --- ...tanceShouldBeStrictBehaviorAnalyzerTest.cs | 366 +++--------------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 2 + 2 files changed, 59 insertions(+), 309 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/MockInstanceShouldBeStrictBehaviorAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/MockInstanceShouldBeStrictBehaviorAnalyzerTest.cs index 5195069..2271b6a 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/MockInstanceShouldBeStrictBehaviorAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/MockInstanceShouldBeStrictBehaviorAnalyzerTest.cs @@ -10,371 +10,119 @@ namespace PosInformatique.Moq.Analyzers.Tests public class MockInstanceShouldBeStrictBehaviorAnalyzerTest { - [Fact] - public async Task NewMock_NoMock() - { - var source = @" - namespace ConsoleApplication1 - { - public class TestClass - { - public void TestMethod() - { - var obj = new object(); - } - } - }"; + private const string TestTypes = + """ + public interface I { } - await Verifier.VerifyAnalyzerAsync(source); - } + public class C : I { } + """; - [Theory] - [InlineData("")] - [InlineData(", 1, 2")] - public async Task NewMock_BehaviorStrict(string args) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + public static TheoryData ValidTestCases => + [ + """var obj = new object();""", - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict" + args + @"); - } - } + """string.Format("Ignored");""", - public interface I - { - } - }"; + """var mock = new Mock(MockBehavior.Strict);""", - await Verifier.VerifyAnalyzerAsync(source); - } + """var mock = new Mock(MockBehavior.Strict, 1, 2);""", - [Fact] - public async Task NewMock_BehaviorStrict_WithFactoryLambdaArgument() - { - var source = @" - namespace ConsoleApplication1 - { - using System; - using System.Linq.Expressions; - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(() => new C(), MockBehavior.Strict); - var mock2 = new Mock((Expression>)null, MockBehavior.Strict); - } - } - - public interface I - { - } + """var mock = new Mock(() => new C(), MockBehavior.Strict);""", - public class C : I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("Loose", "")] - [InlineData("Default", "")] - [InlineData("Loose", ", 1, 2")] - [InlineData("Default", ", 1, 2")] - public async Task NewMock_BehaviorDifferentOfStrict(string mode, string args) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """var mock = new Mock((Expression>)null, MockBehavior.Strict);""", - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock(MockBehavior." + mode + args + @")|]; - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("Loose")] - [InlineData("Default")] - public async Task NewMock_BehaviorDifferentOfStrict_WithFactoryLambdaArgument(string mode) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock(() => new C(), MockBehavior." + mode + @")|]; - } - } - - public interface I - { - } - - public class C : I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NewMock_NoBehavior() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock()|]; - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } + """var mock = Mock.Of(MockBehavior.Strict);""", - [Fact] - public async Task NewMock_NoBehavior_WithNullArgumentList() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """var mock = Mock.Of(i => true, MockBehavior.Strict);""", + ]; - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock { }|]; - } - } + public static TheoryData InvalidTestCases => + [ + """var mock = {|PosInfoMoq1001:new Mock(MockBehavior.Loose)|};""", - public interface I - { - } - }"; + """var mock = {|PosInfoMoq1001:new Mock(MockBehavior.Default)|};""", - await Verifier.VerifyAnalyzerAsync(source); - } + """var mock = {|PosInfoMoq1001:new Mock(MockBehavior.Loose, 1, 2)|};""", - [Fact] - public async Task NewMock_Behavior_NotMemberAccessExpression() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + """var mock = {|PosInfoMoq1001:new Mock(MockBehavior.Default, 1, 2)|};""", - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock(default, 1, 2)|]; - } - } + """var mock = {|PosInfoMoq1001:new Mock(() => new C(), MockBehavior.Loose)|};""", - public interface I - { - } - }"; + """var mock = {|PosInfoMoq1001:new Mock(() => new C(), MockBehavior.Default)|};""", - await Verifier.VerifyAnalyzerAsync(source); - } + """var mock = {|PosInfoMoq1001:new Mock()|};""", - [Fact] - public async Task NewMock_NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; + """var mock = {|PosInfoMoq1001:new Mock { }|};""", - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); - } - } + """var mock = {|PosInfoMoq1001:new Mock(default, 1, 2)|};""", - public interface I - { - } - } + """var mock = {|PosInfoMoq1001:Mock.Of(MockBehavior.Loose)|};""", - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - } + """var mock = {|PosInfoMoq1001:Mock.Of(MockBehavior.Default)|};""", - public enum MockBehavior { Strict, Loose } - }"; + """var mock = {|PosInfoMoq1001:Mock.Of(i => true, MockBehavior.Loose)|};""", - await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); - } + """var mock = {|PosInfoMoq1001:Mock.Of(i => true, MockBehavior.Default)|};""", - [Fact] - public async Task MockOf_NoMock() - { - var source = @" - namespace ConsoleApplication1 - { - public class TestClass - { - public void TestMethod() - { - string.Format(""Ignored""); - } - } - }"; + """var mock = {|PosInfoMoq1001:Mock.Of()|};""", - await Verifier.VerifyAnalyzerAsync(source); - } + """var mock = {|PosInfoMoq1001:Mock.Of(i => true)|};""", + ]; [Theory] - [InlineData("")] - [InlineData("i => true, ")] - public async Task MockOf_BehaviorStrict(string predicate) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; + using System; + using System.Linq.Expressions; public class TestClass { public void TestMethod() { - var mock1 = Mock.Of(" + predicate + @"MockBehavior.Strict); + {{code}} } } - public interface I - { - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } [Theory] - [InlineData("", "Loose")] - [InlineData("", "Default")] - [InlineData("i => true, ", "Loose")] - [InlineData("i => true, ", "Default")] - public async Task MockOf_BehaviorDifferentOfStrict(string predicate, string mode) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = [|Mock.Of(" + predicate + "MockBehavior." + mode + @")|]; - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task MockOf_NoBehavior() + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock()|]; - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task MockOf_NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; + using FakeMoqLibrary; + using System; + using System.Linq.Expressions; public class TestClass { public void TestMethod() { - var mock1 = Mock.Of(MockBehavior.Strict); + {{code}} } } - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public static T Of(MockBehavior behavior) { return default; } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 6ef6733..49267b7 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -29,6 +29,8 @@ public static class It public enum MockBehavior { Strict, + Loose, + Default = Loose, } public struct Times From 99fe6a25813bf991688dbfba16dbb945fd0bcc0a Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:40:46 +0200 Subject: [PATCH 14/30] Refactoring the MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTest unit tests --- ...sedOnlyToMockNonSealedClassAnalyzerTest.cs | 100 ++++++++---------- 1 file changed, 43 insertions(+), 57 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTest.cs index c4e6ba4..05a868e 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTest.cs @@ -10,101 +10,87 @@ namespace PosInformatique.Moq.Analyzers.Tests public class MockClassCanBeUsedOnlyToMockNonSealedClassAnalyzerTest { - [Fact] - public async Task NoSealedClass_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + private const string TestTypes = + """ + public interface I { } - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); + public class StandardClass { } - var mock2 = new Mock(); + public abstract class AbstractClass { } - var mock3 = new Mock(); + public sealed class SealedClass { } + """; - var obj = new object(); // Ignored by the analysis. - } - } + public static TheoryData ValidTestCases => + [ + """var mock = new Mock();""", - public interface I - { - } + """var mock = new Mock(MockBehavior.Strict);""", - public class StandardClass - { - } + """var mock = new Mock();""", - public abstract class AbstractClass - { - } - }"; + """var mock = new Mock();""", - await Verifier.VerifyAnalyzerAsync(source); - } + """var obj = new object();""", + ]; + + public static TheoryData InvalidTestCases => + [ + """var mock = new Mock<{|PosInfoMoq2002:SealedClass|}>();""", - [Fact] - public async Task SealedClass_DiagnosticReported() + """var mock = new Mock<{|PosInfoMoq2002:string|}>();""", + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { public void TestMethod() { - var mock1 = new Mock<[|SealedClass|]>(); - var mock2 = new Mock<[|string|]>(); + {{code}} } } - public sealed class SealedClass - { - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); + {{code}} } } - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } From 39601c6fca5c31a65d26a1b06aca376b47c04fd6 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:49:34 +0200 Subject: [PATCH 15/30] Refactoring CallBackDelegateMustMatchMockedMethodAnalyzerTest unit test --- ...legateMustMatchMockedMethodAnalyzerTest.cs | 602 +++++++++++------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 13 +- 2 files changed, 397 insertions(+), 218 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateMustMatchMockedMethodAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateMustMatchMockedMethodAnalyzerTest.cs index 5eb920c..842fb67 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateMustMatchMockedMethodAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateMustMatchMockedMethodAnalyzerTest.cs @@ -11,200 +11,378 @@ namespace PosInformatique.Moq.Analyzers.Tests public class CallBackDelegateMustMatchMockedMethodAnalyzerTest { - [Theory] - [InlineData("")] - [InlineData(".InSequence(sequence)")] - public async Task CallBackSignatureMatch_NoDiagnosticReported(string sequence) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var sequence = new MockSequence(); + private const string TestTypes = + """ + public interface I + { + void TestMethod(); - var mock1 = new Mock(); - - mock1" + sequence + @".Setup(m => m.TestMethod()) - .Callback(() => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(default)) - .Callback((string x) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(default, default)) - .Callback((string x, int y) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestGenericMethod(1234)) - .Callback((int x) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestGenericMethod(It.IsAny())) - .Callback((object x) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethodWithDefaultParameters(""A"", 10)) - .Callback((string x, int y, int z, string w) => { }) - .Throws(new Exception()); - - mock1" + sequence + @".Setup(m => m.TestMethodReturn()) - .Callback(() => { }) - .Returns(1234); - mock1" + sequence + @".Setup(m => m.TestMethodReturn(default)) - .Callback((string x) => { }) - .Returns(1234); - mock1" + sequence + @".Setup(m => m.TestMethodReturn(default, default)) - .Callback((string x, int y) => { }) - .Returns(1234); - - // Special case add a Verify() method inside the Callback() method. - var innerMock = new Mock(); - - mock1.Setup(m => m.TestMethod()) - .Callback(() => { innerMock.Verify(im => im.TestMethod(""a"")); }); - } - } + void TestMethod(string a); - public interface I - { - void TestMethod(); + void TestMethod(string a, int b); - void TestMethod(string a); + void TestGenericMethod(T value); - void TestMethod(string a, int b); + void TestMethodWithDefaultParameters(string a, int b, int c = 42, string d = "default"); - void TestGenericMethod(T value); + int TestMethodReturn(); - void TestMethodWithDefaultParameters(string a, int b, int c = 42, string d = ""default""); + int TestMethodReturn(string a); - int TestMethodReturn(); + int TestMethodReturn(string a, int b); + } - int TestMethodReturn(string a); + public static class MoqExtensions + { + public static ISetup MySetup(this Mock mock, Expression> exp) + where T : class + { + return mock.Setup(exp); + } + } + + public interface IRepository + { + void Get(string s); + } + """; + + public static TheoryData ValidTestCases => + [ + """ + mock.Setup(m => m.TestMethod()) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod()) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethod(default)) + .Callback((string x) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(default)) + .Callback((string x) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethod(default, default)) + .Callback((string x, int y) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(default, default)) + .Callback((string x, int y) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestGenericMethod(1234)) + .Callback((int x) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestGenericMethod(1234)) + .Callback((int x) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestGenericMethod(It.IsAny())) + .Callback((object x) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestGenericMethod(It.IsAny())) + .Callback((object x) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethodWithDefaultParameters("A", 10)) + .Callback((string x, int y, int z, string w) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodWithDefaultParameters("A", 10)) + .Callback((string x, int y, int z, string w) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethodReturn()) + .Callback(() => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn()) + .Callback(() => { }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn(default)) + .Callback((string x) => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn(default)) + .Callback((string x) => { }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn(default, default)) + .Callback((string x, int y) => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn(default, default)) + .Callback((string x, int y) => { }) + .Returns(1234); + """, + + """ + var innerMock = new Mock(); + mock.Setup(m => m.TestMethod()) + .Callback(() => { innerMock.Verify(im => im.TestMethod("a")); }); + """, + + """ + var repositoryMock = new Mock(MockBehavior.Strict); + repositoryMock.MySetup(i => i.Get("Foobar")) + .Callback(() => + { + }); + """, + + """ + var strictMock = new Mock(MockBehavior.Strict); + strictMock.Setup(m => m.TestMethod()); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + mock.Setup(m => m.TestMethod()) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod()) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethod(default)) + .Callback({|PosInfoMoq2003:()|} => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(default)) + .Callback({|PosInfoMoq2003:()|} => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethod(default)) + .Callback(({|PosInfoMoq2003:int otherType|}) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(default)) + .Callback(({|PosInfoMoq2003:int otherType|}) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethod(default)) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(default)) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestGenericMethod(1234)) + .Callback(({|PosInfoMoq2003:string x|}) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestGenericMethod(1234)) + .Callback(({|PosInfoMoq2003:string x|}) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestGenericMethod(It.IsAny())) + .Callback(({|PosInfoMoq2003:string x|}) => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestGenericMethod(It.IsAny())) + .Callback(({|PosInfoMoq2003:string x|}) => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethodWithDefaultParameters("A", 10)) + .Callback({|PosInfoMoq2003:(string x, int y)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodWithDefaultParameters("A", 10)) + .Callback({|PosInfoMoq2003:(string x, int y)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethodWithDefaultParameters("A", 10)) + .Callback({|PosInfoMoq2003:(string x, int y, string z)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodWithDefaultParameters("A", 10)) + .Callback({|PosInfoMoq2003:(string x, int y, string z)|} => { }) + .Throws(new Exception()); + """, + + """ + mock.Setup(m => m.TestMethodReturn()) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn()) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn(default)) + .Callback({|PosInfoMoq2003:()|} => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn(default)) + .Callback({|PosInfoMoq2003:()|} => { }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn(default)) + .Callback(({|PosInfoMoq2003:int otherType|}) => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn(default)) + .Callback(({|PosInfoMoq2003:int otherType|}) => { }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn(default)) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn(default)) + .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn()) + .Callback(() => { {|PosInfoMoq2014:return false;|} }) + .Returns(1234); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn()) + .Callback(() => { {|PosInfoMoq2014:return false;|} }) + .Returns(1234); + """, + + """ + mock.Setup(m => m.TestMethodReturn()) + .Callback(() => + { + var b = false; + if (b) + { + for (int i = 0; i < 10; i++) + { + if (i == 0) {|#0:return false;|}; + } - int TestMethodReturn(string a, int b); + {|#1:return false;|} } - }"; - await Verifier.VerifyAnalyzerAsync(source); - } + {|#2:return true;|} + }) + .Returns(1234); + """, - [Theory] - [InlineData("")] - [InlineData(".InSequence(sequence)")] - public async Task CallBackSignatureNotMatch_DiagnosticReported(string sequence) - { - var source = @" - namespace ConsoleApplication1 + """ + mock.InSequence(sequence).Setup(m => m.TestMethodReturn()) + .Callback(() => { - using Moq; - using System; - - public class TestClass + var b = false; + if (b) { - public void TestMethod() + for (int i = 0; i < 10; i++) { - var sequence = new MockSequence(); - - var mock1 = new Mock(); - - mock1" + sequence + @".Setup(m => m.TestMethod()) - .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(default)) - .Callback({|PosInfoMoq2003:()|} => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(default)) - .Callback(({|PosInfoMoq2003:int otherType|}) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethod(default)) - .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestGenericMethod(1234)) - .Callback(({|PosInfoMoq2003:string x|}) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestGenericMethod(It.IsAny())) - .Callback(({|PosInfoMoq2003:string x|}) => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethodWithDefaultParameters(""A"", 10)) - .Callback({|PosInfoMoq2003:(string x, int y)|} => { }) - .Throws(new Exception()); - mock1" + sequence + @".Setup(m => m.TestMethodWithDefaultParameters(""A"", 10)) - .Callback({|PosInfoMoq2003:(string x, int y, string z)|} => { }) - .Throws(new Exception()); - - mock1" + sequence + @".Setup(m => m.TestMethodReturn()) - .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) - .Returns(1234); - mock1" + sequence + @".Setup(m => m.TestMethodReturn(default)) - .Callback({|PosInfoMoq2003:()|} => { }) - .Returns(1234); - mock1" + sequence + @".Setup(m => m.TestMethodReturn(default)) - .Callback(({|PosInfoMoq2003:int otherType|}) => { }) - .Returns(1234); - mock1" + sequence + @".Setup(m => m.TestMethodReturn(default)) - .Callback({|PosInfoMoq2003:(int too, int much, int parameters)|} => { }) - .Returns(1234); - - // Callback with return value - mock1" + sequence + @".Setup(m => m.TestMethodReturn()) - .Callback(() => { {|PosInfoMoq2014:return false;|} }) - .Returns(1234); - mock1" + sequence + @".Setup(m => m.TestMethodReturn()) - .Callback(() => - { - var b = false; - if (b) - { - for (int i=0; i<10; i++) - { - if (i == 0) {|#0:return false;|}; - } - - {|#1:return false;|} - } - - {|#2:return true;|} - }) - .Returns(1234); + if (i == 0) {|#0:return false;|}; } - } - - public interface I - { - void TestMethod(); - - void TestMethod(string a); - - void TestMethod(string a, int b); - - void TestGenericMethod(T value); - - void TestMethodWithDefaultParameters(string a, int b, int c = 42, string d = ""default""); - int TestMethodReturn(); - - int TestMethodReturn(string a); - - int TestMethodReturn(string a, int b); + {|#1:return false;|} } - }"; - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(CallBackDelegateMustMatchMockedMethodAnalyzer.CallbackMustNotReturnValue) - .WithLocation(0) - .WithLocation(1) - .WithLocation(2), - ]); - } + {|#2:return true;|} + }) + .Returns(1234); + """, + ]; - [Fact] - public async Task CallBackWithCustomSetupMethod_NoDiagnosticReported() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -216,70 +394,60 @@ public class TestClass { public void TestMethod() { - var m = new Mock(MockBehavior.Strict); - - m.MySetup(i => i.Get(""Foobar"")) - .Callback(() => - { - }); - } - } - - public static class MoqExtensions - { - public static ISetup MySetup(this Mock mock, Expression> exp) - where T : class - { - return mock.Setup(exp); + var mock = new Mock(); + var sequence = new MockSequence(); + {{code}} } } - public interface IRepository - { - void Get(string s); - } + {{TestTypes}} } - "; + """; - await Verifier.VerifyAnalyzerAsync(source); + if (code.Contains("{|#0:", StringComparison.Ordinal)) + { + await Verifier.VerifyAnalyzerAsync( + source, + new DiagnosticResult(CallBackDelegateMustMatchMockedMethodAnalyzer.CallbackMustNotReturnValue) + .WithLocation(0) + .WithLocation(1) + .WithLocation(2)); + } + else + { + await Verifier.VerifyAnalyzerAsync(source); + } } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; + using FakeMoqLibrary.Language.Flow; + using System; + using System.Linq.Expressions; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(m => m.TestMethod()); + var mock = new Mock(); + var sequence = new MockSequence(); + {{code}} } } - public interface I - { - void TestMethod(); - } + {{TestTypes}} } - namespace OtherNamespace - { - using System; - - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup(Action act) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 49267b7..592ac6b 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -19,6 +19,8 @@ namespace FakeMoqLibrary public static class It { + public class IsAnyType { } + public static TValue IsAny() { return default; } public static TValue Is(Expression> match) { return default; } @@ -48,12 +50,18 @@ public class SetupResult { public SetupResult Callback(Action callback) { return this; } + public SetupResult Callback(Delegate callback) { return this; } + public SetupResult Callback(Action callback) { return this; } public SetupResult Callback(Action callback) { return this; } + public SetupResult Callback(Action callback) { return this; } + public SetupResult Callback(Action callback) { return this; } + public void Returns(TResult value) { } + public void Throws(Exception exception) { } public void Verifiable() { } @@ -134,7 +142,10 @@ public void Verify(Expression> expression, Func times, string f namespace FakeMoqLibrary.Language.Flow { - public interface ISetup { } + public interface ISetup + { + SetupResult Callback(System.Action callback); + } } namespace FakeMoqLibrary.Protected From 34e75b00d2759f886c05fddaec6abc4c942fd0db Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:53:54 +0200 Subject: [PATCH 16/30] Refactoring the CallBackDelegateParametersShouldNotBeIgnoredAnalyzerTest unit tests --- ...arametersShouldNotBeIgnoredAnalyzerTest.cs | 207 +++++++++--------- 1 file changed, 102 insertions(+), 105 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateParametersShouldNotBeIgnoredAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateParametersShouldNotBeIgnoredAnalyzerTest.cs index b3de61d..22f0e6f 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateParametersShouldNotBeIgnoredAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateParametersShouldNotBeIgnoredAnalyzerTest.cs @@ -6,143 +6,140 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class CallBackDelegateParametersShouldNotBeIgnoredAnalyzerTest { - [Fact] - public async Task NotUsedParameters_DiagnosticReported() + private const string TestTypes = + """ + public interface I + { + void TestMethod(); + + void TestMethod(string a); + + void TestMethod(string a, int b); + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod(It.IsAny())) + .Callback((string a) => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) + .Callback((string a, int b) => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod("OK", It.IsAny())) + .Callback((string _, int b) => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod(It.IsAny(), 1234)) + .Callback((string a, int _) => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod()); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + mock.Setup(m => m.TestMethod()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod("OK", 1234)); + """, + + """ + var o = new object(); + o.ToString(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) + .Callback(({|PosInfoMoq1004:string _|}, {|PosInfoMoq1004:int _|}) => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod("OK", It.IsAny())) + .Callback((string _, {|PosInfoMoq1004:int _|}) => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.TestMethod(It.IsAny(), 1234)) + .Callback(({|PosInfoMoq1004:string _|}, int _) => { }); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) - .Callback(({|#0:string _|#0}, {|#1:int _|#1}) => { }); - mock1.Setup(m => m.TestMethod(""OK"", It.IsAny())) - .Callback((string _, {|#2:int _|#2}) => { }); - mock1.Setup(m => m.TestMethod(It.IsAny(), 1234)) - .Callback(({|#3:string _|#3}, int _) => { }); - } - } - - public interface I - { - void TestMethod(string a); - - void TestMethod(string a, int b); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(CallBackDelegateParametersShouldNotBeIgnoredAnalyzer.Rule) - .WithLocation(0) - .WithArguments("a"), - new DiagnosticResult(CallBackDelegateParametersShouldNotBeIgnoredAnalyzer.Rule) - .WithLocation(1) - .WithArguments("b"), - new DiagnosticResult(CallBackDelegateParametersShouldNotBeIgnoredAnalyzer.Rule) - .WithLocation(2) - .WithArguments("b"), - new DiagnosticResult(CallBackDelegateParametersShouldNotBeIgnoredAnalyzer.Rule) - .WithLocation(3) - .WithArguments("a"), - ]); - } - - [Fact] - public async Task UsedParameters_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(m => m.TestMethod(It.IsAny())) - .Callback((string a) => { }); - mock1.Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) - .Callback((string a, int b) => { }); - mock1.Setup(m => m.TestMethod(""OK"", It.IsAny())) - .Callback((string _, int b) => { }); - mock1.Setup(m => m.TestMethod(It.IsAny(), 1234)) - .Callback((string a, int _) => { }); - - var mock2 = new Mock(); - mock2.Setup(m => m.TestMethod()); - - var mock3 = new Mock(); - mock3.Setup(m => m.TestMethod(""OK"", 1234)); - - var o = new object(); - o.ToString(); // Ignored - } + {{code}} + } } - public interface I - { - void TestMethod(); - - void TestMethod(string a); - - void TestMethod(string a, int b); - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(m => m.TestMethod()); + {{code}} } } - public interface I - { - void TestMethod(); - } + {{TestTypes}} } - namespace OtherNamespace - { - using System; - - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup(Action act) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } From ed46973d0e66908fe9cf77fbf09e7c1fbf9ceec9 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 22:59:15 +0200 Subject: [PATCH 17/30] Refactoring of the CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzerTest unit tests --- ...BeUsedWithItIsAnyParametersAnalyzerTest.cs | 257 ++++++++---------- 1 file changed, 107 insertions(+), 150 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzerTest.cs index 8cb90a9..679222e 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzerTest.cs @@ -6,123 +6,112 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzerTest { - [Fact] - public async Task NoCallback_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + private const string TestTypes = + """ + public interface I + { + void TestMethod(); - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(m => m.TestMethod({|#0:It.IsAny()|#0}, {|#1:It.IsAny()|#1})); - mock1.Setup(m => m.TestMethod(""Ignored"", {|#2:It.IsAny()|#2})); - mock1.Setup(m => m.TestMethod({|#3:It.IsAny()|#3}, 1234)); - mock1.Setup(m => m.TestMethod({|#4:It.IsAny()|#4})); - } - } + void TestMethod(string a); - public interface I - { - void TestMethod(string a); + void TestMethod(string a, int b); + } + """; - void TestMethod(string a, int b); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(0) - .WithArguments("a"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(1) - .WithArguments("b"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(2) - .WithArguments("b"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(3) - .WithArguments("a"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(4) - .WithArguments("a"), - ]); - } + public static TheoryData ValidTestCases => + [ + """ + mock.Setup(m => m.TestMethod(It.IsAny())) + .Callback(() => { }); + """, - [Fact] - public async Task NoCallback_DiagnosticReported_WithSequence() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(It.IsAny())) + .Callback(() => { }); + """, - public class TestClass - { - public void TestMethod() - { - var sequence = new MockSequence(); + """ + mock.Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) + .Callback(() => { }); + """, - var mock1 = new Mock(); - mock1.InSequence(sequence).Setup(m => m.TestMethod({|#0:It.IsAny()|#0}, {|#1:It.IsAny()|#1})); - mock1.InSequence(sequence).Setup(m => m.TestMethod(""Ignored"", {|#2:It.IsAny()|#2})); - mock1.InSequence(sequence).Setup(m => m.TestMethod({|#3:It.IsAny()|#3}, 1234)); - mock1.InSequence(sequence).Setup(m => m.TestMethod({|#4:It.IsAny()|#4})); - } - } + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) + .Callback(() => { }); + """, - public interface I - { - void TestMethod(string a); + """ + mock.Setup(m => m.TestMethod("OK", It.IsAny())) + .Callback(() => { }); + """, - void TestMethod(string a, int b); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - [ - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(0) - .WithArguments("a"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(1) - .WithArguments("b"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(2) - .WithArguments("b"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(3) - .WithArguments("a"), - new DiagnosticResult(CallBackDelegateShouldBeUsedWithItIsAnyParametersAnalyzer.Rule) - .WithLocation(4) - .WithArguments("a"), - ]); - } + """ + mock.InSequence(sequence).Setup(m => m.TestMethod("OK", It.IsAny())) + .Callback(() => { }); + """, + + """ + mock.Setup(m => m.TestMethod(It.IsAny(), 1234)) + .Callback(() => { }); + """, + + """ + mock.InSequence(sequence).Setup(m => m.TestMethod(It.IsAny(), 1234)) + .Callback(() => { }); + """, + + """mock.Setup(m => m.TestMethod());""", + + """mock.InSequence(sequence).Setup(m => m.TestMethod());""", + + """mock.Setup(m => m.TestMethod("OK", 1234));""", + + """mock.InSequence(sequence).Setup(m => m.TestMethod("OK", 1234));""", + + """ + var strictMock = new Mock(MockBehavior.Strict); + strictMock.Setup(m => m.TestMethod()); + """, + + """ + var o = new object(); + o.ToString(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """mock.Setup(m => m.TestMethod({|PosInfoMoq1003:It.IsAny()|}, {|PosInfoMoq1003:It.IsAny()|}));""", + + """mock.InSequence(sequence).Setup(m => m.TestMethod({|PosInfoMoq1003:It.IsAny()|}, {|PosInfoMoq1003:It.IsAny()|}));""", + + """mock.Setup(m => m.TestMethod("Ignored", {|PosInfoMoq1003:It.IsAny()|}));""", + + """mock.InSequence(sequence).Setup(m => m.TestMethod("Ignored", {|PosInfoMoq1003:It.IsAny()|}));""", + + """mock.Setup(m => m.TestMethod({|PosInfoMoq1003:It.IsAny()|}, 1234));""", + + """mock.InSequence(sequence).Setup(m => m.TestMethod({|PosInfoMoq1003:It.IsAny()|}, 1234));""", + + """mock.Setup(m => m.TestMethod({|PosInfoMoq1003:It.IsAny()|}));""", + + """mock.InSequence(sequence).Setup(m => m.TestMethod({|PosInfoMoq1003:It.IsAny()|}));""", + ]; [Theory] - [InlineData("")] - [InlineData(".InSequence(sequence)")] - public async Task Callback_NoDiagnosticReported(string sequence) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; - using System; public class TestClass { @@ -130,76 +119,44 @@ public void TestMethod() { var sequence = new MockSequence(); - var mock1 = new Mock(); - mock1" + sequence + @".Setup(m => m.TestMethod(It.IsAny())) - .Callback(() => { }); - mock1" + sequence + @".Setup(m => m.TestMethod(It.IsAny(), It.IsAny())) - .Callback(() => { }); - mock1" + sequence + @".Setup(m => m.TestMethod(""OK"", It.IsAny())) - .Callback(() => { }); - mock1" + sequence + @".Setup(m => m.TestMethod(It.IsAny(), 1234)) - .Callback(() => { }); - - var mock2 = new Mock(); - mock2" + sequence + @".Setup(m => m.TestMethod()); - - var mock3 = new Mock(); - mock3" + sequence + @".Setup(m => m.TestMethod(""OK"", 1234)); - - var o = new object(); - o.ToString(); // Ignored - } + var mock = new Mock(); + {{code}} + } } - public interface I - { - void TestMethod(); - - void TestMethod(string a); - - void TestMethod(string a, int b); - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(m => m.TestMethod()); + var sequence = new MockSequence(); + var mock = new Mock(); + {{code}} } } - public interface I - { - void TestMethod(); - } + {{TestTypes}} } - namespace OtherNamespace - { - using System; - - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup(Action act) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } From be925ec60965f5ae3e7b725b77d9ba800411b701 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 23:05:12 +0200 Subject: [PATCH 18/30] Refactoring of the ReturnsMethodDelegateMustMatchMockedMethodAnalyzerTest unit tests --- ...legateMustMatchMockedMethodAnalyzerTest.cs | 550 ++++++------------ .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 4 + 2 files changed, 197 insertions(+), 357 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/ReturnsMethodDelegateMustMatchMockedMethodAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/ReturnsMethodDelegateMustMatchMockedMethodAnalyzerTest.cs index 242f738..d602523 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/ReturnsMethodDelegateMustMatchMockedMethodAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/ReturnsMethodDelegateMustMatchMockedMethodAnalyzerTest.cs @@ -6,331 +6,206 @@ namespace PosInformatique.Moq.Analyzers.Tests { - using Microsoft.CodeAnalysis.Testing; using Verifier = MoqCSharpAnalyzerVerifier; public class ReturnsMethodDelegateMustMatchMockedMethodAnalyzerTest { - [Theory] - [InlineData("Returns", "int")] - [InlineData("ReturnsAsync", "int")] - [InlineData("Returns", "object")] - [InlineData("ReturnsAsync", "object")] - public async Task Returns_ValidReturnsType_Method_NoDiagnosticReported(string methodName, string returnType) - { - if (methodName == "ReturnsAsync") + private const string TestTypes = + """ + public interface I { - returnType = "Task<" + returnType + ">"; - } - - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System.Threading.Tasks; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod()) - .Callback(() => { }) - ." + methodName + @"(() => { return 1234; }); - } - } - - public interface I - { - " + returnType + @" TestMethod(); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("1234")] - [InlineData("\"Foobar\"")] - public async Task Returns_ValidReturnsType_Method_Generic_NoDiagnosticReported(string value) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System.Threading.Tasks; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod()) - .Callback(() => { }) - .Returns(() => { return " + value + @"; }); - } - } - - public interface I - { - T TestMethod(); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } + int TestMethod(); - [Fact] - public async Task Returns_InvalidReturnsType_Method_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; + int TestMethod(string a); - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod()) - .Callback(() => { }) - .Returns({|#0:() => { return ""Foobar""; }|#0}); - } - } + T TestMethod(); - public interface I - { - int TestMethod(); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - new DiagnosticResult(ReturnsMethodDelegateMustMatchMockedMethodAnalyzer.ReturnValueMustMatchRule) - .WithLocation(0) - .WithArguments("Int32")); - } - - [Fact] - public async Task Returns_InvalidReturnsType_Property_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestProperty) - .Callback(() => { }) - .Returns({|#0:() => { return ""Foobar""; }|#0}); - } - } - - public interface I - { - int TestProperty { get; set; } - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source, - new DiagnosticResult(ReturnsMethodDelegateMustMatchMockedMethodAnalyzer.ReturnValueMustMatchRule) - .WithLocation(0) - .WithArguments("Int32")); - } - - [Theory] - [InlineData("TestProperty")] - [InlineData("GetData()")] - public async Task Returns_ValidReturnsValue_NoDiagnosticReported(string member) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i." + member + @") - .Callback(() => { }) - .Returns(1234); - } - } - - public interface I - { - int GetData(); - - int TestProperty { get; set; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Returns_ValidReturnsType_Property_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestProperty) - .Callback(() => { }) - .Returns(() => { return 1234; }); - } - } + int GetData(); - public interface I - { - int TestProperty { get; set; } - } - }"; + int TestProperty { get; set; } + } - await Verifier.VerifyAnalyzerAsync(source); - } + public interface IAsync + { + Task TestMethod(); - [Theory] - [InlineData("Returns")] - [InlineData("ReturnsAsync")] - public async Task Returns_InvalidArgumentType_DiagnosticReported(string methodName) - { - var returnType = "int"; + Task TestMethod(string a); + } - if (methodName == "ReturnsAsync") + public interface IObject { - returnType = "Task<" + returnType + ">"; + object TestMethod(); } - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System.Threading.Tasks; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod(""Ignored"")) - .Callback(() => { }) - ." + methodName + @"(({|PosInfoMoq2013:int s|}) => { return 1234; }); - } - } - - public interface I - { - " + returnType + @" TestMethod(string a); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("Returns")] - [InlineData("ReturnsAsync")] - public async Task Returns_DifferentArgumentCount_DiagnosticReported(string methodName) - { - var returnType = "int"; - - if (methodName == "ReturnsAsync") + public interface IAsyncObject { - returnType = "Task<" + returnType + ">"; + Task TestMethod(); } - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System.Threading.Tasks; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod(""Ignored"")) - .Callback(() => { }) - ." + methodName + @"({|PosInfoMoq2013:(int s, bool b)|} => { return 1234; }); - } - } - - public interface I - { - " + returnType + @" TestMethod(string a); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("Returns")] - [InlineData("ReturnsAsync")] - public async Task Returns_ValidArgumentType_NoDiagnosticReported(string methodName) - { - var returnType = "int"; - - if (methodName == "ReturnsAsync") + public class CustomMock { - returnType = "Task<" + returnType + ">"; + public void Setup() { } } - - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System.Threading.Tasks; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod(""Ignored"")) - .Callback(() => { }) - ." + methodName + @"((string z) => { return 1234; }); - } - } - - public interface I - { - " + returnType + @" TestMethod(string a); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Returns(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .ReturnsAsync(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Returns(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .ReturnsAsync(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Returns(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Returns(() => { return "Foobar"; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestProperty) + .Callback(() => { }) + .Returns(1234); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestProperty) + .Callback(() => { }) + .Returns(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.GetData()) + .Callback(() => { }) + .Returns(1234); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .Returns((string z) => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .ReturnsAsync((string z) => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .Returns(() => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .ReturnsAsync(() => { return 1234; }); + """, + + """ + var mock = new CustomMock(); + mock.Setup(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Returns({|PosInfoMoq2012:() => { return "Foobar"; }|}); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestProperty) + .Callback(() => { }) + .Returns({|PosInfoMoq2012:() => { return "Foobar"; }|}); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .Returns(({|PosInfoMoq2013:int s|}) => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .ReturnsAsync(({|PosInfoMoq2013:int s|}) => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .Returns({|PosInfoMoq2013:(int s, bool b)|} => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod("Ignored")) + .Callback(() => { }) + .ReturnsAsync({|PosInfoMoq2013:(int s, bool b)|} => { return 1234; }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestProperty) + .Callback(() => { }) + .Returns({|PosInfoMoq2013:(int s)|} => { return 1234; }); + """, + ]; [Theory] - [InlineData("Returns")] - [InlineData("ReturnsAsync")] - public async Task Returns_WithNoArgument_NoDiagnosticReported(string methodName) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var returnType = "int"; - - if (methodName == "ReturnsAsync") - { - returnType = "Task<" + returnType + ">"; - } - - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -340,81 +215,42 @@ public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Setup(i => i.TestMethod(""Ignored"")) - .Callback(() => { }) - ." + methodName + @"(() => { return 1234; }); + {{code}} } } - public interface I - { - " + returnType + @" TestMethod(string a); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Returns_WithArgumentsForProperty_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(i => i.TestProperty) - .Callback(() => { }) - .Returns({|PosInfoMoq2013:(int s)|} => { return 1234; }); - } - } - - public interface I - { - int TestProperty { get; set; } - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; + using System.Threading.Tasks; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Setup(); + {{code}} } } - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock() { } - - public void Setup() { } - } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 592ac6b..773446d 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -62,6 +62,10 @@ public class SetupResult public void Returns(TResult value) { } + public void Returns(Delegate valueFunction) { } + + public void ReturnsAsync(Delegate valueFunction) { } + public void Throws(Exception exception) { } public void Verifiable() { } From 734795cfbb50964bb32f61a7bb2077c42c107675 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 23:09:10 +0200 Subject: [PATCH 19/30] Refactoring of the SetupMethodMustReturnValueWithStrictBehaviorAnalyzerTest unit tests --- ...turnValueWithStrictBehaviorAnalyzerTest.cs | 550 +++++++++--------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 4 + 2 files changed, 274 insertions(+), 280 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodMustReturnValueWithStrictBehaviorAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodMustReturnValueWithStrictBehaviorAnalyzerTest.cs index 3c7ef17..0613e39 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodMustReturnValueWithStrictBehaviorAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/SetupMethodMustReturnValueWithStrictBehaviorAnalyzerTest.cs @@ -11,85 +11,257 @@ namespace PosInformatique.Moq.Analyzers.Tests public class SetupMethodMustReturnValueWithStrictBehaviorAnalyzerTest { - [Fact] - public async Task Returns_StrictMode_NoDiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 + private const string TestTypes = + """ + public interface I + { + int TestMethod(); + + Task TestAsyncMethod(); + + int TestProperty { get; set; } + + int Property { get; set; } + } + + public interface IVoid + { + void TestMethod(); + } + + public enum OtherEnum { A, B } + + public class CustomMock + { + public CustomMock(MockBehavior behavior) { } + + public void Setup() { } + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Returns(1234); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestAsyncMethod()) + .Callback(() => { }) + .ReturnsAsync(1234); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestProperty) + .Callback(() => { }) + .Returns(1234); + """, + + """var mock = new Mock(MockBehavior.Strict);""", + + """ + Mock mock; + mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var original = new Mock(MockBehavior.Strict); + Mock mock = original; + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + Mock mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }) + .Throws(new Exception()); + """, + + """ + Mock mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestAsyncMethod()) + .Callback(() => { }) + .ThrowsAsync(new Exception()); + """, + + """ + var obj = new object(); + obj.ToString(); + """, + + """ + var action = new Action(() => { }); + action(); + """, + + """ + var mock = new Mock(MockBehavior.Loose); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose); + mock.Setup(i => i.TestProperty) + .Callback(() => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestProperty) + .Callback(() => { }); + """, + + """ + var mock = new Mock(1, 2); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(1, 2); + mock.Setup(i => i.TestProperty) + .Callback(() => { }); + """, + + """ + var mock = new Mock(OtherEnum.A, 1, 2); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(OtherEnum.A, 1, 2); + mock.Setup(i => i.TestProperty) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose, 1, 2); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose, 1, 2); + mock.Setup(i => i.TestProperty) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Strict, 1, 2); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose, 1, 2); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.TestMethod()) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose); + mock.Setup(i => i.Property) + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Loose, 1, 2); + mock.Setup(i => i.Property) + .Callback(() => { }); + """, + + """ + var mock = new Mock(); + mock.Setup(i => i.Property) + .Callback(() => { }); + """, + + """ + var mock = new Mock(); + mock.Verify(); + """, + + """ + var mock = new CustomMock(MockBehavior.Strict); + mock.Setup(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = new Mock(MockBehavior.Strict); + {|PosInfoMoq2000:mock.Setup(i => i.TestMethod())|} + .Callback(() => { }); + """, + + """ + var mock = new Mock(MockBehavior.Strict); + {|PosInfoMoq2000:mock.Setup(i => i.TestProperty)|} + .Callback(() => { }); + """, + + """ + var mock = new Mock(); + var mock1 = new Mock(MockBehavior.Strict); + var mock2 = new Mock(MockBehavior.Strict); + { { - using Moq; - using System; - using System.Threading.Tasks; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(i => i.TestMethod()) - .Callback(() => { }) - .Returns(1234); - - var mock2 = new Mock(MockBehavior.Strict); - mock2.Setup(i => i.TestAsyncMethod()) - .Callback(() => { }) - .ReturnsAsync(1234); - - var mock3 = new Mock(MockBehavior.Strict); - - // This scenario is not supported because the declaration is separated of the initialization. - // So here, no error should be raised (Missing Returns() with Strict behavior). - Mock mock4; - mock4 = new Mock(MockBehavior.Strict); - mock4.Setup(i => i.TestMethod()) - .Callback(() => { }); - - // This scenario is not supported because the declaration is separated of the initialization. - // So here, no error should be raised (Missing Returns() with Strict behavior). - Mock mock5 = mock1; - mock5.Setup(i => i.TestMethod()) - .Callback(() => { }); - - Mock mock6 = new Mock(MockBehavior.Strict); - mock6.Setup(i => i.TestMethod()) - .Callback(() => { }) - .Throws(new Exception()); - - Mock mock7 = new Mock(MockBehavior.Strict); - mock7.Setup(i => i.TestAsyncMethod()) - .Callback(() => { }) - .ThrowsAsync(new Exception()); - - var mock8 = new Mock(MockBehavior.Strict); - mock8.Setup(i => i.TestProperty) - .Callback(() => { }) - .Returns(1234); - - var obj = new object(); // Ignored because not a Mock - obj.ToString(); - - var action = new Action(() => { }); - action(); // InvocationExpression ignored - } - } - - public interface I - { - int TestMethod(); + {|PosInfoMoq2000:mock1.Setup(i => i.TestMethod())|} + .Callback(() => { }); - Task TestAsyncMethod(); + {|PosInfoMoq2000:mock1.Setup(i => i.TestProperty)|} + .Callback(() => { }); + } + } - int TestProperty { get; set; } - } - }"; + {|PosInfoMoq2000:mock2.Setup(i => i.TestMethod())|} + .Callback(() => { }); - await Verifier.VerifyAnalyzerAsync(source); - } + {|PosInfoMoq2000:mock2.Setup(i => i.TestProperty)|} + .Callback(() => { }); + """, + ]; [Fact] public async Task Returns_StrictMode_InvalidReturnsType_NoDiagnosticReported() { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -101,10 +273,10 @@ public void TestMethod() var mock1 = new Mock(MockBehavior.Strict); mock1.Setup(i => i.TestMethod()) .Callback(() => { }) - .Returns({|#0:""Foobar""|#0}); + .Returns({|#0:"Foobar"|}); mock1.Setup(i => i.TestProperty) .Callback(() => { }) - .Returns({|#1:""Foobar""|#1}); + .Returns({|#1:"Foobar"|}); } } @@ -114,7 +286,8 @@ public interface I int TestProperty { get; set; } } - }"; + } + """; await Verifier.VerifyAnalyzerAsync( source, @@ -122,243 +295,60 @@ await Verifier.VerifyAnalyzerAsync( DiagnosticResult.CompilerError("CS1503").WithLocation(1).WithArguments("1", "string", "int")); } - [Fact] - public async Task NoReturns_WithBlocksAndMixedBeahviors_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - using System; - - public class TestClass - { - public void TestMethod() - { - var mock = new Mock(); - - var mock1 = new Mock(MockBehavior.Strict); - var mock2 = new Mock(MockBehavior.Strict); - { - { - [|mock1.Setup(i => i.TestMethod())|] - .Callback(() => { }); - - [|mock1.Setup(i => i.TestProperty)|] - .Callback(() => { }); - } - } - - [|mock2.Setup(i => i.TestMethod())|] - .Callback(() => { }); - - [|mock2.Setup(i => i.TestProperty)|] - .Callback(() => { }); - } - } - - public interface I - { - int TestMethod(); - - int TestProperty { get; set; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoReturns_StrictMode_DiagnosticReported() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(MockBehavior.Strict); - [|mock1.Setup(i => i.TestMethod())|] - .Callback(() => { }); - [|mock1.Setup(i => i.TestProperty)|] - .Callback(() => { }); - } - } - - public interface I - { - int TestMethod(); - - int TestProperty { get; set; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - [Theory] - [InlineData("MockBehavior.Loose")] - [InlineData("")] - [InlineData("1, 2")] - [InlineData("OtherEnum.A, 1, 2")] - [InlineData("MockBehavior.Loose, 1, 2")] - public async Task NoReturns_OtherMode_NoDiagnosticReported(string mockArguments) + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(" + mockArguments + @"); - mock1.Setup(i => i.TestMethod()) - .Callback(() => { }); - - var mock2 = new Mock("" + mockArguments + @""); - mock2.Setup(i => i.TestProperty) - .Callback(() => { }); - } - } - - public interface I - { - int TestMethod(); - - int TestProperty { get; set; } - } - - public enum OtherEnum { A, B } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Theory] - [InlineData("MockBehavior.Strict")] - [InlineData("MockBehavior.Strict, 1, 2")] - [InlineData("MockBehavior.Loose")] - [InlineData("MockBehavior.Loose, 1, 2")] - [InlineData("")] - public async Task NoReturns_MockSetupMethodVoid_NoDiagnosticReported(string mockArguments) - { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; + using System; + using System.Threading.Tasks; public class TestClass { public void TestMethod() { - var mock1 = new Mock(" + mockArguments + @"); - mock1.Setup(i => i.TestMethod()) - .Callback(() => { }); + {{code}} } } - public interface I - { - void TestMethod(); - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } [Theory] - [InlineData("MockBehavior.Loose")] - [InlineData("MockBehavior.Loose, 1, 2")] - [InlineData("")] - public async Task NoReturns_MockSetupProperty_NoDiagnosticReported(string mockArguments) - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(" + mockArguments + @"); - mock1.Setup(i => i.Property) - .Callback(() => { }); - } - } - - public interface I - { - int Property { get; set; } - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoSetupMethod() + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Verify(); - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMoqLibrary() - { - var source = @" - namespace ConsoleApplication1 - { - using OtherNamespace; + using FakeMoqLibrary; + using System; + using System.Threading.Tasks; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); - mock1.Setup(); + {{code}} } } - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - - public void Setup() { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 773446d..2b24a9e 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -66,8 +66,12 @@ public void Returns(Delegate valueFunction) { } public void ReturnsAsync(Delegate valueFunction) { } + public void ReturnsAsync(TResult value) { } + public void Throws(Exception exception) { } + public void ThrowsAsync(Exception exception) { } + public void Verifiable() { } public void Verifiable(string failMessage) { } From d11b258d3236ecf0093c94f6ac6efa0188f0b8fd Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 23:12:25 +0200 Subject: [PATCH 20/30] Refactoring of the VerifyAllShouldBeCalledAnalyzerTest unit tests --- .../VerifyAllShouldBeCalledAnalyzerTest.cs | 258 +++++++----------- .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 4 + 2 files changed, 101 insertions(+), 161 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/VerifyAllShouldBeCalledAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/VerifyAllShouldBeCalledAnalyzerTest.cs index c74ef20..50e52e2 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/VerifyAllShouldBeCalledAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/VerifyAllShouldBeCalledAnalyzerTest.cs @@ -10,10 +10,89 @@ namespace PosInformatique.Moq.Analyzers.Tests public class VerifyAllShouldBeCalledAnalyzerTest { - [Fact] - public async Task VerifyAll_Called() + private const string TestTypes = + """ + public interface I + { + void Method(); + } + + public class Generic { } + + public class MockHolder + { + public Mock mock = new Mock(); + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = new Mock(); + mock.VerifyAll(); + """, + + """ + var mock1 = new Mock(); + var mock2 = new Mock(); + Mock.VerifyAll(mock1, mock2); + """, + + """ + var mock1 = new Mock(); + var mock2 = new Mock(); + var mock3 = new Mock(); + mock1.VerifyAll(); + Mock.VerifyAll(mock2, mock3); + """, + + """ + var mock = new Mock(); + mock.CallBase = false; + mock.VerifyAll(); + """, + + """new Mock();""", + + """new System.Action(() => { })();""", + + """ + var o = new object(); + o.ToString(); + """, + + """ + var o = new Generic(); + o.ToString(); + """, + + """var holder = new MockHolder();""", + ]; + + public static TheoryData InvalidTestCases => + [ + """var mock = {|PosInfoMoq1000:new Mock()|};""", + + """var mock = {|PosInfoMoq1000:new Mock(MockBehavior.Strict)|};""", + + """ + var mock1 = {|PosInfoMoq1000:new Mock()|}; + var mock2 = {|PosInfoMoq1000:new Mock()|}; + new Mock(); + """, + + """var mock = {|PosInfoMoq1000:new Mock(1, 2, 3)|};""", + + """var mock = {|PosInfoMoq1000:new Mock("A", "B", "C")|};""", + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -22,184 +101,41 @@ public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - - var o = new object(); - o.ToString(); - - var mock5 = new Mock(); - var mock6 = new Mock(); - - new Mock(); // No variable (ignored) - - new System.Action(() => { })(); // Ignored - - mock1.CallBase = false; // Property access are ignored. - - mock1.VerifyAll(); - - Mock.VerifyAll(mock5, mock6); - } - } - - public interface I - { - void Method(); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task VerifyAll_Missing_Calls() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock()|]; - var mock2 = [|new Mock()|]; - - new Mock(); // No variable (ignored) - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task VerifyAll_Missing_Calls_WithArguments() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = [|new Mock(1, 2, 3)|]; - var mock2 = [|new Mock(""A"", ""B"", ""C"")|]; - } - } - - public interface I - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMock_Instance() - { - var source = @" - namespace ConsoleApplication1 - { - public class TestClass - { - public void TestMethod() - { - var o = new object(); - o.ToString(); + {{code}} } } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task NoMock_Instance_OtherGenericType() - { - var source = @" - namespace ConsoleApplication1 - { - public class TestClass - { - public void TestMethod() - { - var o = new Generic(); - o.ToString(); - } - } - - public interface I - { - } - public class Generic - { - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Mock_NotInMethod_Ignored() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public Mock mock1 = new Mock(); - } - - public interface I - { - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(MockBehavior.Strict); + {{code}} } } - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock(MockBehavior _) { } - } - - public enum MockBehavior { Strict, Loose } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 2b24a9e..95bf2e0 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -112,6 +112,8 @@ public Mock(MockBehavior behavior, params object[] args) { } public Mock(Expression> newExpression, MockBehavior behavior = default) { } + public bool CallBase { get; set; } + public void As() { } public Mock InSequence(MockSequence sequence) { return this; } @@ -138,6 +140,8 @@ public void Raise(Action eventExpression, params object[] args) { } public void Verify() { } + public void VerifyAll() { } + public void Verify(Expression> expression, string failMessage = null) { } public void Verify(Expression> expression, string failMessage = null) { } From b40fbb377b9ea599ce57fb225b1589ab4d692624 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 23:15:19 +0200 Subject: [PATCH 21/30] Refactoring of the VerifyShouldBeCalledForVerifiableSetupAnalyzerTest unit tests --- ...dBeCalledForVerifiableSetupAnalyzerTest.cs | 328 +++++++----------- 1 file changed, 120 insertions(+), 208 deletions(-) diff --git a/tests/Moq.Analyzers.Tests/Analyzers/VerifyShouldBeCalledForVerifiableSetupAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/VerifyShouldBeCalledForVerifiableSetupAnalyzerTest.cs index 2569b1b..bf9fd7f 100644 --- a/tests/Moq.Analyzers.Tests/Analyzers/VerifyShouldBeCalledForVerifiableSetupAnalyzerTest.cs +++ b/tests/Moq.Analyzers.Tests/Analyzers/VerifyShouldBeCalledForVerifiableSetupAnalyzerTest.cs @@ -10,10 +10,111 @@ namespace PosInformatique.Moq.Analyzers.Tests public class VerifyShouldBeCalledForVerifiableSetupAnalyzerTest { - [Fact] - public async Task Verifiable_NotUsed() + private const string TestTypes = + """ + public interface I + { + void Method(); + + void OtherMethod(); + + void Method(int a, int b); + + void Method(string c, int d); + } + + public class CustomMock + { + public void Setup() { } + } + """; + + public static TheoryData ValidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(m => m.Method()); + """, + + """ + var mock = new CustomMock(); + mock.Setup(); + """, + ]; + + public static TheoryData InvalidTestCases => + [ + """ + var mock = new Mock(); + mock.Setup(m => m.Method()).{|PosInfoMoq1009:Verifiable|}(); + mock.Verify(); + """, + + """ + var mock1 = new Mock(); + mock1.Setup(m => m.Method()).{|PosInfoMoq1009:Verifiable|}(); + var mock2 = new Mock(); + mock2.Setup(m => m.Method()).{|PosInfoMoq1009:Verifiable|}(); + Mock.Verify(mock1, mock2, default); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.Method()).{|PosInfoMoq1009:Verifiable|}(); + mock.Setup(m => m.OtherMethod()).{|PosInfoMoq1009:Verifiable|}(); + mock.Verify(m => m.Method()); + mock.Verify(m => m.OtherMethod()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.Method(1, 2)).{|PosInfoMoq1009:Verifiable|}(); + mock.Verify(m => m.Method(1, 2)); + mock.Verify(m => m.Method("A", 3)); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.Method()).{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); + var o = new object(); + var s = o.ToString(); + var length = s.Length; + Mock.Verify(); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.Method()).{|PosInfoMoq1009:Verifiable|}(); + mock.Setup(m => m.OtherMethod()).{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); + mock.Verify(m => m.Method()); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.Method(1, 2)).{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); + mock.Verify(m => m.Method()); + mock.Verify(m => m.Method("A", 3)); + """, + + """ + var mock = new Mock(); + mock.Setup(m => m.Method()).{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); + mock.Verify(null); + """, + + """ + var mock = new Mock(); + mock.Setup(null).{|PosInfoMoq1009:Verifiable|}(); + """, + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { using Moq; @@ -22,230 +123,41 @@ public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - mock1.Setup(m => m.Method()); - } - } - - public interface I - { - void Method(); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Verify_Called() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(m => m.Method()) - .{|PosInfoMoq1009:Verifiable|}(); - - var mock2 = new Mock(); - mock2.Setup(m => m.Method()) - .{|PosInfoMoq1009:Verifiable|}(); - - var mock3 = new Mock(); - mock3.Setup(m => m.Method()) - .{|PosInfoMoq1009:Verifiable|}(); - - var mock4 = new Mock(); - mock4.Setup(m => m.Method()) - .{|PosInfoMoq1009:Verifiable|}(); - mock4.Setup(m => m.OtherMethod()) - .{|PosInfoMoq1009:Verifiable|}(); - - var mock5 = new Mock(); - mock5.Setup(m => m.Method(1, 2)) - .{|PosInfoMoq1009:Verifiable|}(); - - var mock9 = new Mock(); - mock9.Setup(m => m.Method()); // No Verifiable() - - var o = new object(); - var s = o.ToString(); // Ignored - - var l = s.Length; // Ignored - - mock1.Verify(); - Mock.Verify(mock2, mock3, default); - - mock4.Verify(m => m.Method()); - mock4.Verify(m => m.OtherMethod()); - - mock5.Verify(m => m.Method(1, 2)); - mock5.Verify(m => m.Method(""A"", 3)); // Not used - } - } - - public interface I - { - void Method(); - - void OtherMethod(); - - void Method(int a, int b); - - void Method(string c, int d); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Verify_Missing() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(m => m.Method()) - .{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); - - var mock4 = new Mock(); - mock4.Setup(m => m.Method()) - .{|PosInfoMoq1009:Verifiable|}(); - mock4.Setup(m => m.OtherMethod()) - .{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); - - var mock5 = new Mock(); - mock5.Setup(m => m.Method(1, 2)) - .{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); - - var o = new object(); - o.ToString(); // Ignored - - mock4.Verify(m => m.Method()); - - mock5.Verify(m => m.Method()); - mock5.Verify(m => m.Method(""A"", 3)); - - Mock.Verify(); // Do nothing - } - } - - public interface I - { - void Method(); - - void OtherMethod(); - - void Method(int a, int b); - - void Method(string c, int d); - } - }"; - - await Verifier.VerifyAnalyzerAsync(source); - } - - [Fact] - public async Task Verify_MissingWithNullLambdaExpression() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(m => m.Method()) - .{|PosInfoMoq1002:{|PosInfoMoq1009:Verifiable|}|}(); - - mock1.Verify(null); - } + {{code}} + } } - public interface I - { - void Method(); - } - }"; + {{TestTypes}} + } + """; await Verifier.VerifyAnalyzerAsync(source); } - [Fact] - public async Task Verify_SetupNullArgument() - { - var source = @" - namespace ConsoleApplication1 - { - using Moq; - - public class TestClass - { - public void TestMethod() - { - var mock1 = new Mock(); - mock1.Setup(null) - .{|PosInfoMoq1009:Verifiable|}(); - } - } - - public interface I - { - void Method(); - } - }"; - - await Verifier.VerifyAnalyzerAsync( - source); - } - - [Fact] - public async Task NoMoqLibrary() + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) { - var source = @" + var source = + $$""" namespace ConsoleApplication1 { - using OtherNamespace; + using FakeMoqLibrary; public class TestClass { public void TestMethod() { - var mock1 = new Mock(); - - mock1.Setup(); + {{code}} } } - public interface I - { - } + {{TestTypes}} } - namespace OtherNamespace - { - public class Mock - { - public Mock() { } - - public void Setup() { } - } - }"; + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); } From ab2eb647db11497ae25dfc4f15b240c48d95c22f Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 23:17:28 +0200 Subject: [PATCH 22/30] Upgrades the version to v2.2.0 --- .github/workflows/github-actions-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-actions-release.yml b/.github/workflows/github-actions-release.yml index 87b9152..3ab4275 100644 --- a/.github/workflows/github-actions-release.yml +++ b/.github/workflows/github-actions-release.yml @@ -7,7 +7,7 @@ on: type: string description: The version of the library required: true - default: 2.1.0 + default: 2.2.0 VersionSuffix: type: string description: The version suffix of the library (for example rc.1) From db74119e4a69d05c213c1305d6e58998cacfcffa Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Tue, 20 Oct 2026 23:21:12 +0200 Subject: [PATCH 23/30] Upgrades the StyleCop analyzers version --- .editorconfig | 3 +++ .github/copilot-instructions.md | 5 +++++ Directory.Build.props | 6 ------ Directory.Packages.props | 2 +- PosInformatique.Moq.Analyzers.slnx | 1 - stylecop.json | 9 --------- 6 files changed, 9 insertions(+), 17 deletions(-) create mode 100644 .github/copilot-instructions.md delete mode 100644 stylecop.json diff --git a/.editorconfig b/.editorconfig index db8784f..90e10fc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,6 +2,9 @@ ## StyleCop +stylecop.documentation.companyName = P.O.S Informatique +stylecop.documentation.copyrightText = Copyright (c) {companyName}. All rights reserved. + # SA1600: Elements should be documented dotnet_diagnostic.SA1600.severity = none diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..5cca20e --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,5 @@ +# Copilot Instructions + +## Project Guidelines +- When consolidating analyzer unit tests, declare every ValidTestCases and InvalidTestCases scenario explicitly as a string in TheoryData collection expressions. Do not generate cases using loops. Use multiline raw strings for multiline snippets, following SetupMustBeUsedOnlyForOverridableMembersAnalyzerTest and SetupMethodShouldSpecifyOptionalArgumentsAnalyzerTest. +- Use AsMustBeUsedWithInterfaceAnalyzerTest and SetupSetAnalyzerTest as references. Isolate scenarios in TheoryData ValidTestCases and InvalidTestCases, use both via MemberData for Analyze and NoMoqLibrary, use raw interpolated source templates and explicit diagnostic-ID markup, reuse/extend MoqAnalyzersTests.FakeMoqLibrary, preserve coverage, and retain MarkupMode.Ignore only for no-Moq verification. \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props index fe1e5a1..e23cb67 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -25,12 +25,6 @@ PosInformatique.$(MSBuildProjectName) PosInformatique.$(MSBuildProjectName.Replace(" ", "_")) - - - - stylecop.json - - diff --git a/Directory.Packages.props b/Directory.Packages.props index 6ffbbc5..d549d03 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,7 +12,7 @@ - + \ No newline at end of file diff --git a/PosInformatique.Moq.Analyzers.slnx b/PosInformatique.Moq.Analyzers.slnx index 592cb6a..9117942 100644 --- a/PosInformatique.Moq.Analyzers.slnx +++ b/PosInformatique.Moq.Analyzers.slnx @@ -8,7 +8,6 @@ - diff --git a/stylecop.json b/stylecop.json deleted file mode 100644 index b747ad1..0000000 --- a/stylecop.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "settings": { - "documentationRules": { - "companyName": "P.O.S Informatique", - "copyrightText": "Copyright (c) {companyName}. All rights reserved.", - "documentInternalElements": false - } - } -} \ No newline at end of file From 803fd4077546c05a575aa1577d574d2b56a9f11d Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Wed, 21 Oct 2026 21:23:32 +0200 Subject: [PATCH 24/30] Adds the PosInfoMoq2020 rule (fixes #61). --- PosInformatique.Moq.Analyzers.slnx | 1 + README.md | 1 + docs/Compilation/PosInfoMoq2020.md | 39 +++++ src/Moq.Analyzers/AnalyzerReleases.Shipped.md | 9 +- ...BeUsedOnlyForOverridableMembersAnalyzer.cs | 93 ++++++++++++ src/Moq.Analyzers/Moq.Analyzers.csproj | 4 + ...edOnlyForOverridableMembersAnalyzerTest.cs | 140 ++++++++++++++++++ .../Moq.Analyzers.Tests/MoqAnalyzersTests.cs | 2 + 8 files changed, 288 insertions(+), 1 deletion(-) create mode 100644 docs/Compilation/PosInfoMoq2020.md create mode 100644 src/Moq.Analyzers/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer.cs create mode 100644 tests/Moq.Analyzers.Tests/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs diff --git a/PosInformatique.Moq.Analyzers.slnx b/PosInformatique.Moq.Analyzers.slnx index 9117942..e7bb495 100644 --- a/PosInformatique.Moq.Analyzers.slnx +++ b/PosInformatique.Moq.Analyzers.slnx @@ -36,6 +36,7 @@ + diff --git a/README.md b/README.md index 8f13623..ddfe5fc 100644 --- a/README.md +++ b/README.md @@ -76,4 +76,5 @@ All the rules of this category should not be disabled (or changed their severity | [PosInfoMoq2017: `Mock.Raise()`/`RaiseAsync()` must use parameters matching the event signature.](docs/Compilation/PosInfoMoq2017.md) | The parameters passed to `Raise()` or `RaiseAsync()` must exactly match the parameters of the corresponding event delegate. | | [PosInfoMoq2018: The first parameter of `Raise()`/`RaiseAsync()` must be an event.](docs/Compilation/PosInfoMoq2018.md) | The first parameter passed to `Raise()` or `RaiseAsync()` must reference an **event** member of the mocked type. | | [PosInfoMoq2019: `RaiseAsync()` must be used only for events with async handlers (returning `Task`).](docs/Compilation/PosInfoMoq2019.md) | `Mock.RaiseAsync()` must only be used with events whose delegate type returns `Task` (i.e., async events). | +| [PosInfoMoq2020: `CallBase()` must be used only on virtual or override members.](docs/Compilation/PosInfoMoq2020.md) | `CallBase()` can be used only on `virtual` or `override` members (not standard, `abstract` or `sealed`). | diff --git a/docs/Compilation/PosInfoMoq2020.md b/docs/Compilation/PosInfoMoq2020.md new file mode 100644 index 0000000..4440376 --- /dev/null +++ b/docs/Compilation/PosInfoMoq2020.md @@ -0,0 +1,39 @@ +# PosInfoMoq2020: `CallBase()` must be used only on virtual or override members + +| Property | Value | +|-----------------------|----------------------------------------------------------------------| +| **Rule ID** | PosInfoMoq2020 | +| **Title** | `CallBase()` must be used only on virtual or override members | +| **Category** | Compilation | +| **Default severity** | Error | + +## Cause + +The `CallBase()` method is used on a `Setup()` of a member which is not `virtual` or `override` +(standard, `abstract`, `sealed` or interface members). + +## Rule description + +`CallBase()` calls the real implementation of the mocked member. Only `virtual` or `override` members +(not `abstract`, not `sealed`) provide an implementation that Moq can call. + +## How to fix violations + +Remove the `CallBase()` call, or make the member `virtual`. + +## Example + +```csharp +public class MyClass +{ + public virtual int VirtualMethod() => 1; + + public int Method() => 1; +} + +var mock = new Mock(); + +mock.Setup(m => m.VirtualMethod()).CallBase(); // Valid + +mock.Setup(m => m.Method()).CallBase(); // PosInfoMoq2020 +``` diff --git a/src/Moq.Analyzers/AnalyzerReleases.Shipped.md b/src/Moq.Analyzers/AnalyzerReleases.Shipped.md index be241a9..f4f2759 100644 --- a/src/Moq.Analyzers/AnalyzerReleases.Shipped.md +++ b/src/Moq.Analyzers/AnalyzerReleases.Shipped.md @@ -1,4 +1,11 @@ -## Release 2.1.0 +## Release 2.2.0 + +### New Rules +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +PosInfoMoq2020 | Compilation | Error | CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer, [Documentation](https://posinformatique.github.io/PosInformatique.Moq.Analyzers/docs/Compilation/PosInfoMoq2020.html) + +## Release 2.1.0 ### New Rules Rule ID | Category | Severity | Notes diff --git a/src/Moq.Analyzers/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer.cs b/src/Moq.Analyzers/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer.cs new file mode 100644 index 0000000..870d354 --- /dev/null +++ b/src/Moq.Analyzers/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer.cs @@ -0,0 +1,93 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) P.O.S Informatique. All rights reserved. +// +//----------------------------------------------------------------------- + +namespace PosInformatique.Moq.Analyzers +{ + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.CSharp; + using Microsoft.CodeAnalysis.CSharp.Syntax; + using Microsoft.CodeAnalysis.Diagnostics; + + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public class CallBaseMustBeUsedOnlyForOverridableMembersAnalyzer : DiagnosticAnalyzer + { + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "PosInfoMoq2020", + "The CallBase() method must be used only on virtual or override members", + "The CallBase() method must be used only on virtual or override members which are not abstract or sealed", + "Compilation", + DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "The CallBase() method can be used only on virtual or override members which provide an implementation (not abstract, not sealed).", + helpLinkUri: "https://posinformatique.github.io/PosInformatique.Moq.Analyzers/docs/Compilation/PosInfoMoq2020.html"); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); + + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); + } + + private static void Analyze(SyntaxNodeAnalysisContext context) + { + var invocationExpression = (InvocationExpressionSyntax)context.Node; + + // Quick syntactic check on the CallBase() method name. + if (invocationExpression.Expression is not MemberAccessExpressionSyntax callBaseAccess || + callBaseAccess.Name.Identifier.ValueText != "CallBase") + { + return; + } + + var moqSymbols = MoqSymbols.FromCompilation(context.Compilation); + + if (moqSymbols is null) + { + return; + } + + var callBaseSymbol = context.SemanticModel.GetSymbolInfo(invocationExpression, context.CancellationToken); + + if (callBaseSymbol.Symbol is not IMethodSymbol callBaseMethod || !callBaseMethod.ContainingNamespace.ToDisplayString().StartsWith("Moq", StringComparison.Ordinal)) + { + return; + } + + var moqExpressionAnalyzer = new MoqExpressionAnalyzer(moqSymbols, context.SemanticModel); + + var setupMethod = moqExpressionAnalyzer.ExtractSetupMethod(invocationExpression, context.CancellationToken); + + if (setupMethod is null || setupMethod.Members.Count == 0) + { + return; + } + + // The first member is the mocked member (the last in the chain). + var member = setupMethod.Members[0]; + + if (IsVirtualOrOverride(member.Symbol)) + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(Rule, callBaseAccess.Name.GetLocation())); + } + + private static bool IsVirtualOrOverride(ISymbol symbol) + { + if (symbol.IsAbstract || symbol.IsSealed) + { + return false; + } + + return symbol.IsVirtual || symbol.IsOverride; + } + } +} diff --git a/src/Moq.Analyzers/Moq.Analyzers.csproj b/src/Moq.Analyzers/Moq.Analyzers.csproj index c835ace..c41505c 100644 --- a/src/Moq.Analyzers/Moq.Analyzers.csproj +++ b/src/Moq.Analyzers/Moq.Analyzers.csproj @@ -7,6 +7,10 @@ https://github.com/PosInformatique/PosInformatique.Moq.Analyzers README.md + 2.2.0 + - Add new rules: + - PosInfoMoq2020: CallBase() must be used only on virtual or override members. + 2.1.0 - Add new rules: - PosInfoMoq1011: The Setup() expression must explicitly specify optional argument values. diff --git a/tests/Moq.Analyzers.Tests/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs b/tests/Moq.Analyzers.Tests/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs new file mode 100644 index 0000000..2704bcb --- /dev/null +++ b/tests/Moq.Analyzers.Tests/Analyzers/CallBaseMustBeUsedOnlyForOverridableMembersAnalyzerTest.cs @@ -0,0 +1,140 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) P.O.S Informatique. All rights reserved. +// +//----------------------------------------------------------------------- + +namespace PosInformatique.Moq.Analyzers.Tests +{ + using Verifier = MoqCSharpAnalyzerVerifier; + + public class CallBaseMustBeUsedOnlyForOverridableMembersAnalyzerTest + { + private const string TestTypes = + """ + public interface I + { + void Method(); + + string Property { get; } + } + + public abstract class BaseClass + { + public abstract void AbstractMethod(); + + public virtual void VirtualMethod() { } + + public virtual string VirtualProperty => null; + } + + public class StandardClass : BaseClass + { + public override void AbstractMethod() { } + + public sealed override void VirtualMethod() { } + + public void Method() { } + + public string Property => null; + + public virtual int VirtualMethodWithResult() => 0; + + public virtual string VirtualSetProperty { get; set; } + + public virtual StandardClass Inner => null; + + public static void StaticMethod() { } + } + + public class Derived : BaseClass + { + public override void AbstractMethod() { } + + public override string VirtualProperty => null; + } + """; + + public static TheoryData ValidTestCases => + [ + "new Mock().Setup(c => c.VirtualMethodWithResult()).CallBase();", + "new Mock().Setup(c => c.VirtualProperty).CallBase();", + "new Mock().Setup(c => c.Inner.VirtualMethodWithResult()).CallBase();", + "new Mock().Setup(c => c.AbstractMethod()).CallBase();", + "new Mock().Setup(c => c.VirtualProperty).CallBase();", + "new Mock().Setup(c => c.VirtualMethod()).CallBase();", + + // No CallBase() call. + "new Mock().Setup(c => c.Method());", + "new Mock().Setup(i => i.Method());", + + // Mock.CallBase property (not a method). + "new Mock().CallBase = true;", + ]; + + public static TheoryData InvalidTestCases => + [ + "new Mock().Setup(c => c.Method()).{|PosInfoMoq2020:CallBase|}();", + "new Mock().Setup(c => c.Property).{|PosInfoMoq2020:CallBase|}();", + "new Mock().Setup(c => c.VirtualMethod()).{|PosInfoMoq2020:CallBase|}();", + "new Mock().Setup(c => c.Inner.Method()).{|PosInfoMoq2020:CallBase|}();", + "new Mock().Setup(c => c.AbstractMethod()).{|PosInfoMoq2020:CallBase|}();", + "new Mock().Setup(i => i.Method()).{|PosInfoMoq2020:CallBase|}();", + "new Mock().Setup(i => i.Property).{|PosInfoMoq2020:CallBase|}();", + ]; + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task Analyze(string code) + { + var source = + $$""" + namespace ConsoleApplication1 + { + using Moq; + + public class TestClass + { + public void TestMethod() + { + {{code}} + } + } + + {{TestTypes}} + } + """; + + await Verifier.VerifyAnalyzerAsync(source); + } + + [Theory] + [MemberData(nameof(ValidTestCases))] + [MemberData(nameof(InvalidTestCases))] + public async Task NoMoqLibrary(string code) + { + var source = + $$""" + namespace ConsoleApplication1 + { + using FakeMoqLibrary; + + public class TestClass + { + public void TestMethod() + { + {{code}} + } + } + + {{TestTypes}} + } + + {{MoqAnalyzersTests.FakeMoqLibrary}} + """; + + await Verifier.VerifyAnalyzerWithNoMoqLibraryAsync(source); + } + } +} diff --git a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs index 95bf2e0..fb7debe 100644 --- a/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs +++ b/tests/Moq.Analyzers.Tests/MoqAnalyzersTests.cs @@ -48,6 +48,8 @@ public struct Times public class SetupResult { + public SetupResult CallBase() { return this; } + public SetupResult Callback(Action callback) { return this; } public SetupResult Callback(Delegate callback) { return this; } From 2cb02adceb6998b4e95bdcf46c9ffc94c76486fb Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Wed, 21 Oct 2026 22:09:30 +0200 Subject: [PATCH 25/30] Fix the CI/CD workflows to use the Trusted Publishing --- .github/workflows/github-actions-ci.yaml | 4 ++-- .github/workflows/github-actions-release.yml | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/.github/workflows/github-actions-ci.yaml b/.github/workflows/github-actions-ci.yaml index 9e6b6ca..2502610 100644 --- a/.github/workflows/github-actions-ci.yaml +++ b/.github/workflows/github-actions-ci.yaml @@ -10,10 +10,10 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Setup .NET 8.x - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: '8.x' diff --git a/.github/workflows/github-actions-release.yml b/.github/workflows/github-actions-release.yml index 3ab4275..80b95c1 100644 --- a/.github/workflows/github-actions-release.yml +++ b/.github/workflows/github-actions-release.yml @@ -18,10 +18,10 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Setup .NET 8.x - uses: actions/setup-dotnet@v5 + uses: actions/setup-dotnet@v6 with: dotnet-version: '8.x' @@ -35,5 +35,14 @@ jobs: --property:VersionSuffix=${{ github.event.inputs.VersionSuffix }} "src/Moq.Analyzers/Moq.Analyzers.csproj" + - name: NuGet login + uses: NuGet/login@v1 + id: nuget_login + with: + user: ${{ secrets.NUGET_USER }} + - name: Publish the package to nuget.org - run: dotnet nuget push "src/Moq.Analyzers/bin/Release/*.nupkg" --api-key "${{ secrets.NUGET_APIKEY }}" --source https://api.nuget.org/v3/index.json + run: dotnet nuget push "src/Moq.Analyzers/bin/Release/*.nupkg" \ + --api-key "${{steps.nuget_login.outputs.NUGET_API_KEY}}" \ + --source https://api.nuget.org/v3/index.json \ + --skip-duplicate From e62373d35c19907f3d890fdb445139136d5489e9 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Wed, 21 Oct 2026 22:15:03 +0200 Subject: [PATCH 26/30] Fix release workflow --- .github/workflows/github-actions-release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/github-actions-release.yml b/.github/workflows/github-actions-release.yml index 80b95c1..f7ed5e9 100644 --- a/.github/workflows/github-actions-release.yml +++ b/.github/workflows/github-actions-release.yml @@ -17,6 +17,9 @@ run-name: ${{ inputs.VersionSuffix && format('{0}-{1}', inputs.VersionPrefix, in jobs: build: runs-on: ubuntu-latest + permissions: + id-token: write + contents: read steps: - uses: actions/checkout@v7 From 5886f15a3422a5fb860fa0e20aeca64d5b1f9d36 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Wed, 21 Oct 2026 22:25:56 +0200 Subject: [PATCH 27/30] Fix release workflow --- .github/workflows/github-actions-release.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/github-actions-release.yml b/.github/workflows/github-actions-release.yml index f7ed5e9..12e08cf 100644 --- a/.github/workflows/github-actions-release.yml +++ b/.github/workflows/github-actions-release.yml @@ -45,7 +45,8 @@ jobs: user: ${{ secrets.NUGET_USER }} - name: Publish the package to nuget.org - run: dotnet nuget push "src/Moq.Analyzers/bin/Release/*.nupkg" \ + run: | + dotnet nuget push "src/Moq.Analyzers/bin/Release/*.nupkg" \ --api-key "${{steps.nuget_login.outputs.NUGET_API_KEY}}" \ --source https://api.nuget.org/v3/index.json \ --skip-duplicate From c32a5f84a7b14daf7bd1ee4b07beb97332920790 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Sat, 7 Nov 2026 21:08:26 +0100 Subject: [PATCH 28/30] Upgrades NuGet packages --- Directory.Packages.props | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index d549d03..3006470 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,13 +5,13 @@ - - + + - - - - + + + + From bccadfeed864e780507fcdd05b3a6fda393153b0 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Sat, 7 Nov 2026 21:09:50 +0100 Subject: [PATCH 29/30] Upgrades the xUnit version to v4 --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 3006470..9759188 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -13,6 +13,6 @@ - + \ No newline at end of file From fc2f2d725283279caf8470f07836326aac752b67 Mon Sep 17 00:00:00 2001 From: Gilles TOURREAU Date: Sat, 7 Nov 2026 21:11:12 +0100 Subject: [PATCH 30/30] Upgrades the StyleCop version --- Directory.Packages.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 9759188..22c0b02 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -12,7 +12,7 @@ - + \ No newline at end of file