How do I unit test a finalizer?

前端 未结 4 1558
不思量自难忘°
不思量自难忘° 2021-02-05 07:25

I have the following class which is a decorator for an IDisposable object (I have omitted the stuff it adds) which itself implements IDisposable using

4条回答
  •  猫巷女王i
    2021-02-05 08:11

    I use Appdomain (see sample below). Class TemporaryFile creates temporary file in constructor and delete's it in Dispose or in finalizer ~TemporaryFile().

    Unfortunately, GC.WaitForPendingFinalizers(); doesn't help me to test finalizer.

        [Test]
        public void TestTemporaryFile_without_Dispose()
        {
            const string DOMAIN_NAME = "testDomain";
            const string FILENAME_KEY = "fileName";
    
            string testRoot = Directory.GetCurrentDirectory();
    
            AppDomainSetup info = new AppDomainSetup
                                      {
                                          ApplicationBase = testRoot
            };
            AppDomain testDomain = AppDomain.CreateDomain(DOMAIN_NAME, null, info);
            testDomain.DoCallBack(delegate
            {
                TemporaryFile temporaryFile = new TemporaryFile();
                Assert.IsTrue(File.Exists(temporaryFile.FileName));
                AppDomain.CurrentDomain.SetData(FILENAME_KEY, temporaryFile.FileName);
            });
            string createdTemporaryFileName = (string)testDomain.GetData(FILENAME_KEY);
            Assert.IsTrue(File.Exists(createdTemporaryFileName));
            AppDomain.Unload(testDomain);
    
            Assert.IsFalse(File.Exists(createdTemporaryFileName));
        }
    

提交回复
热议问题