开发者

NUnit - Asserting Exception and properties

开发者 https://www.devze.com 2023-01-05 07:17 出处:网络
I\'d like to Assert that an exception is being thrown and then check some of the properties of the thrown exception.

I'd like to Assert that an exception is being thrown and then check some of the properties of the thrown exception.

I was under the impression that I could do something like开发者_运维问答 the following:

ICommand command = CreateCommandObj();
Assert.That( () => command.DoWork(), Throws.TypeOf<ArgumentException>(),                        
                     Has.Property("ParamName").EqualTo("myParam") &
Has.Property("Message").EqualTo("myMessage") );

However this doesn't even compile and looking at the expected parameters for Assert.That I can't see how I would be able to do this? I'm sure I have used this before though...

Note the above is a contrived example to illustrate the point, ignore the fact I am looking for an ArgumentException on a method that doesnt except any parameters :)

Any help appreciated.

1) Cannot convert lambda expression to type 'object' because it is not a delegate type.


Ok, sorted.

I need to use the following syntax:

ICommand command = CreateCommandObj();
Assert.That( () => command.DoWork(), 
                   Throws.TypeOf<ArgumentException>()
                   .And.Message.Equals("MyMessage"));

This approach allows me to check properties on the thrown exception. I can add any number of And or Or's to the Assert.

Thanks everyone for the suggestions.


You can also do this:

var exception = Assert.Throws<ArgumentException>(() => {
    command.DoWork();
});
Assert.AreEqual("myMessage", exception.Message);


You test for exceptions with the [ExpectedException] attribute on your method. e.g.

[Test] 
[ExpectedException(typeof(InvalidOperationException))]
public void Test_SomeMethod()
{
    something.SomeMehthod();
}

You can set the properties of the expected exception in the constructor of the ExpectedException attribute.

EDIT You could also specify your test attributes like the following:

[Test]
[ExpectedException(ExpectedException = typeof(InvalidOperationException), ExpectedMessage = "Somethings not right")]
public void Test_SomeMethond()
{
    something.SomeMehthod();
}


Try && - logical and versus bitwise and

Edit:

I think you're looking for Assert.Throws if you're using the constraint interface. Not sure how you would assert on message. I think the old style is clearer for what you're trying to accomplish:

  try
  {
    command.DoWork();
    Assert.Fail("ArgumentException Expected");
  }
  catch (ArgumentException e)
  {
    Assert.AreEqual("Expected Message", e.Message);
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消