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