Should Dispose methods be unit tested?

后端 未结 4 780
自闭症患者
自闭症患者 2021-01-03 23:25

I am using C#. Is it advised to unit test dispose methods? If so why, and how should one test these methods?

4条回答
  •  再見小時候
    2021-01-04 00:06

    If your class creates and works with unmanaged resources, then you should definitely ensure that Dispose works as you expect it to - although it could be argued it is more of an integration test due to the type of hoops you're going to have to jump through.

    If your class only creates / uses managed resources ( i.e. they implement IDisposable ) then all you really need to ensure is that the Dispose method on these resources is invoked at the correct time - if you are using some form of DI then you can inject a mock and assert that Dispose was called.

    Look at the complexity of your dispose methods - if they are only a couple of lines long with maybe 1 condition, ask yourself if there really is a benefit in unit testing them.

提交回复
热议问题