简体   繁体   中英

How can I use Assert.Throws with property get?

I wish to use Assert.Throws with a property get.

Eg

object shouldFail = myobj[fakeField];

my attempts, albeit bad ones to help demonstrate my need.

Assert.Throws<MyException>(() => object shouldFail = myobj[fakeField]);
Assert.Throws<MyException>(() => myobj[fakeField]);

The syntax error I get is Only assignment, call, decrement, and new object expressions can be used as a statement . I understand that. So I am asking without a try/catch, how can I test for an exception on that line of code in the eg above?

I am aware of [ExpectedException(typeof(MyException))]

You can't really do it in lambda with expression since you need to eat return value. Try use statement block instead:

Assert.Throws<MyException>(() => { object shouldFail = myobj[fakeField];});

Note: it is not recommended to throw from get ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM