Search code examples
garbage-collectionrepositorycoding-stylenunit

NUnit OneTimeTearDown Garbage collection best practice


At first, I have declared the variables at the beginning of my class

        private AddressRepository sut;
        private Mock<TransactionDbContext> mockDBContext;

In the OneTimeSetUp, I have created the set up code

        [OneTimeSetUp]
        public void Setup()
        {
            var options = new DbContextOptionsBuilder<TransactionDbContext>().Options;
            mockDBContext = new Mock<TransactionDbContext>(options);
            var dbSetMock = new Mock<DbSet<Address>>();
            var data = ValueTask.FromResult(new Address() { AddressLine1 = "address line 1" 
        });
            dbSetMock.Setup(s => s.FindAsync(It.IsAny<Guid>())).Returns(data);
            mockDBContext.Setup(s => s.Set<Address>()).Returns(dbSetMock.Object);

        }

Question, do I need to write additional code to handle garbage collection, or should I unassign all variables as following to speeds up GC?

        [OneTimeTearDown]
        public void TearDown()
        {
            //unassign all variables
            mockDBContext = null;
            sut = null;
            
           //Possibly call GC.Collect?
            GC.Collect();
        }

Any coding advice will be well appreciated.


Solution

  • You should dispose of any disposable external resources, which you acquire. Where you do this depends on where you acquire the resource.

    1. If you acquire it in your test fixture constructor, then let NUnit dispose of it. You do that by having the fixture class implement IDispose.

    2. If you acquire it in a OneTimeSetUp, then dispose of it in the corresponding OneTimeTearDown.

    3. If you acquire it in a SetUp, then dispose of it in the corresponding TearDown.

    4. If you acuire it in a TestMethod, then dispose of it before that method returns. The simplest way to do this is via using.

    All that said and explained, your example doesn't seem to acquire any disposable external resources. So I would not do any of those things. :-)

    Generally, the time people spend figuring out overly complicated code outweighs any small advantage in efficiency. So wait till you see a performance problem before you fix it.