Best practice for debug Asserts during Unit testing

后端 未结 12 2223
执笔经年
执笔经年 2020-12-23 02:35

Does heavy use of unit tests discourage the use of debug asserts? It seems like a debug assert firing in the code under test implies the unit test shouldn\'t exist or the d

12条回答
  •  我在风中等你
    2020-12-23 03:04

    I took the approach of disabling the assert only where needed as opposed to doing it project wide. Here is an approach where the assert can be suspend so it doesn't interfere with the test flow.

    public static class TraceListenerCollectionEx
    {
        /// 
        /// This is a helper class that allows us to suspend asserts / all trace listeners
        /// 
        public class SuspendTrackerDisposable : IDisposable
        {
            private readonly TraceListenerCollection _traceListenerCollection;
            private readonly TraceListener[] _suspendedListeners;
    
            public SuspendTrackerDisposable(TraceListenerCollection traceListenerCollection)
            {
                _traceListenerCollection = traceListenerCollection;
    
                var numListeners = traceListenerCollection.Count;
                _suspendedListeners = new TraceListener[numListeners];
                for( int index = 0; index < numListeners; index += 1 )
                    _suspendedListeners[index] = traceListenerCollection[index];
    
                traceListenerCollection.Clear();
            }
    
            public void Dispose()
            {
                _traceListenerCollection.AddRange(_suspendedListeners);
            }
        }
    
        public static SuspendTrackerDisposable AssertSuspend(this TraceListenerCollection traceListenerCollection) => new SuspendTrackerDisposable(traceListenerCollection);
    }
    

    Here is an example usage within a test:

        [TestMethod]
        public void EnumDefaultTest()
        {
            using(Trace.Listeners.AssertSuspend()) {
                Enum.DefaultValue.ShouldBe(CarClass.Unknown);  
            }
        }
    

    The code executed within the using block, only one line in this case, will have their asserts disabled.

提交回复
热议问题