nunit/nunit.analyzers

NUnit1032 (missing Dispose), if dispose is wrapped in "(… as IDisposable)?.Dispose()"

DrPepperBianco opened this issue · 2 comments

OK, basically I had a test class. In the Test-Class was a member "IServiceProvider _serviceProvider". In the [TearDown]-method the service provider was disposed with the following code:

(_serviceProvider as IDisposable)?.Dispose();
_serviceProvider = null;

When compiled I got the above mentioned error: Error NUnit1032: The field _serviceProvider should be Disposed in a method annotated with [TearDownAttribute] (https://github.com/nunit/nunit.analyzers/tree/master/documentation/NUnit1032.md)

  1. IServiceProvider doesn’t inherit the IDisposable interface, hence the as operator in the TearDown method.
  2. I explicitly call Dispose() in the TearDown method.

So why do I get this error message!? This is probably a bug.

So for reference, this is the NuGet Config:

<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="NUnit" Version="4.1.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="NUnit.Analyzers" Version="4.2.0">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.2">
    <PrivateAssets>all</PrivateAssets>
    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

Looks like this belongs to the analyzer. Moving it there.

The analyzer already recognized:

if (field is IDisposable disposable)
    dispoable.Dispose()

and

((IDisposable)field.Dispose())

I did create a PR to add support for (field as IDisposable)?.Dispose()