Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check property of an exception with NUnit 2.6

Tags:

c#

nunit

What is the most idiomatic way with NUnit 2.6 to check equality of a property of an exception?

Code I'd like to write but does not work: Expected 3, but was <empty>

Assert.That(() => someObject.MethodThrows(),
  Throws.TypeOf<SomeException>().With.Property("Data").Count.EqualTo(3), /* Data is a collection */
  "Exception expected");

I could use nested Assert expressions, but that seems overly complicated and unnecessary:

  Assert.AreEqual(3,
    Assert.Throws<SomeException>(
      () => someObject.MethodThrows(),
      "Exception expected").Data.Count);

edit In fact, the first code example does work. I don't know why it did not work several times before posting this question

like image 435
knittl Avatar asked Sep 02 '11 18:09

knittl


2 Answers

I can't speak to NUnit 2.6, but on NUnit 2.5 the following test:

Public Class MyException
    Inherits Exception
    Public Property SomeList As New List(Of String) From {"hello", "world"}
End Class

<TestFixture()>
Public Class TestClass1
    Public Shared Sub DoSomething()
        Throw New MyException()
    End Sub

    <Test()>
    Public Sub TestExample()
        Assert.That(Sub() DoSomething(), Throws.TypeOf(Of MyException)().With.Property("SomeList").Count.EqualTo(3))
    End Sub
End Class

produces this following error message:

Expected: <ClassLibrary1.MyException> and property SomeList property Count equal to 3
But was:  < "hello", "world" >

Could this just be a regression in the NUnit 2.6 beta?

like image 116
ckittel Avatar answered Nov 03 '22 03:11

ckittel


I would go with this:

var exception = Assert.Throws<SomeException>(() => someObject.MethodThrows(),
                                             "Exception expected")
Assert.AreEqual(3, exception.Data.Count);

This is the clearest you can get:

  • Unlike your first example, this is refactoring safe
  • It asserts one thing at a time, not multiple like both of your examples.
like image 26
Daniel Hilgarth Avatar answered Nov 03 '22 01:11

Daniel Hilgarth