Skip to content

NUnit1032 - disposals in overridden methods not detectedΒ #921

Closed

Description

@PiotrKlecha

Object disposal that occurs in an overriden method invoked by a base test class is not detected and a diagnostic is reported.

An simplified example that demonstrates the problem:

[TestFixture]
public class BaseTest
{
	[SetUp]
	public void SetUp()
	{
		OnSetUp();
	}

	[TearDown]
	public void TearDown()
	{
		OnTearDown();
	}

	protected virtual void OnSetUp()
	{
	}

	protected virtual void OnTearDown()
	{
	}
}

[TestFixture]
public class InheritedTest : BaseTest
{
	private IDisposable? disposable;

	protected override void OnSetUp()
	{
		base.OnSetUp();
		disposable = new ADisposable();
	}

	protected override void OnTearDown()
	{
		disposable?.Dispose();
		base.OnTearDown();
	}
}

Activity

  1. manfred-brands commented on Sep 29, 2025

    @manfred-brands
    Member

    The analyzer only looks at methods in the current class, it does not have access to code in different classes and therefore does not know that the overridden methods are called by. SetUp/TearDown method.

    NUnit allows a SetUp method in both base and derived class. So if you can, replace the override with a separate method and add the appropriate attribute.

  2. PiotrKlecha commented on Sep 29, 2025

    @PiotrKlecha
    Author

    NUnit allows a SetUp method in both base and derived class. So if you can, replace the override with a separate method and add the appropriate attribute.

    This is potentially an option, but modifying correct code only to conform to the analyzer doesn't seem entirely ideal. Are there any other possible solutions to this problem? E.g. adding a configuration option to specify "additional" SetUp/TearDown methods (similiar to existing dotnet_diagnostic.NUnit1032.additional_dispose_methods)?

  3. manfred-brands commented on Oct 1, 2025

    @manfred-brands
    Member

    I create a PR where you can specify the additional setup and teardown methods:

    dotnet_diagnostic.NUnit1032.additional_setup_methods = OnSetUp
    dotnet_diagnostic.NUnit1032.additional_teardown_methods = OnTearDown
    

    The methods must be override as otherwise they cannot be called by the base class.

  4. added this to the Release 4.11 milestone on Oct 6, 2025
  5. changed the title [-]NUnit1032 - disposals in overriden methods not detected[/-] [+]NUnit1032 - disposals in overridden methods not detected[/+] on Oct 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions