Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Analyzers/MSTest.Analyzers/UseProperAssertMethodsAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,16 @@ expectedArgument.ConstantValue.Value is int expectedValue &&
{
// We have Assert.AreEqual(expectedCount, collection.Count/Length)
// We want Assert.HasCount(expectedCount, collection)
// Assert.HasCount takes int, so skip if expectedCount is not an int (e.g. int?, long, uint, decimal).
if (expectedArgument.Type?.SpecialType != SpecialType.System_Int32)
{
nodeToBeReplaced1 = null;
replacement1 = null;
nodeToBeReplaced2 = null;
replacement2 = null;
return CountCheckStatus.Unknown;
}

// So, only a single replacement is needed. We replace collection.Count with collection.
nodeToBeReplaced1 = actualArgument.Syntax; // collection.Count
replacement1 = expression; // collection
Expand Down Expand Up @@ -1461,6 +1471,16 @@ expectedArgument.ConstantValue.Value is int expectedLinqValue &&
{
// We have Assert.AreEqual(expectedCount, enumerable.Count())
// We want Assert.HasCount(expectedCount, enumerable)
// Assert.HasCount takes int, so skip if expectedCount is not an int (e.g. int?, long, uint, decimal).
if (expectedArgument.Type?.SpecialType != SpecialType.System_Int32)
{
nodeToBeReplaced1 = null;
replacement1 = null;
nodeToBeReplaced2 = null;
replacement2 = null;
return CountCheckStatus.Unknown;
}

nodeToBeReplaced1 = actualArgument.Syntax; // enumerable.Count()
replacement1 = linqCollection; // enumerable
nodeToBeReplaced2 = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2086,6 +2086,35 @@ await VerifyCS.VerifyCodeFixAsync(
fixedCode);
}

[TestMethod]
public async Task WhenAssertAreEqualWithCollectionCountNonZeroNonIntExpected()
{
string code = """
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;

[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod()
{
int? nullableCount = 3;
long longCount = 3L;
var list = new List<int> { 1, 2, 3 };
Assert.AreEqual(nullableCount, list.Count);
Assert.AreEqual(nullableCount, list.AsEnumerable().Count());
Assert.AreEqual(longCount, list.Count);
Assert.AreEqual(longCount, list.AsEnumerable().Count());
}
}
""";

// Should not trigger MSTEST0037 because Assert.HasCount takes int, not int? or long
await VerifyCS.VerifyAnalyzerAsync(code);
}

[TestMethod]
public async Task WhenAssertAreNotEqualWithCollectionCountZero()
{
Expand Down
Loading