1

The new NUnit Version 3.x does not support ExpectedExceptionAttribute any longer. There is an Assert.Throws<MyException>() instead. Probably a better logical concept. But I failed to find any replacement for the old good MatchType - is there any? MyException can be thrown with a number of parameters, in NUnit 2.x I could compare the exception message for the containment of a certain text fragment to know which parameter was used (and, certainly, I am not going to have dozens of exception classes instead of the just logical one). How can this be handled with NUnit 3.x? I was unable to find a hint.

With NUnit 2.x, I would do the following:

[Test]
[ExpectedException(ExpectedException=typeof(MyException),  ExpectedMessage="NON_EXISTENT_KEY", MatchType=MessageMatch.Contains)]
public void DeletePatient_PatientExists_Succeeds()
 {
    Person p    = new Person("P12345", "Testmann^Theo", new DateTime(1960, 11, 5), Gender.Male);
    MyDatabase.Insert(p);

    MyDatabase.Delete(p.Key);

    // Attemp to select from a database with a non-existent key.
    // MyDatabase throws an exception of type MyException with "NON_EXISTENT_KEY" within the message string,
    // so that I can distinguish it from cases where MyException is thrown with different message strings.
    Person p1   = MyDatabase.Select(p.Key);
 }

How can I do anything similar with NUnt 3.x?

Please consider what I mean: the means that NUnit provides for, are not sufficient to recognize the parameters with which the exception was thrown, so this is a different question.

4

2 Answers 2

2
var ex = Assert.Throws<MyException>(()=> MyDatabase.Select(p.Key));
StringAssert.Contains("NON_EXISTENT_KEY", ex.Message);
Sign up to request clarification or add additional context in comments.

5 Comments

I do not understand what you mean.
Assert.Throws check thrown exception of expected type, and returns instance of the exception. In next line StringAssert checks, if expected string contains in Exception.Message. Exactly the same result as in your comment by FluentAssertions, but everything by NUnit 3.
OK, I may have misunderstood StringAssert.
More info about StringAssert in NUnit 3: github.com/nunit/docs/wiki/String-Assert
In my case, Google sent me here and I didn't know what MatchType did (updating old code). Would have been nice to get an explanation that connected MatchType and StringAssert.Contains.
-1

As it looks, a possibility does exist (and even a sharper one than the aforementioned) to provide for this functionality, albeit not in NUnit 3 itself, but in FluentAssertions (http://www.fluentassertions.com/). There, you can do things like

 Action act = () => MyDatabase.Select(p.Key);
 act.ShouldThrow<MyException>().Where(ex => ex.Message.Contains("NON_EXISTENT_KEY"));

For all my practical purposes this solves the problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.