Is there a way how to continue after Debug.Assert() from the code?

蹲街弑〆低调 提交于 2019-12-07 09:53:39

问题


My code operates on data which "should" be correct. However during development there are occasions when I obtain invalid data.
When that happens I would like to raise the debug assert and, if user choose to continue, the code would filter out the invalid records and continue to operate on "safe" data.

// assert incorrect data
Debug.Assert(person.Items.All(item => item.IsValid), "Inconsistent data!");

// operate on filtered data
this.ItemViewModels = new ObservableCollection<ItemViewModel>(
                             person.Items
                                   .Where(i =>item.IsValid) // Use only correct data
                                   .Select(i => new ItemViewModel(lang, i)));

I would like to unit test the code path when I choose to operate on the filtered data.

Question: Is there a way how to get past the assert call in the unit test?
Some equivalent to clicking OK=Continue in the "Assertion Failed" dialogue?

TIA


回答1:


You should not use Debug.Assert for this.
Debug.Assert is intended to be used only as a debugging aid.
It will not be compiled at all in Release mode.

Instead, you should create your own method, which will show the user a simpler dialog box, and can be configured to always continue for unit testing. (eg, use a public static bool ShowWarnings property)




回答2:


In addition to SLaks's answer I would add that what you want to do is logically inconsistent. An assert should be used to document a condition that cannot possibly be false. If the false condition ever arises then you know you have a bug; the purpose of an assert is (1) as a kind of comment that describes to the reader what must be true at this point in the code, and (2) a debugging aid that tells you when you have a bug.

Since correct asserts in correct code never fire, there is no way to test an assert firing. The premise of a test is that it produces a possible configuratin of your software and verifies its correctness; but correct code with correct asserts never have a configuration where the assert fires.

It sounds like you are using Assert not to document something that you know is true but rather something that you hope is true or is normally true. Don't use assertions for that. If there is any inputs to the program that cause the assertion to be violated then you need to either remove the assertion, or cause an exception when you get the invalid data so that the assertion never sees it. Assertions are meant to document what must be true, not what is true most of the time.

See also this related question:

Debug.Assert vs Exception Throwing



来源:https://stackoverflow.com/questions/4886790/is-there-a-way-how-to-continue-after-debug-assert-from-the-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!