9

it seems there are no delegates to properties. Is there a convenient way to do the following?

Assert.Throws<InvalidOperationException>(
       delegate
       {
           // Current is a property as we all know
           nullNodeList.GetEnumerator().Current;
       });
atamanroman
  • 11,607
  • 7
  • 57
  • 81

4 Answers4

11

Fast-forward four years and NUnit now supports this (current version is v2.6 - I've not checked which version this was introduced).

Assert.That(() => nullNodeList.GetEnumerator().Current,
    Throws.InvalidOperationException);
Niels van der Rest
  • 31,664
  • 16
  • 80
  • 86
EddPorter
  • 168
  • 1
  • 9
8
Assert.Throws<InvalidOperationException>(
    delegate { object current = nullNodeList.GetEnumerator().Current; });
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • @Anton Hi anton I would like to know is this the way to use to Test for readonly property of a class that is public ? – Deeptechtons Jul 25 '12 at 05:05
1

You could try assigning it to a variable or try enumerating:

Assert.Throws<InvalidOperationException>(delegate
{
    // Current is a property as we all know
    object current = nullNodeList.GetEnumerator().Current;
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

why not say:

Assert.Throws<InvalidOperationException>(
    () => nullNodeList.GetEnumerator().Current);
sukru
  • 2,229
  • 14
  • 15
  • 1
    You will still need to do an actual (throw away) assignment and keep the {}, so: (() => { var x = nullNodeList.GetEnumerator().Current; }) – bytedev Jan 31 '13 at 16:08
  • That doesn't compile. Error: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement – Bartosz Wójtowicz Nov 07 '19 at 13:35
  • Follow up on @bytedev : For clarity, a discard ( '_' ) can be used (https://learn.microsoft.com/en-us/dotnet/csharp/discards). So the statement becomes: `Assert.Throws(() => { _ = nullNodeList.GetEnumerator().Current; });` – Remco te Wierik Mar 03 '20 at 10:26