Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 600
stefando Avatar asked Dec 04 '22 23:12

stefando


2 Answers

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

like image 74
Eric Lippert Avatar answered Dec 07 '22 11:12

Eric Lippert


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)

like image 27
SLaks Avatar answered Dec 07 '22 12:12

SLaks