False positive on RSPEC-2201

115 views
Skip to first unread message

martin...@codestudio.com

unread,
Mar 14, 2018, 5:40:58 AM3/14/18
to SonarQube
So I have a C# unit test that looks like this:

        [Fact]
       
public void MyTest()
       
{
           
// Arrange.
           
var classUnderTest = new MyClass();

           
// Act.            
           
Action action = () =>
           
{
                classUnderTest
.MyMethod(null).ToList();
           
};

           
// Assert.
            action
.Should()
               
.Throw<ArgumentNullException>();
       
}



I'm getting the error on the ToList() call. The error given is 'S2201 Use the return value of method 'ToList', which has no side effect.' However ToList does have a side effect. In this instance MyMethod(null) is a method that returns IEnumerable<T> and has a yield return within it. It will throw an argument null exception as null is passed in, however it only does this if the returned IEnumerable<T> is iterated over. As such the side effect that ToList has is to cause the IEnumerable<T> to be iterated. I get the same result with .Any(). However I want to use .List() in other tests as I want to ensure that MyMethod picks up things if the collection that is passed to it has duff data in the middle of it.

https://rules.sonarsource.com/csharp/RSPEC-2201

Amaury Leve

unread,
Apr 5, 2018, 3:18:19 AM4/5/18
to martin...@codestudio.com, SonarQube
Hi Martin,

This is indeed a False Positive although we have been working on a new rule that might be interesting for you in this situation (https://github.com/SonarSource/sonar-csharp/issues/1165). As you can see it is recommended to split yield methods into 2 parts and doing so you won't need this call to ToList() to actually check the ArgumentNullException being thrown.

Cheers,
Amaury

--
You received this message because you are subscribed to the Google Groups "SonarQube" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sonarqube+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/sonarqube/382eb168-e111-4045-9b14-95c2fb77a7b2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--

Amaury Levé | SonarSource

Software Developer - .Net Team

http://sonarsource.com


Are you using SonarLint in your IDE? 
Reply all
Reply to author
Forward
0 new messages