diff --git a/Directory.Packages.props b/Directory.Packages.props
index 369bcdd29..80334e135 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -6,10 +6,20 @@
+
+
+
+
+
-
-
\ No newline at end of file
diff --git a/README.md b/README.md
index dca6700c1..55efbe12a 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,8 @@
Install ["Moq.Analyzers" NuGet package](https://www.nuget.org/packages/Moq.Analyzers) into test projects using Moq.
+You must use an in-support version of the .NET SDK (i.e. 6+).
+
## Contributions are welcome!
Moq.Analyzers continues to evolve and add new features. Any help will be appreciated. You can report issues, develop new features, improve the documention, or do other cool stuff.
diff --git a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldFailOnGenericTypesWithMismatchArgs.verified.txt b/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldFailOnGenericTypesWithMismatchArgs.verified.txt
deleted file mode 100644
index 9e7027cee..000000000
--- a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldFailOnGenericTypesWithMismatchArgs.verified.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-Diagnostic 1
- Id: Moq1002
- Location: SourceFile(Test0.cs[608..614))
- Highlight: ("42")
- Lines: var mock = new Mock>("42");
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 2
- Id: Moq1002
- Location: SourceFile(Test0.cs[788..798))
- Highlight: ("42", 42)
- Lines: var mock1 = new Mock>("42", 42);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 3
- Id: Moq1002
- Location: SourceFile(Test0.cs[934..938))
- Highlight: (42)
- Lines: var mock2 = new Mock>(42);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
diff --git a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldFailOnMismatchArgs.verified.txt b/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldFailOnMismatchArgs.verified.txt
deleted file mode 100644
index e5cd7e3f0..000000000
--- a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldFailOnMismatchArgs.verified.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-Diagnostic 1
- Id: Moq1002
- Location: SourceFile(Test0.cs[526..532))
- Highlight: ("42")
- Lines: var mock = new Mock("42");
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 2
- Id: Moq1002
- Location: SourceFile(Test0.cs[691..701))
- Highlight: ("42", 42)
- Lines: var mock1 = new Mock("42", 42);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 3
- Id: Moq1002
- Location: SourceFile(Test0.cs[822..826))
- Highlight: (42)
- Lines: var mock2 = new Mock(42);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
diff --git a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassOnGenericTypesWithNoArgs.verified.txt b/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassOnGenericTypesWithNoArgs.verified.txt
deleted file mode 100644
index c1b8d743e..000000000
--- a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassOnGenericTypesWithNoArgs.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
\ No newline at end of file
diff --git a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassWithArgsPassed.verified.txt b/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassWithArgsPassed.verified.txt
deleted file mode 100644
index c1b8d743e..000000000
--- a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassWithArgsPassed.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
\ No newline at end of file
diff --git a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassWithNoArgs.verified.txt b/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassWithNoArgs.verified.txt
deleted file mode 100644
index c1b8d743e..000000000
--- a/Source/Moq.Analyzers.Test/AbstractClassTests.ShouldPassWithNoArgs.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
\ No newline at end of file
diff --git a/Source/Moq.Analyzers.Test/AbstractClassTests.cs b/Source/Moq.Analyzers.Test/AbstractClassTests.cs
index 0c60b2430..226f11cc5 100644
--- a/Source/Moq.Analyzers.Test/AbstractClassTests.cs
+++ b/Source/Moq.Analyzers.Test/AbstractClassTests.cs
@@ -1,18 +1,17 @@
using System.IO;
using Microsoft.CodeAnalysis.Diagnostics;
-using TestHelper;
+using Moq.Analyzers.Test.Helpers;
using Xunit;
namespace Moq.Analyzers.Test;
-public class AbstractClassTests : DiagnosticVerifier
+public class AbstractClassTests : DiagnosticVerifier
{
// TODO: Review use of `.As<>()` in the test cases. It is not clear what purpose it serves.
[Fact]
- public Task ShouldFailOnGenericTypesWithMismatchArgs()
+ public async Task ShouldFailOnGenericTypesWithMismatchArgs()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
namespace Moq.Analyzers.Test.Data.AbstractClass.GenericMistmatchArgs;
@@ -39,24 +38,22 @@ internal class MyUnitTests
private void TestBadWithGeneric()
{
// The class has a constructor that takes an Int32 but passes a String
- var mock = new Mock>("42");
+ var mock = new Mock>{|Moq1002:("42")|};
// The class has a ctor with two arguments [Int32, String], but they are passed in reverse order
- var mock1 = new Mock>("42", 42);
+ var mock1 = new Mock>{|Moq1002:("42", 42)|};
// The class has a ctor but does not take any arguments
- var mock2 = new Mock>(42);
+ var mock2 = new Mock>{|Moq1002:(42)|};
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldPassOnGenericTypesWithNoArgs()
+ public async Task ShouldPassOnGenericTypesWithNoArgs()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
namespace Moq.Analyzers.Test.Data.AbstractClass.GenericNoArgs;
@@ -79,15 +76,13 @@ private void TestForBaseGenericNoArgs()
var mock2 = new Mock>(MockBehavior.Default);
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldFailOnMismatchArgs()
+ public async Task ShouldFailOnMismatchArgs()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
namespace Moq.Analyzers.Test.Data.AbstractClass.MismatchArgs;
@@ -114,24 +109,22 @@ internal class MyUnitTests
private void TestBad()
{
// The class has a ctor that takes an Int32 but passes a String
- var mock = new Mock("42");
+ var mock = new Mock{|Moq1002:("42")|};
// The class has a ctor with two arguments [Int32, String], but they are passed in reverse order
- var mock1 = new Mock("42", 42);
+ var mock1 = new Mock{|Moq1002:("42", 42)|};
// The class has a ctor but does not take any arguments
- var mock2 = new Mock(42);
+ var mock2 = new Mock{|Moq1002:(42)|};
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldPassWithNoArgs()
+ public async Task ShouldPassWithNoArgs()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
namespace Moq.Analyzers.Test.Data.AbstractClass.NoArgs;
@@ -151,15 +144,13 @@ private void TestForBaseNoArgs()
mock.As();
}
}
- """
- ]));
+ """);
}
[Fact(Skip = "I think this _should_ fail, but currently passes. Tracked by #55.")]
- public Task ShouldFailWithArgsNonePassed()
+ public async Task ShouldFailWithArgsNonePassed()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
namespace Moq.Analyzers.Test.Data.AbstractClass.WithArgsNonePassed;
@@ -181,19 +172,15 @@ private void TestForBaseWithArgsNonePassed()
{
var mock = new Mock();
mock.As();
-
- var mock2 = new Mock(MockBehavior.Default);
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldPassWithArgsPassed()
+ public async Task ShouldPassWithArgsPassed()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
namespace Moq.Analyzers.Test.DataAbstractClass.WithArgsPassed;
@@ -233,12 +220,6 @@ private void TestForBaseWithArgsPassed()
var mock6 = new Mock>(MockBehavior.Default, 42);
}
}
- """
- ]));
- }
-
- protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
- {
- return new ConstructorArgumentsShouldMatchAnalyzer();
+ """);
}
}
diff --git a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldFailWhenUsingAsWithAbstractClass.verified.txt b/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldFailWhenUsingAsWithAbstractClass.verified.txt
deleted file mode 100644
index 3207abdda..000000000
--- a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldFailWhenUsingAsWithAbstractClass.verified.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Diagnostic 1
- Id: Moq1300
- Location: SourceFile(Test0.cs[292..307))
- Highlight: BaseSampleClass
- Lines: mock.As();
- Severity: Error
- Message: Mock.As() should take interfaces only
-
diff --git a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldFailWhenUsingAsWithConcreteClass.verified.txt b/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldFailWhenUsingAsWithConcreteClass.verified.txt
deleted file mode 100644
index e54f2188e..000000000
--- a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldFailWhenUsingAsWithConcreteClass.verified.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Diagnostic 1
- Id: Moq1300
- Location: SourceFile(Test0.cs[433..443))
- Highlight: OtherClass
- Lines: mock.As();
- Severity: Error
- Message: Mock.As() should take interfaces only
-
diff --git a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldPassWhenUsingAsWithInterface.verified.txt b/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldPassWhenUsingAsWithInterface.verified.txt
deleted file mode 100644
index c1b8d743e..000000000
--- a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldPassWhenUsingAsWithInterface.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
\ No newline at end of file
diff --git a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldPassWhenUsingAsWithInterfaceWithSetup.verified.txt b/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldPassWhenUsingAsWithInterfaceWithSetup.verified.txt
deleted file mode 100644
index c1b8d743e..000000000
--- a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.ShouldPassWhenUsingAsWithInterfaceWithSetup.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
\ No newline at end of file
diff --git a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.cs b/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.cs
index b1295ffc7..069c125d4 100644
--- a/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.cs
+++ b/Source/Moq.Analyzers.Test/AsAcceptOnlyInterfaceAnalyzerTests.cs
@@ -1,18 +1,17 @@
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
-using TestHelper;
+using Moq.Analyzers.Test.Helpers;
using Xunit;
namespace Moq.Analyzers.Test;
-public class AsAcceptOnlyInterfaceAnalyzerTests : DiagnosticVerifier
+public class AsAcceptOnlyInterfaceAnalyzerTests : DiagnosticVerifier
{
[Fact]
- public Task ShouldFailWhenUsingAsWithAbstractClass()
+ public async Task ShouldFailWhenUsingAsWithAbstractClass()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using Moq;
@@ -28,18 +27,16 @@ internal class MyUnitTests
private void TestBadAsForAbstractClass()
{
var mock = new Mock();
- mock.As();
+ mock.As<{|Moq1300:BaseSampleClass|}>();
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldFailWhenUsingAsWithConcreteClass()
+ public async Task ShouldFailWhenUsingAsWithConcreteClass()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using Moq;
@@ -66,18 +63,16 @@ internal class MyUnitTests
private void TestBadAsForNonAbstractClass()
{
var mock = new Mock();
- mock.As();
+ mock.As<{|Moq1300:OtherClass|}>();
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldPassWhenUsingAsWithInterface()
+ public async Task ShouldPassWhenUsingAsWithInterface()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using Moq;
@@ -101,15 +96,13 @@ private void TestOkAsForInterface()
mock.As();
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldPassWhenUsingAsWithInterfaceWithSetup()
+ public async Task ShouldPassWhenUsingAsWithInterfaceWithSetup()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using Moq;
@@ -135,12 +128,6 @@ private void TestOkAsForInterfaceWithConfiguration()
.Returns(10);
}
}
- """
- ]));
- }
-
- protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
- {
- return new AsShouldBeUsedOnlyForInterfaceAnalyzer();
+ """);
}
}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldFailWhenIncorrectCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldFailWhenIncorrectCallbacks.verified.txt
deleted file mode 100644
index bfaeee0cc..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldFailWhenIncorrectCallbacks.verified.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-Diagnostic 1
- Id: Moq1100
- Location: SourceFile(Test0.cs[420..427))
- Highlight: (int i)
- Lines: mock.Setup(x => x.Do(It.IsAny())).Callback((int i) => { });
- Severity: Warning
- Message: Callback signature must match the signature of the mocked method.
-
-Diagnostic 2
- Id: Moq1100
- Location: SourceFile(Test0.cs[496..518))
- Highlight: (string s1, string s2)
- Lines: mock.Setup(x => x.Do(It.IsAny())).Callback((string s1, string s2) => { });
- Severity: Warning
- Message: Callback signature must match the signature of the mocked method.
-
-Diagnostic 3
- Id: Moq1100
- Location: SourceFile(Test0.cs[626..645))
- Highlight: (string s1, int i1)
- Lines: mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((string s1, int i1) => { });
- Severity: Warning
- Message: Callback signature must match the signature of the mocked method.
-
-Diagnostic 4
- Id: Moq1100
- Location: SourceFile(Test0.cs[720..727))
- Highlight: (int i)
- Lines: mock.Setup(x => x.Do(It.IsAny>())).Callback((int i) => { });
- Severity: Warning
- Message: Callback signature must match the signature of the mocked method.
-
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndCallbacks.verified.txt
deleted file mode 100644
index d39fa8d42..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndCallbacks.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndParameterlessCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndParameterlessCallbacks.verified.txt
deleted file mode 100644
index d39fa8d42..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndParameterlessCallbacks.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndReturns.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndReturns.verified.txt
deleted file mode 100644
index d39fa8d42..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndReturns.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndReturnsAndCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndReturnsAndCallbacks.verified.txt
deleted file mode 100644
index d39fa8d42..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.ShouldPassWhenCorrectSetupAndReturnsAndCallbacks.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.cs b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.cs
deleted file mode 100644
index cfe825e8b..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodAnalyzerTests.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-using System.IO;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace Moq.Analyzers.Test;
-
-public class CallbackSignatureShouldMatchMockedMethodAnalyzerTests : CallbackSignatureShouldMatchMockedMethodBase
-{
- [Fact]
- public Task ShouldPassWhenCorrectSetupAndReturns()
- {
- return Verify(VerifyCSharpDiagnostic(GoodSetupAndCallback));
- }
-
- [Fact]
- public Task ShouldFailWhenIncorrectCallbacks()
- {
- return Verify(VerifyCSharpDiagnostic(BadCallbacks));
- }
-
- [Fact]
- public Task ShouldPassWhenCorrectSetupAndCallbacks()
- {
- return Verify(VerifyCSharpDiagnostic(GoodSetupAndCallback));
- }
-
- [Fact]
- public Task ShouldPassWhenCorrectSetupAndParameterlessCallbacks()
- {
- return Verify(VerifyCSharpDiagnostic(GoodSetupAndParameterlessCallback));
- }
-
- [Fact]
- public Task ShouldPassWhenCorrectSetupAndReturnsAndCallbacks()
- {
- return Verify(VerifyCSharpDiagnostic(GoodSetupAndReturnsAndCallback));
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodBase.cs b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodBase.cs
deleted file mode 100644
index 87a09ebe3..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodBase.cs
+++ /dev/null
@@ -1,166 +0,0 @@
-using Microsoft.CodeAnalysis.CodeFixes;
-using Microsoft.CodeAnalysis.Diagnostics;
-using TestHelper;
-
-namespace Moq.Analyzers.Test;
-
-// TODO: These tests should be broken down further
-// TODO: Merge the diagnostic and codefix tests into a single harness
-public abstract class CallbackSignatureShouldMatchMockedMethodBase : CodeFixVerifier
-{
- protected string GoodSetupAndReturns { get; } =
- """
- using System;
- using System.Collections.Generic;
- using Moq;
-
- namespace CallbackSignatureShouldMatchMockedMethod.MyGoodSetupAndReturns;
-
- internal interface IFoo
- {
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
- }
-
- internal class MyUnitTests
- {
- private void MyGoodSetupAndReturns()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Returns((string s) => { return 0; });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns((int i, string s, DateTime dt) => { return 0; });
- mock.Setup(x => x.Do(It.IsAny>())).Returns((List l) => { return 0; });
- }
- }
- """;
-
- protected string BadCallbacks { get; } =
- """
- using System;
- using System.Collections.Generic;
- using Moq;
-
- namespace CallbackSignatureShouldMatchMockedMethod.TestBadCallbacks;
-
- internal interface IFoo
- {
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
- }
-
- internal class MyUnitTests
- {
- private void TestBadCallbacks()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Callback((int i) => { });
- mock.Setup(x => x.Do(It.IsAny())).Callback((string s1, string s2) => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((string s1, int i1) => { });
- mock.Setup(x => x.Do(It.IsAny>())).Callback((int i) => { });
- }
- }
- """;
-
- protected string GoodSetupAndCallback { get; } =
- """
- using System;
- using System.Collections.Generic;
- using Moq;
-
- namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndCallback;
-
- internal interface IFoo
- {
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
- }
-
- internal class MyUnitTests
- {
- private void TestGoodSetupAndCallback()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((int i, string s, DateTime dt) => { });
- mock.Setup(x => x.Do(It.IsAny>())).Callback((List l) => { });
- }
- }
- """;
-
- protected string GoodSetupAndParameterlessCallback { get; } =
- """
- using System;
- using System.Collections.Generic;
- using Moq;
-
- namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndParameterlessCallback;
-
- internal interface IFoo
- {
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
- }
-
- internal class MyUnitTests
- {
- private void TestGoodSetupAndParameterlessCallback()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Callback(() => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback(() => { });
- mock.Setup(x => x.Do(It.IsAny>())).Callback(() => { });
- }
- }
- """;
-
- protected string GoodSetupAndReturnsAndCallback { get; } =
- """
- using System;
- using System.Collections.Generic;
- using Moq;
-
- namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndReturnsAndCallback;
-
- internal interface IFoo
- {
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
- }
-
- internal class MyUnitTests
- {
- private void TestGoodSetupAndReturnsAndCallback()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Returns(0).Callback((string s) => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0).Callback((int i, string s, DateTime dt) => { });
- mock.Setup(x => x.Do(It.IsAny>())).Returns(0).Callback((List l) => { });
- }
- }
- """;
-
- protected override CodeFixProvider GetCSharpCodeFixProvider()
- {
- return new CallbackSignatureShouldMatchMockedMethodCodeFix();
- }
-
- protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
- {
- return new CallbackSignatureShouldMatchMockedMethodAnalyzer();
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndCallbacks.verified.txt
deleted file mode 100644
index 80913877d..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndCallbacks.verified.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Moq;
-
-namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndCallback;
-
-internal interface IFoo
-{
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
-}
-
-internal class MyUnitTests
-{
- private void TestGoodSetupAndCallback()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((int i, string s, DateTime dt) => { });
- mock.Setup(x => x.Do(It.IsAny>())).Callback((List l) => { });
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndParameterlessCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndParameterlessCallbacks.verified.txt
deleted file mode 100644
index ccd5ce3ed..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndParameterlessCallbacks.verified.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Moq;
-
-namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndParameterlessCallback;
-
-internal interface IFoo
-{
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
-}
-
-internal class MyUnitTests
-{
- private void TestGoodSetupAndParameterlessCallback()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Callback(() => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback(() => { });
- mock.Setup(x => x.Do(It.IsAny>())).Callback(() => { });
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndReturns.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndReturns.verified.txt
deleted file mode 100644
index 756d8892c..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndReturns.verified.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Moq;
-
-namespace CallbackSignatureShouldMatchMockedMethod.MyGoodSetupAndReturns;
-
-internal interface IFoo
-{
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
-}
-
-internal class MyUnitTests
-{
- private void MyGoodSetupAndReturns()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Returns((string s) => { return 0; });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns((int i, string s, DateTime dt) => { return 0; });
- mock.Setup(x => x.Do(It.IsAny>())).Returns((List l) => { return 0; });
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndReturnsAndCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndReturnsAndCallbacks.verified.txt
deleted file mode 100644
index 17f6b9040..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldPassWhenCorrectSetupAndReturnsAndCallbacks.verified.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Moq;
-
-namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndReturnsAndCallback;
-
-internal interface IFoo
-{
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
-}
-
-internal class MyUnitTests
-{
- private void TestGoodSetupAndReturnsAndCallback()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Returns(0).Callback((string s) => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0).Callback((int i, string s, DateTime dt) => { });
- mock.Setup(x => x.Do(It.IsAny>())).Returns(0).Callback((List l) => { });
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldSuggestQuickFixWhenIncorrectCallbacks.verified.txt b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldSuggestQuickFixWhenIncorrectCallbacks.verified.txt
deleted file mode 100644
index 2ae7ce25b..000000000
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.ShouldSuggestQuickFixWhenIncorrectCallbacks.verified.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Moq;
-
-namespace CallbackSignatureShouldMatchMockedMethod.TestBadCallbacks;
-
-internal interface IFoo
-{
- int Do(string s);
-
- int Do(int i, string s, DateTime dt);
-
- int Do(List l);
-}
-
-internal class MyUnitTests
-{
- private void TestBadCallbacks()
- {
- var mock = new Mock();
- mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
- mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
- mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((int i, string s, DateTime dt) => { });
- mock.Setup(x => x.Do(It.IsAny>())).Callback((List l) => { });
- }
-}
diff --git a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.cs b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.cs
index 49221e4df..e923af8c2 100644
--- a/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.cs
+++ b/Source/Moq.Analyzers.Test/CallbackSignatureShouldMatchMockedMethodCodeFixTests.cs
@@ -1,41 +1,314 @@
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
-using TestHelper;
+using Moq.Analyzers.Test.Helpers;
using Xunit;
namespace Moq.Analyzers.Test;
-public class CallbackSignatureShouldMatchMockedMethodCodeFixTests : CallbackSignatureShouldMatchMockedMethodBase
+public class CallbackSignatureShouldMatchMockedMethodCodeFixTests : CodeFixVerifier
{
[Fact]
- public Task ShouldPassWhenCorrectSetupAndReturns()
+ public async Task ShouldPassWhenCorrectSetupAndReturns()
{
- return Verify(VerifyCSharpFix(GoodSetupAndReturns));
+ await VerifyCSharpFix(
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.MyGoodSetupAndReturns;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void MyGoodSetupAndReturns()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Returns((string s) => { return 0; });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns((int i, string s, DateTime dt) => { return 0; });
+ mock.Setup(x => x.Do(It.IsAny>())).Returns((List l) => { return 0; });
+ }
+ }
+ """,
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.MyGoodSetupAndReturns;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void MyGoodSetupAndReturns()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Returns((string s) => { return 0; });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns((int i, string s, DateTime dt) => { return 0; });
+ mock.Setup(x => x.Do(It.IsAny>())).Returns((List l) => { return 0; });
+ }
+ }
+ """);
}
[Fact]
- public Task ShouldSuggestQuickFixWhenIncorrectCallbacks()
+ public async Task ShouldSuggestQuickFixWhenIncorrectCallbacks()
{
- return Verify(VerifyCSharpFix(BadCallbacks));
+ await VerifyCSharpFix(
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestBadCallbacks;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestBadCallbacks()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Callback({|Moq1100:(int i)|} => { });
+ mock.Setup(x => x.Do(It.IsAny())).Callback({|Moq1100:(string s1, string s2)|} => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback({|Moq1100:(string s1, int i1)|} => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Callback({|Moq1100:(int i)|} => { });
+ }
+ }
+ """,
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestBadCallbacks;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestBadCallbacks()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
+ mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((int i, string s, DateTime dt) => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Callback((List l) => { });
+ }
+ }
+ """);
}
[Fact]
- public Task ShouldPassWhenCorrectSetupAndCallbacks()
+ public async Task ShouldPassWhenCorrectSetupAndCallbacks()
{
- return Verify(VerifyCSharpFix(GoodSetupAndCallback));
+ await VerifyCSharpFix(
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndCallback;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestGoodSetupAndCallback()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((int i, string s, DateTime dt) => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Callback((List l) => { });
+ }
+ }
+ """,
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndCallback;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestGoodSetupAndCallback()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Callback((string s) => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback((int i, string s, DateTime dt) => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Callback((List l) => { });
+ }
+ }
+ """);
}
[Fact]
- public Task ShouldPassWhenCorrectSetupAndParameterlessCallbacks()
+ public async Task ShouldPassWhenCorrectSetupAndParameterlessCallbacks()
{
- return Verify(VerifyCSharpFix(GoodSetupAndParameterlessCallback));
+ await VerifyCSharpFix(
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndParameterlessCallback;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestGoodSetupAndParameterlessCallback()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Callback(() => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback(() => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Callback(() => { });
+ }
+ }
+ """,
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndParameterlessCallback;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestGoodSetupAndParameterlessCallback()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Callback(() => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Callback(() => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Callback(() => { });
+ }
+ }
+ """);
}
[Fact]
- public Task ShouldPassWhenCorrectSetupAndReturnsAndCallbacks()
+ public async Task ShouldPassWhenCorrectSetupAndReturnsAndCallbacks()
{
- return Verify(VerifyCSharpFix(GoodSetupAndReturnsAndCallback));
+ await VerifyCSharpFix(
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndReturnsAndCallback;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestGoodSetupAndReturnsAndCallback()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Returns(0).Callback((string s) => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0).Callback((int i, string s, DateTime dt) => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Returns(0).Callback((List l) => { });
+ }
+ }
+ """,
+ """
+ using System;
+ using System.Collections.Generic;
+ using Moq;
+
+ namespace CallbackSignatureShouldMatchMockedMethod.TestGoodSetupAndReturnsAndCallback;
+
+ internal interface IFoo
+ {
+ int Do(string s);
+
+ int Do(int i, string s, DateTime dt);
+
+ int Do(List l);
+ }
+
+ internal class MyUnitTests
+ {
+ private void TestGoodSetupAndReturnsAndCallback()
+ {
+ var mock = new Mock();
+ mock.Setup(x => x.Do(It.IsAny())).Returns(0).Callback((string s) => { });
+ mock.Setup(x => x.Do(It.IsAny(), It.IsAny(), It.IsAny())).Returns(0).Callback((int i, string s, DateTime dt) => { });
+ mock.Setup(x => x.Do(It.IsAny>())).Returns(0).Callback((List l) => { });
+ }
+ }
+ """);
}
}
diff --git a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldFailWhenConstructorArumentsDoNotMatch.verified.txt b/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldFailWhenConstructorArumentsDoNotMatch.verified.txt
deleted file mode 100644
index 17eea554b..000000000
--- a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldFailWhenConstructorArumentsDoNotMatch.verified.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-Diagnostic 1
- Id: Moq1002
- Location: SourceFile(Test0.cs[392..401))
- Highlight: (1, true)
- Lines: var mock1 = new Mock(1, true);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 2
- Id: Moq1002
- Location: SourceFile(Test0.cs[436..445))
- Highlight: (2, true)
- Lines: var mock2 = new Mock(2, true);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 3
- Id: Moq1002
- Location: SourceFile(Test0.cs[480..488))
- Highlight: ("1", 3)
- Lines: var mock3 = new Mock("1", 3);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 4
- Id: Moq1002
- Location: SourceFile(Test0.cs[523..546))
- Highlight: (new int[] { 1, 2, 3 })
- Lines: var mock4 = new Mock(new int[] { 1, 2, 3 });
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
diff --git a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldFailWhenConstructorArumentsWithExplicitMockBehaviorDoNotMatch.verified.txt b/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldFailWhenConstructorArumentsWithExplicitMockBehaviorDoNotMatch.verified.txt
deleted file mode 100644
index 1976d03e7..000000000
--- a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldFailWhenConstructorArumentsWithExplicitMockBehaviorDoNotMatch.verified.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-Diagnostic 1
- Id: Moq1002
- Location: SourceFile(Test0.cs[423..453))
- Highlight: (MockBehavior.Strict, 4, true)
- Lines: var mock1 = new Mock(MockBehavior.Strict, 4, true);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 2
- Id: Moq1002
- Location: SourceFile(Test0.cs[488..517))
- Highlight: (MockBehavior.Loose, 5, true)
- Lines: var mock2 = new Mock(MockBehavior.Loose, 5, true);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
-Diagnostic 3
- Id: Moq1002
- Location: SourceFile(Test0.cs[552..580))
- Highlight: (MockBehavior.Loose, "2", 6)
- Lines: var mock3 = new Mock(MockBehavior.Loose, "2", 6);
- Severity: Warning
- Message: Parameters provided into mock do not match any existing constructors.
-
diff --git a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldPassWhenConstructorArgumentsMatch.verified.txt b/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldPassWhenConstructorArgumentsMatch.verified.txt
deleted file mode 100644
index d39fa8d42..000000000
--- a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.ShouldPassWhenConstructorArgumentsMatch.verified.txt
+++ /dev/null
@@ -1 +0,0 @@
-emptyString
diff --git a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.cs b/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.cs
index d825fbb3f..63bf31717 100644
--- a/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.cs
+++ b/Source/Moq.Analyzers.Test/ConstructorArgumentsShouldMatchAnalyzerTests.cs
@@ -1,18 +1,17 @@
using System.IO;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
-using TestHelper;
+using Moq.Analyzers.Test.Helpers;
using Xunit;
namespace Moq.Analyzers.Test;
-public class ConstructorArgumentsShouldMatchAnalyzerTests : DiagnosticVerifier
+public class ConstructorArgumentsShouldMatchAnalyzerTests : DiagnosticVerifier
{
[Fact]
- public Task ShouldPassWhenConstructorArgumentsMatch()
+ public async Task ShouldPassWhenConstructorArgumentsMatch()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using System;
using System.Collections.Generic;
@@ -57,15 +56,13 @@ private void TestGood()
var mock16 = new Mock(MockBehavior.Default, new List());
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldFailWhenConstructorArumentsDoNotMatch()
+ public async Task ShouldFailWhenConstructorArumentsDoNotMatch()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using System;
using System.Collections.Generic;
@@ -88,21 +85,19 @@ internal class MyUnitTests
{
private void TestBad()
{
- var mock1 = new Mock(1, true);
- var mock2 = new Mock(2, true);
- var mock3 = new Mock("1", 3);
- var mock4 = new Mock(new int[] { 1, 2, 3 });
+ var mock1 = new Mock{|Moq1002:(1, true)|};
+ var mock2 = new Mock{|Moq1002:(2, true)|};
+ var mock3 = new Mock{|Moq1002:("1", 3)|};
+ var mock4 = new Mock{|Moq1002:(new int[] { 1, 2, 3 })|};
}
}
- """
- ]));
+ """);
}
[Fact]
- public Task ShouldFailWhenConstructorArumentsWithExplicitMockBehaviorDoNotMatch()
+ public async Task ShouldFailWhenConstructorArumentsWithExplicitMockBehaviorDoNotMatch()
{
- return Verify(VerifyCSharpDiagnostic(
- [
+ await VerifyCSharpDiagnostic(
"""
using System;
using System.Collections.Generic;
@@ -125,17 +120,11 @@ internal class MyUnitTests
{
private void TestBadWithMockBehavior()
{
- var mock1 = new Mock(MockBehavior.Strict, 4, true);
- var mock2 = new Mock(MockBehavior.Loose, 5, true);
- var mock3 = new Mock(MockBehavior.Loose, "2", 6);
+ var mock1 = new Mock{|Moq1002:(MockBehavior.Strict, 4, true)|};
+ var mock2 = new Mock{|Moq1002:(MockBehavior.Loose, 5, true)|};
+ var mock3 = new Mock{|Moq1002:(MockBehavior.Loose, "2", 6)|};
}
}
- """
- ]));
- }
-
- protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
- {
- return new ConstructorArgumentsShouldMatchAnalyzer();
+ """);
}
}
diff --git a/Source/Moq.Analyzers.Test/Helpers/AnalyzerTestExtensions.cs b/Source/Moq.Analyzers.Test/Helpers/AnalyzerTestExtensions.cs
new file mode 100644
index 000000000..14a77a2bd
--- /dev/null
+++ b/Source/Moq.Analyzers.Test/Helpers/AnalyzerTestExtensions.cs
@@ -0,0 +1,16 @@
+using Microsoft.CodeAnalysis.Testing;
+
+namespace Moq.Analyzers.Test.Helpers;
+
+internal static class AnalyzerTestExtensions
+{
+ public static TAnalyzerTest SetDefaults(this TAnalyzerTest test)
+ where TAnalyzerTest : AnalyzerTest
+ where TVerifier : IVerifier, new()
+ {
+ test.ReferenceAssemblies = ReferenceAssemblies.Net.Net80.AddPackages([new PackageIdentity("Moq", "4.8.2")]); // TODO: See https://github.com/Litee/moq.analyzers/issues/58
+ test.TestBehaviors = TestBehaviors.SkipGeneratedCodeCheck; // TODO: We should enable the generated code check
+
+ return test;
+ }
+}
diff --git a/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.Helper.cs b/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.Helper.cs
deleted file mode 100644
index a6b06168d..000000000
--- a/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.Helper.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.Formatting;
-using Microsoft.CodeAnalysis.Simplification;
-
-namespace TestHelper;
-
-///
-/// Diagnostic Producer class with extra methods dealing with applying codefixes
-/// All methods are static
-///
-public abstract partial class CodeFixVerifier : DiagnosticVerifier
-{
- ///
- /// Apply the inputted CodeAction to the inputted document.
- /// Meant to be used to apply codefixes.
- ///
- /// The Document to apply the fix on
- /// A CodeAction that will be applied to the Document.
- /// A Document with the changes from the CodeAction
- private static Document ApplyFix(Document document, CodeAction codeAction)
- {
- var operations = codeAction.GetOperationsAsync(CancellationToken.None).Result;
- var solution = operations.OfType().Single().ChangedSolution;
- return solution.GetDocument(document.Id);
- }
-
- ///
- /// Compare two collections of Diagnostics,and return a list of any new diagnostics that appear only in the second collection.
- /// Note: Considers Diagnostics to be the same if they have the same Ids. In the case of multiple diagnostics with the same Id in a row,
- /// this method may not necessarily return the new one.
- ///
- /// The Diagnostics that existed in the code before the CodeFix was applied
- /// The Diagnostics that exist in the code after the CodeFix was applied
- /// A list of Diagnostics that only surfaced in the code after the CodeFix was applied
- private static IEnumerable GetNewDiagnostics(IEnumerable diagnostics, IEnumerable newDiagnostics)
- {
- var oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
- var newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
-
- int oldIndex = 0;
- int newIndex = 0;
-
- while (newIndex < newArray.Length)
- {
- if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id)
- {
- ++oldIndex;
- ++newIndex;
- }
- else
- {
- yield return newArray[newIndex++];
- }
- }
- }
-
- ///
- /// Get the existing compiler diagnostics on the inputted document.
- ///
- /// The Document to run the compiler diagnostic analyzers on
- /// The compiler diagnostics that were found in the code
- private static IEnumerable GetCompilerDiagnostics(Document document)
- {
- return document.GetSemanticModelAsync().Result.GetDiagnostics();
- }
-
- ///
- /// Given a document, turn it into a string based on the syntax root
- ///
- /// The Document to be converted to a string
- /// A string containing the syntax of the Document after formatting
- private static string GetStringFromDocument(Document document)
- {
- var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result;
- var root = simplifiedDoc.GetSyntaxRootAsync().Result;
- root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace);
- return root.GetText().ToString();
- }
-}
diff --git a/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.cs b/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.cs
index 8f87121fe..a2b39f4b6 100644
--- a/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.cs
+++ b/Source/Moq.Analyzers.Test/Helpers/CodeFixVerifier.cs
@@ -1,112 +1,24 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CodeActions;
-using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CodeFixes;
+using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
-using Microsoft.CodeAnalysis.Formatting;
-using Xunit;
+using Microsoft.CodeAnalysis.Testing;
-namespace TestHelper;
+namespace Moq.Analyzers.Test.Helpers;
-///
-/// Superclass of all Unit tests made for diagnostics with codefixes.
-/// Contains methods used to verify correctness of codefixes
-///
-public abstract partial class CodeFixVerifier : DiagnosticVerifier
+public abstract class CodeFixVerifier
+ where TAnalyzer : DiagnosticAnalyzer, new()
+ where TCodeFixProvider : CodeFixProvider, new()
{
- ///
- /// Returns the codefix being tested (C#) - to be implemented in non-abstract class
- ///
- /// The CodeFixProvider to be used for CSharp code
- protected virtual CodeFixProvider GetCSharpCodeFixProvider()
+ protected async Task VerifyCSharpFix(string originalSource, string fixedSource)
{
- return null;
- }
-
- ///
- /// Called to test a C# codefix when applied on the inputted string as a source
- ///
- /// A class in the form of a string before the CodeFix was applied to it
- /// Index determining which codefix to apply if there are multiple
- /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied
- /// Code with quick fix applied
- protected string VerifyCSharpFix(string oldSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false)
- {
- return VerifyFix(LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), GetCSharpCodeFixProvider(), oldSource, codeFixIndex, allowNewCompilerDiagnostics);
- }
-
- ///
- /// General verifier for codefixes.
- /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes.
- /// Then gets the string after the codefix is applied and compares it with the expected result.
- /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true.
- ///
- /// The language the source code is in
- /// The analyzer to be applied to the source code
- /// The codefix to be applied to the code wherever the relevant Diagnostic is found
- /// A class in the form of a string before the CodeFix was applied to it
- /// Index determining which codefix to apply if there are multiple
- /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied
- /// Code with quick fix applied
- private string VerifyFix(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, int? codeFixIndex, bool allowNewCompilerDiagnostics)
- {
- var document = CreateDocument(oldSource, language);
- var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });
- var compilerDiagnostics = GetCompilerDiagnostics(document);
- var attempts = analyzerDiagnostics.Length;
-
- for (int i = 0; i < attempts; ++i)
+ CSharpCodeFixTest context = new()
{
- var actions = new List();
- var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
- codeFixProvider.RegisterCodeFixesAsync(context).Wait(context.CancellationToken);
-
- if (!actions.Any())
- {
- break;
- }
-
- if (codeFixIndex != null)
- {
- document = ApplyFix(document, actions.ElementAt((int)codeFixIndex));
- break;
- }
-
- document = ApplyFix(document, actions.ElementAt(0));
- analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });
-
- var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document));
-
- // check if applying the code fix introduced any new compiler diagnostics
- if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
- {
- // Format and get the compiler diagnostics again so that the locations make sense in the output
- SyntaxNode root = Formatter.Format(
- document.GetSyntaxRootAsync(context.CancellationToken).Result,
- Formatter.Annotation,
- document.Project.Solution.Workspace,
- cancellationToken: context.CancellationToken);
- document = document.WithSyntaxRoot(root);
- newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document));
-
- Assert.True(
- false,
- string.Format(
- "Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
- string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
- document.GetSyntaxRootAsync(context.CancellationToken).Result.ToFullString()));
- }
+ TestCode = originalSource,
+ FixedCode = fixedSource,
+ };
- // check if there are analyzer diagnostics left after the code fix
- if (!analyzerDiagnostics.Any())
- {
- break;
- }
- }
+ context.SetDefaults, DefaultVerifier>();
- // after applying all of the code fixes, compare the resulting string to the inputted one
- return GetStringFromDocument(document);
+ await context.RunAsync().ConfigureAwait(false);
}
}
diff --git a/Source/Moq.Analyzers.Test/Helpers/DiagnosticResult.cs b/Source/Moq.Analyzers.Test/Helpers/DiagnosticResult.cs
deleted file mode 100644
index 1d47fbd34..000000000
--- a/Source/Moq.Analyzers.Test/Helpers/DiagnosticResult.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-using Microsoft.CodeAnalysis;
-
-namespace TestHelper;
-
-///
-/// Struct that stores information about a Diagnostic appearing in a source
-///
-public struct DiagnosticResult
-{
- private DiagnosticResultLocation[] locations;
-
- public DiagnosticResultLocation[] Locations
- {
- get
- {
- return locations ?? (this.locations = new DiagnosticResultLocation[] { });
- }
-
- set
- {
- locations = value;
- }
- }
-
- public DiagnosticSeverity Severity { get; set; }
-
- public string Id { get; set; }
-
- public string Message { get; set; }
-
- public string Path
- {
- get
- {
- return this.Locations.Length > 0 ? this.Locations[0].Path : string.Empty;
- }
- }
-
- public int Line
- {
- get
- {
- return this.Locations.Length > 0 ? this.Locations[0].Line : -1;
- }
- }
-
- public int Column
- {
- get
- {
- return this.Locations.Length > 0 ? this.Locations[0].Column : -1;
- }
- }
-}
diff --git a/Source/Moq.Analyzers.Test/Helpers/DiagnosticResultLocation.cs b/Source/Moq.Analyzers.Test/Helpers/DiagnosticResultLocation.cs
deleted file mode 100644
index 114061d77..000000000
--- a/Source/Moq.Analyzers.Test/Helpers/DiagnosticResultLocation.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System;
-
-namespace TestHelper;
-
-///
-/// Location where the diagnostic appears, as determined by path, line number, and column number.
-///
-public struct DiagnosticResultLocation
-{
- public DiagnosticResultLocation(string path, int line, int column)
- {
- if (line < -1)
- {
- throw new ArgumentOutOfRangeException(nameof(line), "line must be >= -1");
- }
-
- if (column < -1)
- {
- throw new ArgumentOutOfRangeException(nameof(column), "column must be >= -1");
- }
-
- this.Path = path;
- this.Line = line;
- this.Column = column;
- }
-
- public string Path { get; }
-
- public int Line { get; }
-
- public int Column { get; }
-}
diff --git a/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.Helper.cs b/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.Helper.cs
deleted file mode 100644
index eedb9e92c..000000000
--- a/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.Helper.cs
+++ /dev/null
@@ -1,180 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Diagnostics;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.Diagnostics;
-using Microsoft.CodeAnalysis.Text;
-using Moq;
-
-namespace TestHelper;
-
-///
-/// Class for turning strings into documents and getting the diagnostics on them
-/// All methods are static.
-///
-public abstract partial class DiagnosticVerifier
-{
- private const string DefaultFilePathPrefix = "Test";
- private const string CSharpDefaultFileExt = "cs";
- private const string VisualBasicDefaultExt = "vb";
- private const string TestProjectName = "TestProject";
-
- private static readonly MetadataReference CorlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
- private static readonly MetadataReference SystemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location);
- private static readonly MetadataReference SystemLinqExpressions = MetadataReference.CreateFromFile(typeof(Expression).Assembly.Location);
- private static readonly MetadataReference GenericCollectionsReference = MetadataReference.CreateFromFile(typeof(IEnumerable<>).Assembly.Location);
- private static readonly MetadataReference CSharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location);
- private static readonly MetadataReference CodeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location);
- private static readonly MetadataReference MoqReference = MetadataReference.CreateFromFile(typeof(Mock).Assembly.Location);
- private static readonly MetadataReference NetStandardReference = MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("netstandard")).Location);
- private static readonly MetadataReference SystemRuntimeReference = MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("System.Runtime")).Location);
-
- ///
- /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it.
- /// The returned diagnostics are then ordered by location in the source document.
- ///
- /// The analyzer to run on the documents.
- /// The Documents that the analyzer will be run on.
- /// An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location.
- protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, Document[] documents)
- {
- Debug.Assert(documents != null, nameof(documents) + " != null");
-
- var projects = new HashSet();
- foreach (var document in documents)
- {
- projects.Add(document.Project);
- }
-
- var diagnostics = new List();
- foreach (var project in projects)
- {
- Debug.Assert(analyzer != null, nameof(analyzer) + " != null");
- var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
- var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(compilationWithAnalyzers.CancellationToken).Result;
- foreach (var diag in diags)
- {
- if (diag.Location == Location.None || diag.Location.IsInMetadata)
- {
- diagnostics.Add(diag);
- }
- else
- {
- for (int i = 0; i < documents.Length; i++)
- {
- var document = documents[i];
- var tree = document.GetSyntaxTreeAsync(compilationWithAnalyzers.CancellationToken).Result;
- if (tree == diag.Location.SourceTree)
- {
- diagnostics.Add(diag);
- }
- }
- }
- }
- }
-
- var results = SortDiagnostics(diagnostics);
- diagnostics.Clear();
- return results;
- }
-
- ///
- /// Create a Document from a string through creating a project that contains it.
- ///
- /// Classes in the form of a string.
- /// The language the source code is in.
- /// A Document created from the source string.
- protected static Document CreateDocument(string source, string language = LanguageNames.CSharp)
- {
- return CreateProject(new[] { source }, language).Documents.First();
- }
-
- ///
- /// Given classes in the form of strings, their language, and an IDiagnosticAnlayzer to apply to it, return the diagnostics found in the string after converting it to a document.
- ///
- /// Classes in the form of strings.
- /// The language the source classes are in.
- /// The analyzer to be run on the sources.
- /// An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location.
- private static Diagnostic[] GetSortedDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer)
- {
- return GetSortedDiagnosticsFromDocuments(analyzer, GetDocuments(sources, language));
- }
-
- ///
- /// Sort diagnostics by location in source document.
- ///
- /// The list of Diagnostics to be sorted.
- /// An IEnumerable containing the Diagnostics in order of Location.
- private static Diagnostic[] SortDiagnostics(IEnumerable diagnostics)
- {
- return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
- }
-
- ///
- /// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it.
- ///
- /// Classes in the form of strings.
- /// The language the source code is in.
- /// A Tuple containing the Documents produced from the sources and their TextSpans if relevant.
- private static Document[] GetDocuments(string[] sources, string language)
- {
- if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic)
- {
- throw new ArgumentException("Unsupported Language");
- }
-
- var project = CreateProject(sources, language);
- var documents = project.Documents.ToArray();
-
- if (sources.Length != documents.Length)
- {
- throw new SystemException("Amount of sources did not match amount of Documents created");
- }
-
- return documents;
- }
-
- ///
- /// Create a project using the inputted strings as sources.
- ///
- /// Classes in the form of strings.
- /// The language the source code is in.
- /// A Project created out of the Documents created from the source strings.
- private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
- {
- const string fileNamePrefix = DefaultFilePathPrefix;
- string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
-
- var projectId = ProjectId.CreateNewId(debugName: TestProjectName);
-
- var solution = new AdhocWorkspace()
- .CurrentSolution
- .AddProject(projectId, TestProjectName, TestProjectName, language)
- .AddMetadataReference(projectId, CorlibReference)
- .AddMetadataReference(projectId, SystemCoreReference)
- .AddMetadataReference(projectId, CodeAnalysisReference)
- .AddMetadataReference(projectId, SystemLinqExpressions)
- .AddMetadataReference(projectId, CSharpSymbolsReference)
- .AddMetadataReference(projectId, GenericCollectionsReference)
- .AddMetadataReference(projectId, SystemRuntimeReference)
- .AddMetadataReference(projectId, NetStandardReference)
- .AddMetadataReference(projectId, MoqReference);
-
- int count = 0;
- foreach (var source in sources)
- {
- var newFileName = fileNamePrefix + count + "." + fileExt;
- var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
- solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
- count++;
- }
-
- return solution.GetProject(projectId);
- }
-}
diff --git a/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.cs b/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.cs
index 7e52849f7..6f87cdd72 100644
--- a/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.cs
+++ b/Source/Moq.Analyzers.Test/Helpers/DiagnosticVerifier.cs
@@ -1,88 +1,22 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Testing;
-namespace TestHelper;
+namespace Moq.Analyzers.Test.Helpers;
-///
-/// Superclass of all Unit Tests for DiagnosticAnalyzers
-///
-public abstract partial class DiagnosticVerifier
+public abstract class DiagnosticVerifier
+ where TAnalyzer : DiagnosticAnalyzer, new()
{
- ///
- /// Get the CSharp analyzer being tested - to be implemented in non-abstract class
- ///
- /// Diagnostics to be used in test
- protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
+ protected async Task VerifyCSharpDiagnostic(string source)
{
- return null;
- }
-
- ///
- /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source
- /// Note: input a DiagnosticResult for each Diagnostic expected
- ///
- /// A class in the form of a string to run the analyzer on
- /// String representation of diagnostics results
- protected string VerifyCSharpDiagnostic(string source)
- {
- return VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer());
- }
-
- ///
- /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source
- /// Note: input a DiagnosticResult for each Diagnostic expected
- ///
- /// An array of strings to create source documents from to run the analyzers on
- /// String representation of diagnostics results
- protected string VerifyCSharpDiagnostic(string[] sources)
- {
- return VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer());
- }
-
- ///
- /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run,
- /// then verifies each of them.
- ///
- /// An array of strings to create source documents from to run the analyzers on
- /// The language of the classes represented by the source strings
- /// The analyzer to be run on the sources
- /// String representation of diagnostics results
- private string VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer)
- {
- var diagnostics = GetSortedDiagnostics(sources, language, analyzer);
- return VerifyDiagnosticResults(diagnostics);
- }
-
- ///
- /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results.
- /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic.
- ///
- /// The Diagnostics found by the compiler after running the analyzer on the source code
- /// String representation of diagnostics results
- private string VerifyDiagnosticResults(IEnumerable actualResults)
- {
- StringBuilder result = new StringBuilder();
- int i = 1;
- foreach (var diagnostic in actualResults)
+ CSharpAnalyzerTest context = new()
{
- result.AppendLine("Diagnostic " + i);
- result.AppendLine("\tId: " + diagnostic.Id);
- result.AppendLine("\tLocation: " + diagnostic.Location);
- var sourceSpan = diagnostic.Location.SourceSpan;
- var code = diagnostic.Location.SourceTree.GetText();
- result.AppendLine("\tHighlight: " + code.GetSubText(sourceSpan));
- var lineSpan = diagnostic.Location.GetLineSpan();
- result.AppendLine("\tLines: " + string.Join("\n", code.Lines.Where(x => x.LineNumber >= lineSpan.StartLinePosition.Line && x.LineNumber <= lineSpan.EndLinePosition.Line).Select(x => x.ToString().Trim())));
- result.AppendLine("\tSeverity: " + diagnostic.Severity);
- result.AppendLine("\tMessage: " + diagnostic.GetMessage());
- result.AppendLine();
+ TestCode = source,
+ };
- i += 1;
- }
+ context.SetDefaults, DefaultVerifier>();
- return result.ToString();
+ await context.RunAsync().ConfigureAwait(false);
}
}
diff --git a/Source/Moq.Analyzers.Test/Moq.Analyzers.Test.csproj b/Source/Moq.Analyzers.Test/Moq.Analyzers.Test.csproj
index f23cac3e0..a5f5f7084 100644
--- a/Source/Moq.Analyzers.Test/Moq.Analyzers.Test.csproj
+++ b/Source/Moq.Analyzers.Test/Moq.Analyzers.Test.csproj
@@ -19,8 +19,11 @@
runtime; build; native; contentfiles; analyzers; buildtransitive
all
+
+
-
+
+
diff --git a/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIfMockedInterfaceHasConstructorParameters.verified.txt b/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIfMockedInterfaceHasConstructorParameters.verified.txt
deleted file mode 100644
index 8822aefe0..000000000
--- a/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIfMockedInterfaceHasConstructorParameters.verified.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-Diagnostic 1
- Id: Moq1001
- Location: SourceFile(Test0.cs[231..241))
- Highlight: (25, true)
- Lines: var mock1 = new Mock(25, true);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 2
- Id: Moq1001
- Location: SourceFile(Test0.cs[283..290))
- Highlight: ("123")
- Lines: var mock2 = new Mock("123");
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 3
- Id: Moq1001
- Location: SourceFile(Test0.cs[332..342))
- Highlight: (25, true)
- Lines: var mock3 = new Mock(25, true);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 4
- Id: Moq1001
- Location: SourceFile(Test0.cs[384..391))
- Highlight: ("123")
- Lines: var mock4 = new Mock("123");
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
diff --git a/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIfMockedInterfaceHasConstructorParametersAndExplicitMockBehavior.verified.txt b/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIfMockedInterfaceHasConstructorParametersAndExplicitMockBehavior.verified.txt
deleted file mode 100644
index 3501f8d28..000000000
--- a/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIfMockedInterfaceHasConstructorParametersAndExplicitMockBehavior.verified.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-Diagnostic 1
- Id: Moq1001
- Location: SourceFile(Test0.cs[263..292))
- Highlight: (MockBehavior.Default, "123")
- Lines: var mock1 = new Mock(MockBehavior.Default, "123");
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 2
- Id: Moq1001
- Location: SourceFile(Test0.cs[334..365))
- Highlight: (MockBehavior.Strict, 25, true)
- Lines: var mock2 = new Mock(MockBehavior.Strict, 25, true);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 3
- Id: Moq1001
- Location: SourceFile(Test0.cs[407..436))
- Highlight: (MockBehavior.Default, "123")
- Lines: var mock3 = new Mock(MockBehavior.Default, "123");
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 4
- Id: Moq1001
- Location: SourceFile(Test0.cs[478..508))
- Highlight: (MockBehavior.Loose, 25, true)
- Lines: var mock4 = new Mock(MockBehavior.Loose, 25, true);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
diff --git a/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIsRealMoqIsUsedWithInvalidParameters.verified.txt b/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIsRealMoqIsUsedWithInvalidParameters.verified.txt
deleted file mode 100644
index efa763351..000000000
--- a/Source/Moq.Analyzers.Test/NoConstructorArgumentsForInterfaceMockAnalyzerTests.ShouldFailIsRealMoqIsUsedWithInvalidParameters.verified.txt
+++ /dev/null
@@ -1,48 +0,0 @@
-Diagnostic 1
- Id: Moq1001
- Location: SourceFile(Test0.cs[550..559))
- Highlight: (1, true)
- Lines: var mock1 = new Moq.Mock(1, true);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 2
- Id: Moq1001
- Location: SourceFile(Test0.cs[605..610))
- Highlight: ("2")
- Lines: var mock2 = new Moq.Mock("2");
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 3
- Id: Moq1001
- Location: SourceFile(Test0.cs[656..687))
- Highlight: (Moq.MockBehavior.Default, "3")
- Lines: var mock3 = new Moq.Mock(Moq.MockBehavior.Default, "3");
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 4
- Id: Moq1001
- Location: SourceFile(Test0.cs[733..762))
- Highlight: (MockBehavior.Loose, 4, true)
- Lines: var mock4 = new Moq.Mock(MockBehavior.Loose, 4, true);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 5
- Id: Moq1001
- Location: SourceFile(Test0.cs[808..830))
- Highlight: (MockBehavior.Default)
- Lines: var mock5 = new Moq.Mock(MockBehavior.Default);
- Severity: Warning
- Message: Mocked interfaces cannot have constructor parameters.
-
-Diagnostic 6
- Id: Moq1001
- Location: SourceFile(Test0.cs[876..898))
- Highlight: (MockBehavior.Default)
- Lines: var mock6 = new Moq.Mock