Skip to content

Commit

Permalink
Fix the PosInfoMoq2004 to not check the Mock<T> instantiation with th…
Browse files Browse the repository at this point in the history
…e factory lambda expression (fixes: #39).
  • Loading branch information
GillesTourreau committed Oct 23, 2024
1 parent cd59a08 commit bd80329
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ private static void Analyze(SyntaxNodeAnalysisContext context)
return;
}

// Check if the mock instantiation is with a factory.
// In this case, we ignore the matching of the constructor arguments.
var constructorSymbol = context.SemanticModel.GetSymbolInfo(objectCreation, context.CancellationToken);

if (moqSymbols.IsMockConstructorWithFactory(constructorSymbol.Symbol))
{
return;
}

var moqExpressionAnalyzer = new MoqExpressionAnalyzer(moqSymbols, context.SemanticModel);

// Check there is "new Mock<I>()" statement.
Expand Down Expand Up @@ -90,8 +99,7 @@ private static void Analyze(SyntaxNodeAnalysisContext context)
.Select(a => a.Expression.GetLocation())
.ToArray();

var diagnostic = Diagnostic.Create(Rule, locations[0], locations.Skip(1));
context.ReportDiagnostic(diagnostic);
context.ReportDiagnostic(Rule, locations);

return;
}
Expand Down
3 changes: 2 additions & 1 deletion src/Moq.Analyzers/Moq.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
- Add new rules:
- PosInfoMoq2014: The delegate in the argument of the Returns() method must return a value with same type of the mocked method.
- PosInfoMoq2015: The Protected().Setup() method must match the return type of the mocked method.
- Fix the PosInfoMoq1001 rule for the Mock&lt;T&gt; instantiation with the lambad expression to create mock object.
- Fix the PosInfoMoq1001 rule for the Mock&lt;T&gt; instantiation with the lambda expression to create mock instances.
- Fix the PosInfoMoq2004 rule for the Mock&lt;T&gt; instantiation with the lambda expression to create mock instances.

1.10.0
- Add new rules:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,36 @@ await Verifier.VerifyAnalyzerAsync(
.WithLocation(1).WithArguments("2"));
}

[Theory]
[InlineData("")]
[InlineData(", MockBehavior.Strict")]
public async Task Interface_WithFactoryLambdaExpression(string behavior)
{
var source = @"
namespace ConsoleApplication1
{
using Moq;
public class TestClass
{
public void TestMethod()
{
var mock1 = new Mock<I>(() => new C()" + behavior + @");
}
}
public interface I
{
}
public class C : I
{
}
}";

await Verifier.VerifyAnalyzerAsync(source);
}

[Fact]
public async Task Class()
{
Expand Down

0 comments on commit bd80329

Please sign in to comment.